/[winpt]/trunk/Src/wptKeyserver.cpp
ViewVC logotype

Diff of /trunk/Src/wptKeyserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2 by twoaday, Mon Jan 31 11:02:21 2005 UTC revision 276 by twoaday, Thu Dec 21 08:24:59 2006 UTC
# Line 1  Line 1 
1  /* wptKeyserver.cpp - W32 Keyserver Access  /* wptKeyserver.cpp - W32 Keyserver Access
2   *      Copyright (C) 2000-2005 Timo Schulz   *      Copyright (C) 2000-2006 Timo Schulz
3   *      Copyright (C) 2001 Marco Cunha   *      Copyright (C) 2001 Marco Cunha
4   *   *
5   * This file is part of WinPT.   * This file is part of WinPT.
6   *   *
7   * WinPT is free software; you can redistribute it and/or   * WinPT is free software; you can redistribute it and/or
8   * modify it under the terms of the GNU General Public License   * modify it under the terms of the GNU General Public License
9   * as published by the Free Software Foundation; either version 2   * as published by the Free Software Foundation; either version 2
10   * of the License, or (at your option) any later version.   * of the License, or (at your option) any later version.
11   *     *  
12   * WinPT is distributed in the hope that it will be useful,   * WinPT is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * General Public License for more details.   * General Public License for more details.
16   *   *
17   * You should have received a copy of the GNU General Public License   * You should have received a copy of the GNU General Public License
18   * along with WinPT; if not, write to the Free Software Foundation,   * along with WinPT; if not, write to the Free Software Foundation,
19   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20   */   */
21    
22  #include <windows.h>  #ifdef HAVE_CONFIG_H
23  #include <stdio.h>  #include <config.h>
24  #include <sys/stat.h>  #endif
25  #include <ctype.h>  
26    #include <windows.h>
27  #include "wptKeyserver.h"  #include <shlobj.h>
28  #include "wptErrors.h"  #include <stdio.h>
29  #include "wptTypes.h"  #include <sys/stat.h>
30  #include "wptNLS.h"  #include <ctype.h>
31  #include "wptW32API.h"  
32  #include "wptVersion.h"  #include "wptGPG.h"
33  #include "wptGPG.h"  #include "wptKeyserver.h"
34  #include "wptRegistry.h"  #include "wptErrors.h"
35    #include "wptTypes.h"
36  static char base64code[] =  #include "wptNLS.h"
37    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  #include "wptW32API.h"
38    #include "wptRegistry.h"
39  keyserver server[MAX_KEYSERVERS] = {0};  #include "wptUTF8.h"
40  static keyserver_proxy_ctx proxy = {0};  #include "wptVersion.h"
41  static const char * server_list[] = {  
42      "hkp://wwwkeys.nl.pgp.net",  
43      "hkp://wwwkeys.pl.pgp.net",  /* Map net_errno to a winsock error. */
44      "hkp://wwwkeys.at.pgp.net",  #define net_errno ((int)WSAGetLastError ())
45      "hkp://wwwkeys.ch.pgp.net",  
46      "hkp://wwwkeys.de.pgp.net",  
47      "hkp://wwwkeys.dk.pgp.net",  keyserver server[MAX_KEYSERVERS] = {0};
48      "hkp://wwwkeys.cz.pgp.net",  keyserver_proxy_s proxy = {0};
49      "hkp://wwwkeys.es.pgp.net",  static const char *server_list[] = {
50      "hkp://wwwkeys.eu.pgp.net",      "hkp://sks.keyserver.penguin.de",
51      "hkp://wwwkeys.uk.pgp.net",      "hkp://subkeys.pgp.net",
52      "hkp://wwwkeys.us.pgp.net",      "ldap://keyserver.pgp.com",
53      "hkp://gnv.us.ks.cryptnet.net",      NULL
54      "hkp://subkeys.pgp.net",  };
55      "ldap://keyserver.pgp.com",  
56      NULL  
57  };  static char  hkp_errmsg[1024];  /* Holds the error message from the server */
58  static char hkp_errmsg[1024];  static int   hkp_err = 0;       /* != 0 indicates an error occurred. */
59  static int hkp_err = 0;  
60  static u32 conf_timestamp = 0;  /* Default keyserver and port. */
61  char * default_keyserver = NULL;  char *default_keyserver = NULL;
62  unsigned short default_keyserver_port = 0;  WORD default_keyserver_port = 0;
63    
64    /* Default socket timeout (secs). */
65  static void  static size_t default_socket_timeout = 6;
66  base64_encode( const char *inputstr, char *outputstr, int maxlen )  
67  {        
68      int index = 0, temp = 0, res = 0, i = 0, inputlen = 0, len = 0;  /* Wrapper for safe memory allocation. */
69        static char*
70      inputlen = strlen (inputstr); /* fixme: check if len > maxlen */  safe_alloc (DWORD n)
71      for (i = 0; i <inputlen; i++) {  {
72          res = temp;      char *p;
73          res = (res << 8) | (inputstr[i] & 0xFF);  
74          switch (index++) {      p = new char[n+1];
75          case 0: outputstr[len++] = base64code[res >> 2 & 0x3F]; res &= 0x3; break;                  if (!p)
76          case 1: outputstr[len++] = base64code[res >> 4 & 0x3F]; res &= 0xF; break;                      BUG (0);
77          case 2: outputstr[len++] = base64code[res >> 6 & 0x3F];      memset (p, 0, n);
78                  outputstr[len++] = base64code[res & 0x3F]; res = index = 0; break;      return p;
79          }  }
80          temp = res;  
81      }  /* Basic64 encode the input @inbuf to @outbuf. */
82        static void
83      switch( index ) {  base64_encode (const char *inbuf, char *outbuf)
84      case 0: break;          {
85      case 2: outputstr[len++] = base64code[temp << 2 & 0x3F];          char base64code[] =
86              outputstr[len++] = '='; break;                  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
87      case 1: outputstr[len++] = base64code[temp << 4 & 0x3F];          int index = 0, temp = 0, res = 0;
88              outputstr[len++] = '=';      int i, inputlen, len = 0;
89              outputstr[len++] = '=';      
90      }      inputlen = strlen (inbuf);
91            for (i = 0; i < inputlen; i++) {
92      outputstr[len] = '\0';          res = temp;
93  } /* base64_encode */          res = (res << 8) | (inbuf[i] & 0xFF);
94            switch (index++) {
95            case 0:
96  static const char *              outbuf[len++] = base64code[res >> 2 & 0x3F];
97  skip_type_prefix (const char * hostname)              res &= 0x3;
98  {              break;
99      if (hostname && !strncmp (hostname, "http://", 7))          case 1:
100          hostname += 7;              outbuf[len++] = base64code[res >> 4 & 0x3F];
101      else if (hostname && !strncmp (hostname, "hkp://", 6))              res &= 0xF;
102          hostname += 6;              break;
103      else if (hostname && !strncmp (hostname, "finger://", 9))          case 2:
104          hostname += 9;              outbuf[len++] = base64code[res >> 6 & 0x3F];
105      else if (hostname && !strncmp (hostname, "ldap://", 7))              outbuf[len++] = base64code[res & 0x3F];
106          hostname += 7;              res = index = 0;
107      return hostname;              break;
108  }          }
109            temp = res;
110        }
111  static int      
112  check_hkp_response (const char *resp, int recv)      if (index == 2) {      
113  {          outbuf[len++] = base64code[temp << 2 & 0x3F];  
114      int ec, len;          outbuf[len++] = '=';
115      char *p, * end;      }
116        else if (index == 1) {
117      ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;          outbuf[len++] = base64code[temp << 4 & 0x3F];
118      if (!strstr (resp, "HTTP/1.0 200 OK")) /* http error */          outbuf[len++] = '=';
119          return ec;          outbuf[len++] = '=';
120      if (strstr (resp, "Public Key Server -- Error")      }
121          || strstr (resp, "Public Key Server -- Error")  
122          || strstr (resp, "No matching keys in database")) {      outbuf[len] = '\0';
123          p = strstr (resp, "<p>");  }
124          if (p && strlen (p) < sizeof (hkp_errmsg)) {  
125              end = strstr (p, "</p>");  
126              len = end? (end - p + 1) : strlen (p);  /* Check that the given buffer contains a valid keyserver URL
127              strncpy (hkp_errmsg, p, len);     and return the prefix length, 0 in case of an error. */
128              hkp_err = 1;  static int
129          }  check_URL (const char *buf)
130          return ec;  {
131      }      const char *proto[] = {
132      return 0;          "ldap://",
133  } /* check_hkp_response */          "http://",
134            "finger://",
135            "hkp://",
136  static int          NULL};
137  sock_getline (int fd, char *buf, int buflen, int *nbytes)      int i;
138  {  
139      char ch;      if (strlen (buf) < 7)
140      int count = 0;                return 0;
141        
142      if (nbytes)      for (i=0; proto[i] != NULL; i++) {
143          *nbytes = 0;          if (strstr (buf, proto[i]))
144      *buf = 0;              return strlen (proto[i]);
145      while (recv (fd, &ch, 1, 0) > 0) {      }
146          *buf++ = ch;      return 0;
147          count++;  }
148          if (ch == '\n' || count == (buflen - 1)) {  
149              *buf = 0;  
150              if (nbytes)  /* Skip the URL schema and return only the host part of it. */
151                  *nbytes = count;  static const char*
152              return 0;  skip_type_prefix (const char *hostname)
153          }  {
154      }      int pos;
155    
156      return -1;      if (!hostname)
157  } /* sock_getline */          return hostname;
158    
159        pos = check_URL (hostname);
160  static int      if (pos > 0)
161  sock_select( int fd )          hostname += pos;
162  {      return hostname;
163      FD_SET rfd;  }
164      timeval tv = {1, 0};  
165    /* Parse the keyserver response and extract the human
166      FD_ZERO( &rfd );     readable text passages. */
167      FD_SET( fd, &rfd );  static int
168      if( select( fd + 1, &rfd, NULL, NULL, &tv ) == SOCKET_ERROR )  parse_keyserver_error (const char *resp, char *txt, size_t txtlen)
169          return SOCKET_ERROR;  {
170      if( FD_ISSET( fd, &rfd ) )      char *p, *p2;
171          return 1;  
172      return 0;      /* If we find no 'Error' substring, we assume a success. */
173  } /* sock_select */      if (!stristr (resp, "Error"))
174            return -1;
175    
176  static int      memset (txt, 0, txtlen);
177  sock_read( int fd, char *buf, int buflen, int *nbytes )      p = strstr (resp, "\r\n\r\n");
178  {            if (!p)
179      DWORD nread;          return -1;
180      int nleft = buflen;      resp += (p-resp);
181      int rc, n = 0;      p = strstr (resp, "<h1>");
182        if (!p)
183      while (nleft > 0) {          return -1;
184          if (n >= 10)      resp += (p-resp)+strlen ("<h1>");
185              return WPTERR_WINSOCK_TIMEOUT;      p = strstr (resp, "</h1>");
186          if ( (rc = sock_select( fd )) == SOCKET_ERROR )      if (!p)
187              return SOCKET_ERROR;          return -1;
188          else if( !rc )      resp += (p-resp)+strlen ("</h1>");
189              n++;      p2 = strstr (resp, "</body>");
190          else {      if (p2 != NULL)
191              nread = recv(fd, buf, nleft, 0);          memcpy (txt, resp, (p2-resp));
192              if (nread == SOCKET_ERROR)      else {
193                  return SOCKET_ERROR;          if (!strnicmp (resp, "<p>", 3))
194              else if (!nread)              resp += 3;
195                  break;          while (resp && *resp == '\r' || *resp == '\n')
196              nleft -= nread;              resp++;
197              buf += nread;          memcpy (txt, resp, strlen (resp));
198          }            }
199      }      return 0;
200      if (nbytes)  }
201          *nbytes = buflen - nleft;  
202            
203      return 0;  /* Check that the keyserver response indicates an OK.
204  } /* sock_read */     Return 0 on success. */
205    static int
206    check_hkp_response (const char *resp, int recv)
207  static int  {
208  sock_write( int fd, const char *buf, int buflen )      int ec;
209  {  
210      DWORD nwritten;      log_debug ("check_hkp_response: '%s'\r\n", resp);
211      int nleft = buflen;      ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;
212        if (!strstr (resp, "HTTP/1.0 200 OK") &&
213      while (nleft > 0) {          !strstr (resp, "HTTP/1.1 200 OK") &&
214          nwritten = send (fd, buf, nleft, 0);          !strstr (resp, "HTTP/1.0 500 OK") &&
215          if (nwritten == SOCKET_ERROR)          !strstr (resp, "HTTP/1.1 500 OK"))
216              return SOCKET_ERROR;          return ec; /* http error */
217          nleft -= nwritten;  
218          buf += nwritten;              if (!parse_keyserver_error (resp, hkp_errmsg, DIM (hkp_errmsg)-2)) {
219      }          if (!strlen (hkp_errmsg))
220                _snprintf (hkp_errmsg, DIM (hkp_errmsg)-1,
221      return 0;                          "Unknown keyserver error");
222  } /* sock_write */          hkp_err = 1;
223            return ec;
224        }
225  void      return 0;
226  set_default_kserver (void)  }
227  {  
228      char * p = get_reg_entry_keyserver ("Default");  
229      free_if_alloc (default_keyserver);  /* Read a single line (\r\n) from a socket.
230      default_keyserver = p && *p != ' ' ? p : m_strdup (DEF_HKP_KEYSERVER);     Return 0 on success. */
231      p = get_reg_entry_keyserver ("Default_Port");  static int
232      if (p && *p) {  sock_getline (int fd, char *buf, int buflen, int *nbytes)
233          default_keyserver_port = (u16)strtoul (p, NULL, 10);  {
234          free_if_alloc (p);      char ch;
235      }      int nread = 0;      
236      else      
237          default_keyserver_port = HKP_PORT;      if (nbytes)
238  } /* set_default_kserver */          *nbytes = 0;
239        *buf = 0;
240        while (recv (fd, &ch, 1, 0) > 0) {
241  /*          *buf++ = ch;
242   * Initialize the Winsock2 interface.          nread++;
243   */          if (ch == '\r')
244  int              continue; /* remove this char. */
245  wsock_init (void)          if (ch == '\n' || nread == (buflen - 1)) {
246  {              *buf = 0;
247      WSADATA wsa;              if (nbytes)
248                    *nbytes = nread;
249      if (WSAStartup (0x202, &wsa))              return 0;
250          return WPTERR_WINSOCK_INIT;          }
251      set_default_kserver ();      }
252      return 0;  
253  } /* wsock_init */      return -1;
254    }
255    
256  /*  
257   * Should be called after the keyserver access.  /* Perform a select() on the given fd to find out
258   */     is there is data for reading. Wait at least @nsecs seconds. */
259  void  static int
260  wsock_end (void)  sock_select (int fd, int nsecs)
261  {  {
262      int i;      FD_SET rfd;
263        timeval tv = {nsecs, 0};
264      free_if_alloc (default_keyserver);  
265      default_keyserver = NULL;      FD_ZERO (&rfd);
266      for (i=0; i < MAX_KEYSERVERS; i++) {      FD_SET (fd, &rfd);
267          if (server[i].used)      if (select (fd + 1, &rfd, NULL, NULL, &tv) == SOCKET_ERROR) {
268              free_if_alloc (server[i].name);          log_debug ("sock_select: select() failed ec=%d.\r\n", net_errno);
269      }          return SOCKET_ERROR;
270      WSACleanup ();      }
271  } /* wsock_end */      if (FD_ISSET (fd, &rfd))
272            return 1;
273        return 0;
274  const char*  }
275  wsock_strerror( void )  
276  {      
277      static char buf[384];  /* Read from a socket @fd to buffer @buf with a fixed timeout
278      int ec = WSAGetLastError( );     of 10 seconds. The amount of bytes which were read are
279           returned in @nbytes.
280      switch ( ec ) {     Return value: 0 on success. */
281      case WSAENETDOWN: return _("The network subsystem has failed");      static int
282      case WSAHOST_NOT_FOUND: return _("Authoritative Answer Host not found");              sock_read (int fd, char *buf, size_t buflen, int *nbytes)
283      case WSAETIMEDOUT: return _("The connection has been dropped because of a network failure");  {
284      default: _snprintf( buf, sizeof (buf) -1, _("Unknown Winsock error ec=%d"),ec); return buf;      int nread;
285      }      size_t nleft = buflen;
286      return NULL;      size_t n = 0;
287  } /* wsock_strerror */      int rc;
288        
289        if (nbytes)
290  const char*          *nbytes = 0;
291  kserver_strerror( void )      while (nleft > 0) {
292  {                if (n >= default_socket_timeout)
293      if( hkp_err )              return WPTERR_WINSOCK_TIMEOUT;
294          return hkp_errmsg;          rc = sock_select (fd, 1);
295      return NULL;          if (rc == SOCKET_ERROR)
296  } /* kserver_strerror */              return rc;
297            else if (!rc)
298                n++;
299  const char *          else {
300  kserver_get_hostname (int idx, int type, u16 *port)              nread = recv (fd, buf, nleft, 0);
301  {              if (nread == SOCKET_ERROR) {
302      if (type == -1) {                  log_debug ("sock_read: recv() failed ec=%d.\r\n", net_errno);
303          *port = default_keyserver_port;                  return SOCKET_ERROR;
304          return default_keyserver;              }
305      }              else if (!nread)
306      else if (!type && idx < DIM (server_list)) {                  break;
307          *port = HKP_PORT;              nleft -= nread;
308          return server_list[idx];              buf += nread;
309      }          }      
310      return NULL;      }
311  }      if (nbytes)
312            *nbytes = buflen - nleft;
313            
314  int      return 0;
315  kserver_check_inet_connection (void)  }
316  {  
317      int fd;  
318    /* Helper to create a string from the gpgme data and
319      if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {     then release the gpgme data object. */
320          closesocket (fd);  char*
321          return 0;  data_release_and_get_mem (gpgme_data_t in, size_t *r_bufferlen)
322      }  {
323      return -1;      size_t n;
324  }      char *buffer, *p;
325    
326        gpg_data_putc (in, '\0');
327  /*      p = gpgme_data_release_and_get_mem (in, &n);
328   * If the request contains the keyid, it have to be      buffer = m_strdup (p);
329   * always postfix with '0x'+keyid. This code checks      if (r_bufferlen)
330   * if the keyid is a decimal value and if so if it contains          *r_bufferlen = n;
331   * the '0x'. If not it is inserted.      gpgme_free (p);
332   */      return buffer;
333  const char*  }
334  kserver_check_keyid (const char *keyid)  
335  {        
336      static char id[20];  /* Read much data as possible from the socket @fd and
337       return the data in @buffer. Caller must free data.
338      if (strstr (keyid, "@"))     Return value: 0 on success. */
339          return keyid; /* email address */  int
340      if (strncmp (keyid, "0x", 2)) {  sock_read_ext (int fd, char **buffer, size_t *r_bufferlen)
341          memset (&id, 0, sizeof (id));  {
342          _snprintf (id, sizeof (id)-1, "0x%s", keyid);      gpgme_data_t dh;
343          return id;      char buf[1024];
344      }      size_t timeout=0;
345      return keyid;      int nread, rc;
346  } /* kserver_check_keyid */  
347        if (gpgme_data_new (&dh))
348            return SOCKET_ERROR;
349  static void      while (timeout < default_socket_timeout) {
350  kserver_update_proxyuser (const char *proxy_user, const char *proxy_pass)          rc = sock_select (fd, 1);
351  {          if (rc == SOCKET_ERROR) {
352      char t[257]; /* user:pass = 127+1+127+1 = 257 */              gpgme_data_release (dh);
353                return rc;
354      free_if_alloc (proxy.base64_user);          }
355      proxy.base64_user = new char[4*strlen( proxy_user ) / 3 + 32];          else if (!rc)
356      if( !proxy.base64_user )              timeout++; /* socket not ready yet. */
357          BUG (0);          else {
358      _snprintf (t, sizeof (t)-1, "%s:%s", proxy_user, proxy_pass);              nread = recv (fd, buf, DIM (buf), 0);
359      base64_encode (t, proxy.base64_user, 257);              if (nread == SOCKET_ERROR)
360      free_if_alloc (proxy.user);                  return SOCKET_ERROR;
361      free_if_alloc (proxy.pass);              else if (!nread)
362      proxy.user = m_strdup (proxy_user);                  break;
363      proxy.pass = m_strdup (proxy_pass);              gpgme_data_write (dh, buf, nread);
364  } /* kserver_update_proxyuser */          }
365        }
366        if (timeout >= default_socket_timeout)
367  static int          return WPTERR_WINSOCK_TIMEOUT;
368  check_URL (const char * buf)      *buffer = data_release_and_get_mem (dh, r_bufferlen);
369  {      return 0;
370      if (strlen (buf) < 7)  }
371          return -1;  
372      if( !strstr (buf, "ldap://")  
373          && !strstr (buf, "http://")  /* Write the buffer @buf with the length @buflen to a socket @fd. */
374          && !strstr (buf, "finger://")  static int
375          && !strstr (buf, "hkp://"))  sock_write (int fd, const char *buf, size_t buflen)
376          return -1;  {
377      return 0;      int nwritten;
378  } /* check_URL */      int nleft = buflen;
379        
380        while (nleft > 0) {
381  static int          nwritten = send (fd, buf, nleft, 0);
382  proto_from_URL (const char * buf)          if (nwritten == SOCKET_ERROR) {
383  {              log_debug ("sock_write: send() failed ec=%d\r\n", net_errno);
384      if (strstr( buf, "ldap"))              return SOCKET_ERROR;
385          return KSPROTO_LDAP;          }
386      else if (strstr( buf, "finger"))          nleft -= nwritten;
387          return KSPROTO_FINGER;          buf += nwritten;
388      return KSPROTO_HTTP;      }
389  } /* proto_from_URL */  
390        return 0;
391    }
392  void  
393  keyserver_set_default (const char * hostname, u16 port)  
394  {  /* Initialize the Winsock2 interface.*/
395      if (hostname) {  int
396          free_if_alloc (default_keyserver);  wsock_init (void)
397          default_keyserver = m_strdup (hostname);  {
398          if (!default_keyserver)      WSADATA wsa;
399              BUG (0);  
400          default_keyserver_port = port;      if (WSAStartup (0x202, &wsa)) {
401      }          log_debug ("wsock_init: WSAStartup failed ec=%d\r\n", net_errno);
402      server[0].name =  default_keyserver;          return WPTERR_WINSOCK_INIT;
403      server[0].used = 1;      }
404      server[0].port = port;      return 0;
405      server[0].proto = proto_from_URL (default_keyserver);  }
406  } /* keyserver_set_default */  
407    
408    /* Cleanup the Winsock2 interface. */
409  static const char *  void
410  skip_whitespace (const char * str)  wsock_end (void)
411  {  {
412      while (str && *str)      char *p;
413      {      int i;
414          if (*str == ' ' ||  
415              *str == '\t' ||  #ifdef WINPT_MOBILE
416              *str == '\n' ||      p = m_strdup ("keyserver.conf");
417              *str == '\r')  #else
418          {      p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);
419              str++;  #endif
420              continue;      kserver_save_conf (p);
421          }      free_if_alloc (p);
422          break;      free_if_alloc (default_keyserver);
423      }      for (i=0; i < MAX_KEYSERVERS; i++) {
424      return str;          if (server[i].name != NULL)
425  }              free_if_alloc (server[i].name);
426        }
427        kserver_proxy_release (&proxy);
428  int      WSACleanup ();
429  kserver_load_conf (const char * conf)      log_debug ("wsock_end: cleanup finished.\r\n");
430  {  }
431      struct stat statbuf;  
432      FILE *fp;  
433      char buf[1024], * s, * p;  /* Return a string representation of a winsock error. */
434      char *user = NULL, *pass = NULL;      const char*
435      int pos, proxy_auth = 0;  wsock_strerror (void)
436      int no_config=0;  {
437            int ec = WSAGetLastError ();
438      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {      
439          server[pos].used = 0;      if (!ec)
440          server[pos].port = HKP_PORT;          return "";
441      }      switch (ec) {
442            case WSAENETDOWN:
443      fp = fopen (conf, "rb");          return _("Network unreachable");
444      if (!fp) {  
445          for( pos = 0; server_list[pos]; pos++ ) {      case WSAEHOSTUNREACH:
446              server[pos].used = 1;          return _("Host unreachable");
447              server[pos].name = (char *)server_list[pos];  
448              server[pos].proto = proto_from_URL( server_list[pos] );      case WSAHOST_NOT_FOUND:
449          }          return _("Could not resolve host name");
450          no_config=1;  
451      }      case WSAECONNREFUSED:
452      get_reg_proxy_prefs( &proxy.host, &proxy.port, &user, &pass );          return _("Connection refused");
453      if( user && pass )  
454          kserver_update_proxyuser( user, pass );      case WSAETIMEDOUT:
455      else if( user && !pass || !user && pass ) {      case WSAECONNABORTED:
456          msg_box( NULL, _("Invalid proxy configuration."          return _("Connection timeout");
457                           "You need to set a user and a password"  
458                           "to use proxy authentication!"), _("Proxy Error"), MB_ERR );      case WSAENETRESET:
459      }      case WSAECONNRESET:    
460      /* check if the host has a http:// prefix and skip it */          return _("Connection resetted by peer");
461      if( proxy.host && !strncmp( proxy.host, "http://", 7 ) ) {  
462          const char *s = proxy.host+7;      case WSAESHUTDOWN:
463          char * p = m_strdup (s);          return _("Socket has been shutdown");
464          if (!p)  
465              BUG (0);      default:
466          free_if_alloc (proxy.host);          break;
467          proxy.host = p;      }
468      }  
469      free_if_alloc (user);      return "";
470      free_if_alloc (pass);  }
471        
472      pos = 0;  
473      while( fp && !feof( fp ) ) {  /* Set default socket timeout for all reading operations. */
474          s = fgets (buf, sizeof (buf)-1, fp);  void
475          if (!s)  kserver_set_socket_timeout (size_t nsec)
476              break;  {
477          if (strstr (buf, "\r\n"))      if (nsec < 0 || nsec > 3600)
478              buf[strlen (buf)-2] = '\0';          nsec = 0;
479          if (strstr (buf, "\n"))      default_socket_timeout = nsec;
480              buf[strlen (buf)-1] = '\0';  }
481          s = (char *)skip_whitespace (buf);  
482          if (*s == '#' || strlen (s) < 7)  
483              continue;  /* Return the last keyserver error as a string. */
484          if (check_URL (s)) {  const char*
485              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"  kserver_strerror (void)
486                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),  {      
487                               _("Keyserver Error"), MB_ERR);      if (hkp_err)
488              continue;          return hkp_errmsg;
489          }      return NULL;
490          p = strchr (s+6, ':');  }
491          server[pos].used = 1;  
492          server[pos].proto = proto_from_URL (s);  
493          if (!p)  /* Read a keyserver from the list at index @idx.
494              server[pos].name = m_strdup (s);     Return value: keyserver name at the given position. */
495          else {        const char*
496              server[pos].port = atol (p+1);  kserver_get_hostname (int idx, int type, WORD *port)
497              if (server[pos].port < 0 || server[pos].port > 65536)  {
498                  server[pos].port = HKP_PORT;      if (type == -1) {
499              server[pos].name = new char [(p-s)+2];          *port = default_keyserver_port;
500              if (!server[pos].name)          return default_keyserver;
501                  BUG (0);      }
502              memset (server[pos].name, 0, (p-s)+2);      else if (!type && (size_t)idx < DIM (server_list)) {
503              memcpy (server[pos].name, s, (p-s));          /* XXX: handle non HKP servers. */
504          }          *port = HKP_PORT;
505          pos++;          return server_list[idx];
506          if (pos > MAX_KEYSERVERS)      }
507          {      return NULL;
508              msg_box (NULL, _("The keyserver limit is exceeded"), _("Keyserver Warning"), MB_INFO);  }
509              break;  
510          }  
511      }  /* Check if the computer is connected to the internet.
512      if (fp)     Return 0 on success -1 otherwise. */
513          fclose (fp);  int
514      if (!pos)  kserver_check_inet_connection (void)
515      {  {
516          /* only issue an error if the config file exist but it has no valid entries. */      int fd;
517          keyserver_set_default (NULL, HKP_PORT);  
518          if (!no_config)      if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {
519              return WPTERR_CONFIG_FILE;            closesocket (fd);
520      }          return 0;
521        }
522      if (!stat (conf, &statbuf))      log_debug ("kserver_check_inet_connection: no inet connection.\r\n");
523          conf_timestamp = statbuf.st_mtime;      return -1;
524      return 0;  }
525  } /* kserver_load_conf */  
526    
527    /* If the request contains the keyid, it have to be
528  const char *     always postfix with '0x'+keyid. This code checks
529  kserver_get_proxy (int * r_port)     if the keyid is a decimal value and if so if it contains
530  {     the '0x'. If not it is inserted. */
531      if (proxy.host)  const char*
532      {  kserver_check_keyid (const char *keyid)
533          if (r_port)  {      
534              *r_port = proxy.port;      static char id[22];
535          return proxy.host;  
536      }      if (strstr (keyid, "@"))
537      return NULL;          return keyid; /* email address */
538  } /* kserver_get_proxy */      if (strncmp (keyid, "0x", 2)) {
539            memset (&id, 0, sizeof (id));
540            _snprintf (id, DIM (id)-1, "0x%s", keyid);
541  const char *          return id;
542  kserver_get_proxy_info( int id )      }
543  {      return keyid;
544      switch( id ) {    }
545      case PROXY_USER: return proxy.user;  
546      case PROXY_PASS: return proxy.pass;  
547      }  /* Update the keyserver proxy user. */
548      return NULL;  static void
549  } /* kserver_get_proxy_info */  update_proxy_user (const char *proxy_user, const char *proxy_pass)
550    {
551        char t[257]; /* user:pass = 127+1+127+1 = 257 */
552  /*      int n = 0;
553   * Connect to the keyserver 'hostname'.  
554   * We always use the HKP port.      n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;
555   */      free_if_alloc (proxy.base64_user);
556  int      proxy.base64_user = safe_alloc (n+1);
557  kserver_connect (const char *hostname, u16 port, int *conn_fd)      _snprintf (t, DIM (t)-1, "%s:%s", proxy_user, proxy_pass);
558  {      base64_encode (t, proxy.base64_user);
559      int rc, fd;      free_if_alloc (proxy.user);
560      u32 iaddr;      free_if_alloc (proxy.pass);
561      char host[128] = {0};      proxy.user = m_strdup (proxy_user);
562      struct hostent *hp;      proxy.pass = m_strdup (proxy_pass);
563      struct sockaddr_in sock;  }
564        
565      if (debug)  
566          log_f ("kserver_connect: %s:%d\r\n", hostname, port);  /* Get the port number from the given protocol. */
567      if (!port)  static int
568          port = HKP_PORT;  port_from_proto (int proto)
569      if (conn_fd)  {
570          *conn_fd = 0;      switch (proto) {
571      hostname = skip_type_prefix (hostname);      case KSPROTO_LDAP:   return LDAP_PORT;
572            case KSPROTO_FINGER: return FINGER_PORT;
573      memset (&sock, 0, sizeof (sock));      case KSPROTO_HTTP:   return HKP_PORT;
574      sock.sin_family = AF_INET;      }
575      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);      return 0;
576      if (proxy.host)  }
577          strncpy (host, proxy.host, 127);  
578      else  
579          strncpy (host, hostname, 127);  /* Get the port number from the given URL. */
580        static int
581      if ((iaddr = inet_addr (host)) != INADDR_NONE)  proto_from_URL (const char *buf)
582          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));  {
583      else if ((hp = gethostbyname (host))) {      if (strstr (buf, "ldap"))
584          if (hp->h_addrtype != AF_INET)          return KSPROTO_LDAP;
585              return WPTERR_WINSOCK_RESOLVE;      else if (strstr (buf, "finger"))
586          else if (hp->h_length != 4)          return KSPROTO_FINGER;
587              return WPTERR_WINSOCK_RESOLVE;      return KSPROTO_HKP;
588          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);  }
589      }  
590      else {  
591          if (debug)  /* Set the default keyserver.
592              log_f ("gethostbyname: failed.\r\n");     If @hostname is NULL, use the predefined keyserver. */
593          return WPTERR_WINSOCK_RESOLVE;  void
594      }  keyserver_set_default (const char *hostname, WORD port)
595      fd = socket (AF_INET, SOCK_STREAM, 0);  {
596      if (fd == INVALID_SOCKET)        if (!port)
597          return WPTERR_WINSOCK_SOCKET;          port = HKP_PORT;
598      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));      if (hostname != NULL) {
599      if (rc == SOCKET_ERROR) {          free_if_alloc (default_keyserver);
600          if (debug)          default_keyserver = m_strdup (hostname);
601              log_f ("connect: failed.\r\n");          default_keyserver_port = port;
602          closesocket(fd);      }
603          return WPTERR_WINSOCK_CONNECT;      if (!default_keyserver) {
604      }          default_keyserver = m_strdup (DEF_HKP_KEYSERVER);
605            default_keyserver_port = HKP_PORT;
606      if (conn_fd)      }
607          *conn_fd = fd;      server[0].name =  m_strdup (default_keyserver);
608      WSASetLastError(0);      server[0].used = 1;
609      return 0;      server[0].port = port;
610  } /* kserver_connect */      server[0].proto = proto_from_URL (default_keyserver);
611    }
612    
613  static char*  
614  kserver_urlencode (const char *pubkey, int octets, int *newlen)  /* Skip all kind of whitespace chars in @str. */
615  {  static const char*
616      char *p, numbuf[5];  skip_whitespace (const char *str)
617      size_t j = 0;  {
618      int i, size;      while (str && *str) {
619                if (*str == ' ' ||
620      p = new char [2*octets];              *str == '\t' ||
621      if (!p)              *str == '\n' ||
622          BUG (0);              *str == '\r') {
623                str++;
624      for (size=0, i=0; i<octets; i++) {              continue;
625          if (isalnum (pubkey[i]) || pubkey[i] == '-') {          }
626              p[size] = pubkey[i];          break;
627              size++;      }
628          }      return str;
629          else if (pubkey[i] == ' ') {  }
630              p[size] = '+';  
631              size++;  
632          }  /* Save the keyserver config file in @conf. */
633          else {  int
634              sprintf(numbuf, "%%%02X", pubkey[i]);  kserver_save_conf (const char *conf)
635              for (j = 0; j<strlen(numbuf); j++) {  {
636                  p[size] = numbuf[j];      FILE *fp;
637                  size++;      int pos;
638              }  
639          }      fp = fopen (conf, "wb");
640      }      if (!fp) {
641      p[size] = '\0';          msg_box (NULL, _("Could not save keyserver.conf file"),
642      *newlen = size;                   _("Keyserver"), MB_ERR);
643      return p;          return -1;
644  } /* kserver_urlencode */      }
645    
646        fprintf (fp, "# do NOT manually modify this file, it will be "
647  /*                   "generated automatically!!\r\n");
648   * Format a request for the given keyid (send).      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
649   */          if (!server[pos].used)
650  static char*              continue;
651  kserver_send_request (const char *hostname, u16 port, const char *pubkey, int octets)          fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
652  {      }
653      char *request = NULL, *enc_pubkey = NULL;      fclose (fp);
654      int reqlen, enc_octets;      return 0;
655        }
656      if (debug)  
657          log_f ("kserver_send_request: %s:%d\n", hostname, port);  
658      if (!port)  /* Return the specified keyserver config setting @key as an integer. */
659          port = HKP_PORT;  static int
660      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);  get_conf_kserver_int (const char *key)
661      request = new char[reqlen];  {
662      if (!request)      char *p;
663          BUG (0);      int val = 0;
664      enc_pubkey = kserver_urlencode (pubkey, octets, &enc_octets);  
665      if (!enc_pubkey || !enc_octets) {      p = get_reg_entry_keyserver (key);
666          free_if_alloc (request);      if (p && *p)
667          return NULL;          val = atoi (p);
668      }      free_if_alloc (p);
669            return val;
670      if (proxy.user) {  }
671          _snprintf (request, reqlen-1,  
672                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"  
673                     "Referer: \r\n"  /* Read the proxy configuration and store it into @prox. */
674                     "User-Agent: WinPT/W32\r\n"  static void
675                     "Host: %s:%d\r\n"  read_proxy_config (keyserver_proxy_t prox)
676                     "Proxy-Authorization: Basic %s\r\n"  {
677                     "Content-type: application/x-www-form-urlencoded\r\n"      char *proto;
678                     "Content-length: %d\r\n"  
679                     "\r\n"      if (!prox)
680                     "keytext=%s"          return;
681                     "\n",      
682                     skip_type_prefix (hostname), port, hostname, port,      proto = get_reg_entry_keyserver("Proto");
683                     proxy.base64_user, enc_octets+9, enc_pubkey);      if (proto != NULL && strlen (proto) > 0)
684      }          prox->proto = atoi (proto);
685      else {      else
686          _snprintf (request, reqlen-1,          prox->proto = PROXY_PROTO_NONE;
687                     "POST /pks/add HTTP/1.0\r\n"      free_if_alloc (proto);
688                     "Referer: \r\n"      free_if_alloc (prox->host);
689                     "User-Agent: WinPT/W32\r\n"      prox->host = get_reg_entry_keyserver ("Host");
690                     "Host: %s:%d\r\n"      free_if_alloc (prox->user);
691                     "Content-type: application/x-www-form-urlencoded\r\n"      prox->user = get_reg_entry_keyserver ("User");
692                     "Content-length: %d\r\n"      free_if_alloc (prox->pass);
693                     "\r\n"      prox->pass = get_reg_entry_keyserver ("Pass");
694                     "keytext=%s"      prox->port = get_conf_kserver_int ("Port");
695                     "\n",  }
696                     skip_type_prefix (hostname), port, enc_octets+9, enc_pubkey);  
697      }  
698      free_if_alloc (enc_pubkey);  /* Load the keyserver config file @conf. */
699      if (debug)  int
700          log_f("%s\n", request);  kserver_load_conf (const char *conf)
701      return request;  {    
702  } /* kserver_send_request */      FILE *fp;
703        char buf[1024], *s, *p;
704        char *user = NULL, *pass = NULL;    
705  /*      int no_config=0, chk_pos;
706   * Interface receiving a public key.      int pos;
707   */      
708  int      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
709  kserver_recvkey (const char *hostname, u16 port, const char *keyid, char *key, int maxkeylen)          server[pos].used = 0;
710  {                server[pos].port = HKP_PORT;
711      int rc, n;          server[pos].name = NULL;
712      int conn_fd;      }
713      char *request = NULL;      
714            fp = fopen (conf, "rb");
715      if (!port)      if (!fp) {
716          port = HKP_PORT;          for (pos = 0; server_list[pos]; pos++) {
717      hkp_err = 0; /* reset */                  server[pos].used = 1;
718      rc = kserver_connect (hostname, port, &conn_fd);              server[pos].name = m_strdup (server_list[pos]);
719      if (rc)              server[pos].proto = proto_from_URL (server_list[pos]);
720          goto leave;          }
721                no_config = 1;
722      request = new char[300+1];      }
723      if (!request)      read_proxy_config (&proxy);
724          BUG (0);      if (user && pass)
725                update_proxy_user (user, pass);
726      if (proxy.host && proxy.user) {      else if (user && !pass || !user && pass) {
727          _snprintf (request, 300,          msg_box (NULL, _("Invalid proxy configuration. "
728              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"                           "You need to set a user and a password "
729              "Proxy-Authorization: Basic %s\r\n\r\n",                           "to use proxy authentication!"),
730              skip_type_prefix (hostname), port, keyid, proxy.base64_user);                           _("Proxy Error"), MB_ERR);
731      }      }
732      else if (proxy.host) {      /* check if the host has a http:// prefix and skip it */
733          _snprintf (request, 300,      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
734              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",          char *host = m_strdup (proxy.host+7);
735              skip_type_prefix (hostname), port, keyid);          free_if_alloc (proxy.host);
736      }              proxy.host = host;
737      else {      }
738          _snprintf (request, 300,      free_if_alloc (user);
739              "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);      free_if_alloc (pass);
740      }        
741      if (debug)      pos = 0;
742          log_f ("%s\n", request);      while (fp && !feof (fp)) {
743                s = fgets (buf, DIM (buf)-1, fp);
744      rc = sock_write (conn_fd, request, strlen (request));          if (!s)
745      if (rc == SOCKET_ERROR) {              break;
746          rc = WPTERR_WINSOCK_RECVKEY;          if (strstr (buf, "\r\n"))
747          goto leave;              buf[strlen (buf)-2] = '\0';
748      }          if (strstr (buf, "\n"))
749                    buf[strlen (buf)-1] = '\0';
750      rc = sock_read( conn_fd, key, maxkeylen, &n );          s = (char *)skip_whitespace (buf);
751      if( rc == SOCKET_ERROR ) {          if (*s == '#' || strlen (s) < 7)
752          rc = WPTERR_WINSOCK_RECVKEY;              continue;
753          goto leave;          chk_pos = check_URL (s);
754      }          if (!chk_pos) {
755                    msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
756      if( debug )                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
757          log_f("%s\n", key);                               _("Keyserver Error"), MB_ERR);
758                    continue;
759      rc = check_hkp_response( key, 1 );          }
760      if( rc )          p = strchr (s+chk_pos, ':');
761          goto leave;          server[pos].used = 1;
762                server[pos].proto = proto_from_URL (s);
763      WSASetLastError( 0 );          server[pos].port = port_from_proto (server[pos].proto);
764                if (!p)
765  leave:              server[pos].name = m_strdup (s);
766      closesocket( conn_fd );          else {      
767      free_if_alloc( request );              server[pos].port = atol (p+1);
768      return rc;              if (server[pos].port < 0 || server[pos].port > 65536)
769  } /* kserver_recvkey */                  server[pos].port = HKP_PORT;
770                server[pos].name = safe_alloc ((p-s)+2);
771                memset (server[pos].name, 0, (p-s)+2);
772  /*              memcpy (server[pos].name, s, (p-s));
773   * Interface to send a public key.          }
774   */          pos++;
775  int          if (pos > MAX_KEYSERVERS) {
776  kserver_sendkey (const char *hostname, u16 port, const char *pubkey, int len )              msg_box (NULL, _("The keyserver limit is exceeded"),
777  {                       _("Keyserver Warning"), MB_INFO);
778      int n, rc;              break;
779      int conn_fd;          }
780      char *request = NULL;      }
781      char log[2048];      if (fp)
782                fclose (fp);
783      hkp_err = 0; /* reset */      if (!pos) {
784      rc = kserver_connect (hostname, port, &conn_fd);          /* Only issue an error if the config file exist but
785      if (rc)             it has no valid entries. */
786          goto leave;          keyserver_set_default (NULL, HKP_PORT);
787                if (!no_config)
788      request = kserver_send_request (hostname, port, pubkey, len);              return WPTERR_CONFIG_FILE;
789      if( request == NULL ) {      }
790          rc = WPTERR_GENERAL;  
791          goto leave;          return 0;
792      }  }
793        
794      rc = sock_write( conn_fd, request, lstrlen(request) );  
795      if( rc == SOCKET_ERROR ) {  /* Connect to the keyserver @hostname (port @port).
796          rc = WPTERR_WINSOCK_SENDKEY;     Return value: 0 on success */
797          goto leave;      int
798      }  kserver_connect (const char *hostname, WORD port, int *conn_fd)
799        {        
800      rc = sock_read( conn_fd, log, sizeof (log)-1, &n );      struct hostent *hp;
801      if( rc == SOCKET_ERROR ) {      struct sockaddr_in sock;
802          rc = WPTERR_WINSOCK_SENDKEY;      char host[128] = {0};
803          goto leave;      DWORD iaddr;
804      }      bool use_proxy = proxy.host != NULL;
805      if (debug)      int rc, fd;
806          log_f("%s\n", log);  
807            if (!port)
808      rc = check_hkp_response( log, 0 );          port = HKP_PORT;
809      if( rc )      if (conn_fd)
810          goto leave;          *conn_fd = 0;
811            hostname = skip_type_prefix (hostname);
812      WSASetLastError( 0 );      log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
813            
814  leave:      if (use_proxy && proxy.proto == PROXY_PROTO_HTTP)
815      closesocket( conn_fd );          port = proxy.port;
816      free_if_alloc( request );      memset (&sock, 0, sizeof (sock));
817      return rc;      sock.sin_family = AF_INET;
818  } /* kserver_sendkey */      sock.sin_port = htons (port);
819        strncpy (host, use_proxy? proxy.host : hostname, DIM (host)-1);
820    
821  int      if ((iaddr = inet_addr (host)) != INADDR_NONE)
822  kserver_search_init (const char * hostname, u16 port, const char * keyid, int * conn_fd)          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
823  {      else if ((hp = gethostbyname (host))) {
824      int rc, sock_fd;          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
825      char * request = NULL;              log_debug ("gethostbyname: unknown address type.\r\n");
826                    return WPTERR_WINSOCK_RESOLVE;
827      rc = kserver_connect (hostname, port, &sock_fd);          }
828      if (rc) {          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
829          *conn_fd = 0;      }
830          goto leave;      else {
831      }          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
832                return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_RESOLVE;
833      request = new char[300+1];      }
834      if (!request)      fd = socket (AF_INET, SOCK_STREAM, 0);
835          BUG (0);      if (fd == INVALID_SOCKET)  
836                return WPTERR_WINSOCK_SOCKET;
837      if (proxy.host && proxy.user) {      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
838          _snprintf (request, 300,      if (rc == SOCKET_ERROR) {
839              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"          log_debug ("connect: failed ec=%d.\r\n", net_errno);
840              "Proxy-Authorization: Basic %s\r\n\r\n",          closesocket (fd);
841              skip_type_prefix (hostname), port, keyid, proxy.base64_user);          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_CONNECT;
842      }          }
843      else if (proxy.host) {  
844          _snprintf (request, 300,      if (proxy.proto == PROXY_PROTO_SOCKS5) {
845              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",          /* XXX: finish code and provide errors constants. */
846              skip_type_prefix (hostname), port, keyid);          rc = socks_handshake (&proxy, fd, hostname, port);
847      }          if (rc) {
848      else {              closesocket (fd);
849          _snprintf (request, 300,              return WPTERR_GENERAL;
850                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n", keyid);          }
851      }      }
852        
853      if (debug)      if (conn_fd)
854          log_f("%s\n", request);          *conn_fd = fd;
855            WSASetLastError (0);
856      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {      return 0;
857          rc = WPTERR_GENERAL;  }
858          goto leave;  
859      }  
860        /* Check if the URL needs to be encoded or not. */
861      *conn_fd = sock_fd;  static bool
862        URL_must_encoded (const char *url)
863  leave:  {
864      free_if_alloc (request);      if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
865      return rc;          return true;
866  } /* kserver_search_init */      return false;
867    }
868    
869  int  
870  kserver_search_chkresp (int fd)  /* Perform URL encoding of the given data. */
871  {  static char*
872      char buf[128];  URL_encode (const char *url, DWORD ulen, DWORD *ret_nlen)
873      int n=0, i=0;  {
874        gpgme_data_t hd;
875      /* parse response 'HTTP/1.0 500 OK' */      char numbuf[5], *p;
876      if (sock_getline (fd, buf, 127, &n))      size_t i, nlen;
877          return WPTERR_KEYSERVER_NOTFOUND;  
878      if (strncmp (buf, "HTTP/1.", 7))      if (gpgme_data_new (&hd))
879          return WPTERR_KEYSERVER_NOTFOUND;          BUG (0);
880      i = 8+1;      for (i=0; i < ulen; i++) {
881      if (strncmp (buf+i, "200", 3))          if (isalnum (url[i]) || url[i] == '-')
882          return WPTERR_KEYSERVER_NOTFOUND;              gpg_data_putc (hd, url[i]);
883      return 0;          else if (url[i] == ' ')
884  } /* kserver_search_chkresp */              gpg_data_putc (hd, '+');
885            else {
886                sprintf (numbuf, "%%%02X", url[i]);
887  int              gpgme_data_write (hd, numbuf, strlen (numbuf));
888  kserver_search (int fd, keyserver_key * key)          }
889  {      }
890      char buf[1024], *p;  
891      int uid_len, nbytes, pos = 0;      p = data_release_and_get_mem (hd, &nlen);
892            if (ret_nlen)
893      if (debug)          *ret_nlen = nlen;
894          log_f ("keyserver_search:\n");      return p;
895        }
896      if (sock_getline (fd, buf, sizeof (buf), &nbytes))      
897          return WPTERR_GENERAL;  
898        /* Format a request for the given keyid (send). */
899      if (debug)  static char*
900          log_f ("%s\n", buf);  kserver_send_request (const char *hostname, WORD port,
901                              const char *pubkey, DWORD octets)
902      if (!strncmp (buf, "pub", 3)) {  {
903          key->bits = atol (buf+3);      const char *fmt;
904          p = strchr (buf, '>');      char *request;
905          if (p)      char *enc_pubkey;
906              pos = p-buf+1;      DWORD enc_octets;
907          memcpy (key->keyid, buf+pos, 8);      int reqlen;
908          key->keyid[8] = '\0';  
909          p = strstr (buf, "</a>");      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
910          if (p)  
911              pos = p-buf+5;      if (!port)
912          memcpy (key->date, buf+pos, 10);          port = HKP_PORT;
913          key->date[10] = '\0';      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
914          pos += 10;      reqlen = 2*strlen (hostname) + 2*32/*port*/ + enc_octets + 32 /*len*/ + 1;
915          p = buf+pos+1;      
916          while (p && *p != '>')      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
917              p++;          fmt = "POST http://%s:%d/pks/add HTTP/1.0\r\n"
918          p++;                "Referer: \r\n"
919          uid_len = strlen (p) - 10;                "User-Agent: WinPT/W32\r\n"
920          memcpy (key->uid, p, uid_len);                "Host: %s:%d\r\n"
921          key->uid[uid_len] = '\0';                "Proxy-Authorization: Basic %s\r\n"
922          strcat (key->uid, ">");                "Content-type: application/x-www-form-urlencoded\r\n"
923          p = strchr (key->uid, '&');                "Content-length: %d\r\n"
924          if (p) {                "\r\n"
925              key->uid[(p-key->uid)] = '<';                "keytext=%s"
926              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4, strlen (key->uid)-3);                "\r\n";
927          }          reqlen += strlen (fmt) + strlen (proxy.base64_user) + 1;
928      }          request = safe_alloc (reqlen+1);
929      else {          _snprintf (request, reqlen, fmt,
930          key->bits = 0;                     skip_type_prefix (hostname), port, hostname, port,
931          memset (key, 0, sizeof *key);                     proxy.base64_user, enc_octets+9, enc_pubkey);
932      }      }
933            else {
934      return 0;          fmt = "POST /pks/add HTTP/1.0\r\n"
935  } /* kserver_search */                "Referer: \r\n"
936                  "User-Agent: WinPT/W32\r\n"
937                  "Host: %s:%d\r\n"
938  static int                "Content-type: application/x-www-form-urlencoded\r\n"
939  add_node( keyserver_cfgfile *cfg, const char *entry )                "Content-length: %d\r\n"
940  {                "\r\n"
941      keyserver_node *node;                "keytext=%s"
942      char *p = NULL;                "\r\n";
943                reqlen += strlen (fmt)+1;
944      p = strchr( entry, '=' );          request = safe_alloc (reqlen+1);
945      if( p == NULL )          _snprintf (request, reqlen, fmt,
946          return WPTERR_GENERAL;                       skip_type_prefix (hostname), port,
947      node = new keyserver_node;                     enc_octets+9, enc_pubkey);
948      if( !node )      }
949          BUG( NULL );  
950            free_if_alloc (enc_pubkey);
951      memset( node, 0, sizeof *node );      log_debug ("request:\r\n%s\r\n", request);
952      node->used = 1;      return request;
953        }
954      node->host.used = 1;  
955      node->host.proto = proto_from_URL( entry );  
956      memcpy( node->host.name, entry+7, p-entry-7 );  /* Interface for receiving a public key. */
957      node->next = cfg->list;  int
958      cfg->list = node;  kserver_recvkey (const char *hostname, WORD port, const char *keyid,
959                         char **r_key, size_t *r_keylen)
960      return 0;  {
961  } /* add_node */      const char *fmt;
962        char *request = NULL;
963        int conn_fd;
964  void      int rc, reqlen;
965  kserver_change_proxy( keyserver_proxy_ctx *ctx )  
966  {          if (!port)
967      proxy.port = ctx->port;          port = HKP_PORT;
968      free_if_alloc (proxy.host);      hkp_err = 0; /* reset */
969      proxy.host = ctx->host? m_strdup( ctx->host ) : NULL;      rc = kserver_connect (hostname, port, &conn_fd);
970      free_if_alloc( proxy.pass );      if (rc)
971      proxy.pass = ctx->pass? m_strdup( ctx->pass ) : NULL;          goto leave;
972      free_if_alloc( proxy.user );  
973      proxy.user = ctx->user? m_strdup( ctx->user ) : NULL;      reqlen = strlen (hostname)+32+strlen (keyid)+1;
974      set_reg_proxy_prefs( proxy.host, proxy.port, proxy.user, proxy.pass );      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
975  } /* kserver_change_proxy */          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"
976                  "Proxy-Authorization: Basic %s\r\n\r\n";
977            reqlen =+ strlen (fmt) + strlen (proxy.base64_user)+1;
978  int          request = safe_alloc (reqlen+1);
979  kserver_read_config( const char *fname, keyserver_cfgfile **ret_cfg )          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
980  {                     keyid, proxy.base64_user);
981      FILE *fp;      }
982      keyserver_cfgfile *cfg;      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
983      char buf[256];          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
984      int rc = 0;          reqlen += strlen (fmt)+1;
985                request = safe_alloc (reqlen+1);
986      *ret_cfg = NULL;          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname),
987      fp = fopen( fname, "rb" );                                           port, keyid);
988      if( fp == NULL )      }
989          return WPTERR_FILE_OPEN;      else {
990                fmt = "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
991      cfg = new keyserver_cfgfile;          reqlen += strlen (fmt)+1;
992      if ( !cfg )          request = safe_alloc (reqlen+1);
993          BUG( NULL );          _snprintf (request, reqlen, fmt, keyid);
994      memset( cfg, 0, sizeof *cfg );      }
995        
996      while ( !feof( fp ) ) {      log_debug ("request:\r\n%s\r\n", request);
997          if ( fgets( buf, sizeof(buf)-1, fp ) == NULL )      
998              break;      rc = sock_write (conn_fd, request, strlen (request));
999          if ( *buf == '\r' || *buf == '\n' || *buf == '#' )      if (rc == SOCKET_ERROR) {
1000              continue;          rc = WPTERR_WINSOCK_RECVKEY;
1001          buf[strlen(buf) -2] = '\0';          goto leave;
1002          if ( !strncmp( buf, "use_proxy=", 10 ) ) {      }
1003              char *p = strchr(buf, ':');      
1004              if (!p)      rc = sock_read_ext (conn_fd, r_key, r_keylen);
1005                  continue;      if (rc == SOCKET_ERROR) {
1006              cfg->proxy.port = atol( buf+(p-buf+1) );          rc = WPTERR_WINSOCK_RECVKEY;
1007              buf[p-buf] = '\0';          goto leave;
1008              cfg->proxy.host = m_strdup( buf+10 );      }
1009          }  
1010          else if ( !strncmp( buf, "proxy_user=", 11 ) )      log_debug ("response:\r\n%s\r\n", *r_key);
1011              cfg->proxy.user = m_strdup( buf+11 );      rc = check_hkp_response (*r_key, 1);
1012          else if ( !strncmp( buf, "proxy_pass=", 11 ) )      if (rc)
1013              cfg->proxy.pass = m_strdup( buf+11 );          goto leave;
1014          if ( !strncmp( buf, "http://", 7 )      
1015              || !strncmp( buf, "hkp://", 6 )      WSASetLastError (0);
1016              || !strncmp( buf, "ldap://", 7 ) ) {      
1017              add_node( cfg, buf );  leave:
1018              cfg->nlist++;      closesocket (conn_fd);
1019          }      free_if_alloc (request);
1020      }      return rc;
1021        }
1022      fclose( fp );  
1023      *ret_cfg = cfg;  
1024        /* Interface to send a public key. */
1025      return rc;  int
1026  } /* kserver_read_config */  kserver_sendkey (const char *hostname, WORD port,
1027                     const char *pubkey, size_t len)
1028    {
1029  int      char *request = NULL;
1030  kserver_write_config( const char * fname, keyserver_cfgfile * cfg )      char log[2048] = {0};
1031  {      int conn_fd, n;
1032            int rc;
1033      return 0;      
1034  }      hkp_err = 0; /* reset */
1035        rc = kserver_connect (hostname, port, &conn_fd);
1036        if (rc)
1037  void          goto leave;
1038  kserver_cfgfile_release( keyserver_cfgfile *cfg )      
1039  {            request = kserver_send_request (hostname, port, pubkey, len);
1040      keyserver_node *k, *k2;      rc = sock_write (conn_fd, request, strlen (request));
1041        if (rc == SOCKET_ERROR) {
1042      proxy_release( &cfg->proxy );          rc = WPTERR_WINSOCK_SENDKEY;
1043      for( k = cfg->list; cfg->nlist--; k = k2 ) {          goto leave;    
1044          k2 = k->next;      }
1045          free_if_alloc( k );          
1046      }      rc = sock_read (conn_fd, log, DIM (log)-1, &n);
1047      free_if_alloc( cfg );      if (rc == SOCKET_ERROR) {
1048  } /* kserver_cfgfile_release */          rc = WPTERR_WINSOCK_SENDKEY;
1049            goto leave;
1050        }
1051  void  
1052  proxy_release( keyserver_proxy_ctx *ctx )      log_debug ("kserver_sendkey: read %d bytes\r\n%s\r\n", n, log);
1053  {      rc = check_hkp_response (log, 0);
1054      free_if_alloc( ctx->host );      if (rc)
1055      free_if_alloc( ctx->pass );          goto leave;
1056      free_if_alloc( ctx->user );      
1057  } /* proxy_release */      WSASetLastError (0);
1058    
1059    leave:
1060  int      closesocket (conn_fd);
1061  ldap_recvkey (const char * host, const char * keyid, char * key, int maxkeylen)      free_if_alloc (request);
1062  {      return rc;
1063      const char *s;  }
1064      char *ksprg = NULL, *p = NULL;  
1065      char temp[512], outf[512];  
1066      FILE * inp;  /* Check keyserver response. */
1067      int rc, start_key = 0;  static int
1068      STARTUPINFO si;  kserver_search_chkresp (int fd)
1069      PROCESS_INFORMATION pi;  {
1070        char buf[128];
1071      p = get_gnupg_path ();      int n=0;
1072      ksprg = new char[strlen (p) + 1 + 128];      
1073      if (!ksprg)      /* parse response 'HTTP/1.0 500 OK' */
1074          BUG (0);      if (sock_getline (fd, buf, DIM (buf)-1, &n))
1075      strcpy (ksprg, p);          return WPTERR_KEYSERVER_NOTFOUND;
1076      strcat (ksprg, "\\");  
1077      strcat (ksprg, "gpgkeys_ldap.exe");      log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1078      free_if_alloc (p);      if (strncmp (buf, "HTTP/1.", 7))
1079      if (file_exist_check (ksprg)) {          return WPTERR_KEYSERVER_NOTFOUND;
1080          log_box ( "LDAP Keyserver Plugin", MB_ERR, "Could not find LDAP keyserver module!");      if (strncmp (buf+(8+1), "200", 3))
1081          rc = -1;          return WPTERR_KEYSERVER_NOTFOUND;
1082          goto leave;      return 0;
1083      }  }
1084      GetTempPath (sizeof (temp)-1, temp);  
1085      strcpy (outf, temp);  
1086      strcat (outf, keyid);  /* End the keyserver search procedure. */
1087      strcat (outf, ".out");  void
1088      strcat (temp, keyid);  kserver_search_end (int conn_fd)
1089      inp = fopen (temp, "w+b");  {
1090      if( !inp ) {      log_debug ("kserver_search_end: fd=%d\r\n", conn_fd);
1091          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", temp,      closesocket (conn_fd);
1092                   winpt_strerror (WPTERR_FILE_OPEN));  }
1093          rc = -1;  
1094          goto leave;  
1095      }  /* Extract the amount of keys from the info record. */
1096      fprintf (inp,  static size_t
1097          "VERSION 0\n"  count_keys_in_response (char *buf)
1098          "HOST %s\n"  {
1099          "OPTION verbose\n"      char *p;
1100          "COMMAND GET\n"      int recno = 0;
1101          "\n"      size_t n = 0;
1102          "%s\n", host? skip_type_prefix (host): "64.94.85.200", keyid);  
1103      fclose (inp);      /* info:1:4 */
1104        if (strncmp (buf, "info", 4))
1105      memset (&si, 0, sizeof (si));          return 0;
1106      si.cb = sizeof (si);      p = strtok (buf, ":");
1107      si.dwFlags = STARTF_USESHOWWINDOW;      while (p != NULL) {
1108      si.wShowWindow = SW_HIDE;          recno++;
1109      memset (&pi, 0, sizeof (pi));          if (recno == 3)
1110      p = new char[strlen (ksprg) + strlen (temp) + strlen (outf) + 32];              n = atoi (p);
1111      sprintf (p, "%s -o %s %s", ksprg, outf, temp);          p = strtok (NULL, ":");
1112      rc = CreateProcess (NULL, p, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);      }
1113      if (!rc) {      return n;
1114          log_box ("LDAP Keyserver Plugin", MB_ERR, "Could not spawn process");  }
1115          rc = -1;  
1116          goto leave;  
1117      }  /* Start the keyserver search.
1118      CloseHandle (pi.hThread);     Connect to host @hostname and port @port.
1119      WaitForSingleObject (pi.hProcess, INFINITE);     The pattern are given in @pattern.
1120      CloseHandle (pi.hProcess);     The socket is returned in @conn_fd and @nkeys contains
1121       the amount of keys which were found. */
1122      inp = fopen (outf, "rb");  int
1123      if (!inp) {  kserver_search_begin (const char *hostname, WORD port,
1124          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,                        const char *pattern, int *conn_fd, size_t *nkeys)
1125                   winpt_strerror (WPTERR_FILE_OPEN));  {
1126          rc = -1;      const char *fmt;
1127          goto leave;      char *request = NULL;
1128      }      char *enc_patt = NULL;
1129      memset (key, 0, maxkeylen);      char status[128];
1130      while( !feof( inp ) ) {      int rc, sock_fd;
1131          s = fgets( temp, sizeof (temp)-1, inp );      int reqlen;
1132          if( !s )      
1133              break;      *conn_fd = 0;
1134          if( !start_key && strstr( s, "KEY" ) && strstr( s, "BEGIN" ) ) {  
1135              start_key = 1;      rc = kserver_connect (hostname, port, &sock_fd);
1136              continue;      if (rc)
1137          }                goto leave;
1138          if( !start_key )  
1139              continue;      enc_patt = URL_encode (pattern, strlen (pattern), NULL);
1140          strcat( key, temp );      reqlen = strlen (enc_patt) + strlen (hostname) + 32 + 1;
1141          maxkeylen -= strlen( temp );  
1142          if( maxkeylen < 0 || (strstr( s, "KEY" ) && strstr( s, "END" )) )                if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
1143              break;          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n"
1144      }                "Proxy-Authorization: Basic %s\r\n\r\n";
1145      fclose( inp );              reqlen += strlen (proxy.base64_user) + strlen (fmt) + 1;
1146            request = safe_alloc (reqlen+1);
1147  leave:          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
1148      if( !strlen( key ) )                     enc_patt, proxy.base64_user);
1149          rc = WPTERR_WINSOCK_RECVKEY;      }    
1150      free_if_alloc( p );      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
1151      free_if_alloc( ksprg );          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1152      return rc;          reqlen += strlen (fmt)+1;
1153  } /* ldap_recvkey */          request = safe_alloc (reqlen+1);
1154            _snprintf (request, reqlen, skip_type_prefix (hostname), port,
1155                                enc_patt);
1156  static int      }
1157  finger_readline (int fd, char * buf, int nbytes)      else {
1158  {          fmt = "GET /pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1159      char c = 0;          reqlen += strlen (fmt)+1;
1160      int n, pos = 0;          request = safe_alloc (reqlen+1);
1161                _snprintf (request, reqlen, fmt, enc_patt);
1162      while (nbytes > 0) {      }
1163          n = recv (fd, &c, 1, 0);  
1164          if (n <= 0)      log_debug ("kserver_search_begin:\r\n%s\r\n", request);
1165              break;      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1166          if (c == '\n')          rc = WPTERR_GENERAL;
1167              break;          goto leave;
1168          buf[pos++] = c;      }
1169          nbytes--;      
1170      }      rc = kserver_search_chkresp (sock_fd);
1171      if (nbytes > 0)      if (rc) {
1172          buf[pos++] = '\0';          closesocket (sock_fd);
1173      if (n <= 0)          sock_fd = 0;
1174          pos = n;          goto leave;
1175      return pos;      }
1176  }  
1177        /* Skip all lines until we reach the "info:" record. */
1178        for (;;) {
1179  int          if (sock_getline (sock_fd, status, DIM (status)-1, &reqlen)) {  
1180  finger_recvkey (const char * host, const char * user, char * key, int maxkeylen)              log_debug ("kserver_search_begin: retrieving status line failed.\r\n");
1181  {              closesocket (sock_fd);
1182      struct hostent * hp;              sock_fd = 0;
1183      struct sockaddr_in saddr;              rc = WPTERR_GENERAL;
1184      char buf[128];              break;
1185      int fd, nread;          }
1186      int start_key = 0;          if (!strncmp (status, "info:", 5))
1187      int rc=0;              break;
1188        }
1189      fd = socket (PF_INET, SOCK_STREAM, 0);  
1190      if (fd == -1)      if (!rc)
1191          return WPTERR_WINSOCK_SOCKET;          *nkeys = count_keys_in_response (status);
1192      hp = gethostbyname (skip_type_prefix (host));      *conn_fd = sock_fd;
1193      if (!hp) {      
1194          closesocket (fd);  leave:
1195          return WPTERR_WINSOCK_RESOLVE;      free_if_alloc (request);
1196      }      free_if_alloc (enc_patt);
1197        return rc;
1198      memset (&saddr, 0, sizeof (saddr));  }
1199      saddr.sin_family = AF_INET;  
1200      saddr.sin_port = htons (FINGER_PORT);  
1201      saddr.sin_addr = *(struct in_addr *)hp->h_addr;  /* Parse a single pub record returned by the keyserver. */
1202      if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {  static void
1203          closesocket (fd);  parse_pub_record (keyserver_key_s *key, char *buf)
1204          return WPTERR_WINSOCK_CONNECT;  {
1205      }      enum pub_rec_t {ID=1, KEYID, ALGO, SIZE, CREATE, EXPIRE};
1206      send (fd, user, strlen (user), 0);      char *p;
1207      send (fd, "\r\n", 2, 0);      int recno = 0;
1208        int off = 0;
1209      memset (key, 0, maxkeylen);  
1210      while (maxkeylen > 0) {      /* pub:BF3DF9B4:17:1024:925411133:: */
1211          nread = finger_readline (fd, buf, sizeof (buf)-1);      p = strtok (buf, ":");
1212          if (nread <= 0)      while (p != NULL) {
1213              break;          recno++;
1214          strcat (buf, "\n");          switch (recno) {
1215          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {          case ID:
1216              strcat (key, buf);              break;
1217              start_key = 1;  
1218              maxkeylen -= nread;          case KEYID:
1219          }              /* If for any reason the returned record actually contains
1220          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {                 a fingerprint instead of a key ID, we truncate the fpr. */
1221              strcat (key, buf);              off = strlen (p) == 40? 32 : 0;
1222              start_key--;              free_if_alloc (key->keyid);
1223              maxkeylen -= nread;              key->keyid = m_strdup (p+off);
1224              break;              break;
1225          }  
1226          else if (start_key) {          case ALGO:
1227              strcat (key, buf);              key->algo = atoi (p);
1228              maxkeylen -= nread;              break;
1229          }              
1230      }          case SIZE:
1231      closesocket (fd);              key->bits = atoi (p);
1232      if (start_key != 0)              break;
1233          rc = WPTERR_WINSOCK_RECVKEY;  
1234      return rc;          case CREATE:
1235  }              key->creation = strtoul (p, NULL, 10);
1236                break;
1237    
1238            case EXPIRE:
1239                key->expires = strtoul (p, NULL, 10);
1240                break;
1241            }
1242            p = strtok (NULL, ":");
1243        }
1244    }
1245    
1246    
1247    /* Parse a single user id returned by the keyserver. */
1248    static void
1249    parse_uid_record (keyserver_key_s *key, char *buf)
1250    {
1251        enum uid_rec_t {ID=1, UID, CREATE, EXPIRE};
1252        keyserver_uid_s *u, *n;
1253        char *p, *raw;
1254        int recno = 0;
1255    
1256        /* uid:Timo Schulz <[email protected]>:1138440360:: */
1257        u = new keyserver_uid_s;
1258        memset (u, 0, sizeof *u);
1259    
1260        p = strtok (buf, ":");
1261        while (p != NULL) {
1262            recno++;
1263    
1264            switch (recno) {
1265            case ID:
1266                break;
1267    
1268            case UID:
1269                unhexify_buffer (p, &raw);
1270                u->uid = utf8_to_native (raw);
1271                free_if_alloc (raw);
1272                break;
1273    
1274            case CREATE:
1275                u->creation = strtoul (p, NULL, 10);
1276                break;
1277    
1278            case EXPIRE:
1279                u->expires = strtoul (p, NULL, 10);
1280                break;
1281            }
1282    
1283            p = strtok (NULL, ":");
1284        }
1285        if (!key->uids)
1286            key->uids = u;
1287        else {
1288            for (n = key->uids; n->next; n=n->next)
1289                ;
1290            n->next = u;
1291        }
1292    }
1293    
1294    
1295    /* Peek the next 3 bytes to check if the next line
1296       would be a new "pub" record. In this case, return
1297       -1 as an EOF indication, 0 otherwise. */
1298    static int
1299    is_key_eof (int fd)
1300    {
1301        char buf[64];
1302        int n;
1303    
1304        n = recv (fd, buf, 3, MSG_PEEK);
1305        if (n < 3 || strncmp (buf, "pub", 3))
1306            return 0;
1307        return -1;
1308    }
1309    
1310    
1311    /* Return the next key from the search response. */
1312    int
1313    kserver_search_next (int fd, keyserver_key_s **r_key)
1314    {
1315        keyserver_uid_s *uid, *u = NULL;
1316        keyserver_key_s *key;
1317        char buf[512];
1318        int n = 0;
1319        long max = 0;
1320    
1321        log_debug ("keyserver_search_next:\r\n");
1322        *r_key = NULL;
1323    
1324        key = new keyserver_key_s;
1325        memset (key, 0, sizeof *key);
1326        for (;;) {
1327            if (sock_getline (fd, buf, DIM (buf)-1, &n))
1328                break;
1329            /*log_debug ("record: '%s'\r\n", buf); */
1330            if (!strncmp (buf, "pub", 3))
1331                parse_pub_record (key, buf);
1332            else
1333                parse_uid_record (key, buf);
1334            if (is_key_eof (fd))
1335                break;
1336        }
1337    
1338        /* the uid with the newest self sig is used as the
1339           primary user id. */
1340        for (uid = key->uids; uid; uid = uid->next) {
1341            if (uid->creation > max) {
1342                max = uid->creation;
1343                u = uid;
1344            }
1345        }
1346    
1347        key->main_uid = u? u : key->uids;
1348        *r_key = key;
1349        return 0;
1350    }
1351    
1352    
1353    /* Release the keyserver key @key and all its elements. */
1354    void
1355    kserver_release_key (keyserver_key_s *key)
1356    {
1357        keyserver_uid_s *u;
1358    
1359        while (key->uids) {
1360            u = key->uids->next;
1361            free_if_alloc (key->uids->uid);
1362            free_if_alloc (key->uids);
1363            key->uids = u;
1364        }
1365        free_if_alloc (key->keyid);
1366        free_if_alloc (key);
1367    }
1368    
1369    
1370    /* Release mbmers in the proxy context @ctx. */
1371    void
1372    kserver_proxy_release (keyserver_proxy_t ctx)
1373    {
1374        free_if_alloc (ctx->host);
1375        free_if_alloc (ctx->pass);
1376        free_if_alloc (ctx->user);
1377        ctx->port = ctx->proto = 0;
1378    }
1379    
1380    
1381    /* Spawn a process given by @cmdl. */
1382    static int
1383    spawn_application (char *cmdl)
1384    {
1385        STARTUPINFO si;
1386        PROCESS_INFORMATION pi;
1387        int rc = 0;
1388    
1389        memset (&si, 0, sizeof (si));
1390        si.cb = sizeof (si);
1391        si.dwFlags = STARTF_USESHOWWINDOW;
1392        si.wShowWindow = SW_HIDE;
1393        memset (&pi, 0, sizeof (pi));
1394    
1395        if (!CreateProcess (NULL, cmdl, NULL, NULL, FALSE, 0,
1396                            NULL, NULL, &si, &pi)) {
1397            log_box ("Keyserver Plugin", MB_ERR, "Could not spawn helper process");
1398            rc = -1;
1399        }
1400    
1401        CloseHandle (pi.hThread);
1402        WaitForSingleObject (pi.hProcess, INFINITE);
1403        CloseHandle (pi.hProcess);
1404        return rc;
1405    }
1406    
1407    
1408    static FILE*
1409    do_spawn_ldap_helper (const char *host, const char *keyid)
1410    {
1411        FILE *fp = NULL;
1412        char *p, *sep;
1413        char *ksprg;
1414        char outf[256], inf[256];
1415        size_t n;
1416    
1417        p = get_gnupg_prog ();
1418        n = strlen (p) + 1 + 128;
1419        ksprg = safe_alloc (n+1);
1420        if (!ksprg)
1421            BUG (0);
1422        sep = strrchr (p, '\\');
1423        if (sep != NULL)
1424            p[(sep-p)] = 0;
1425    
1426        _snprintf (ksprg, n, "%s\\gpgkeys_ldap.exe", p);
1427        free_if_alloc (p);
1428        if (file_exist_check (ksprg)) {
1429            log_box ("LDAP Keyserver Plugin", MB_ERR,
1430                     "%s: could not find LDAP keyserver module!", ksprg);
1431            fp = NULL;
1432            goto leave;
1433        }
1434        get_temp_name (outf, DIM (outf)-1, keyid);
1435        get_temp_name (inf, DIM (inf)-1, NULL);
1436        fp = fopen (inf, "w+b");
1437        if (!fp) {
1438            log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", inf,
1439                     winpt_strerror (WPTERR_FILE_OPEN));
1440            goto leave;
1441        }
1442        fprintf (fp,
1443            "VERSION 1\n"
1444            "PROGRAM %d.%d.%d\n"
1445            "SCHEME ldap\n"
1446            "HOST %s\n"
1447            "COMMAND GET\n"
1448            "\n"
1449            "%s\n",
1450            gpgver[0], gpgver[1], gpgver[2],
1451            host? skip_type_prefix (host): "64.94.85.200", keyid);
1452        fclose (fp);
1453    
1454        p = safe_alloc (strlen (ksprg) + strlen (inf) + strlen (outf) + 32);
1455        sprintf (p, "%s -o %s %s", ksprg, outf, inf);
1456        if (spawn_application (p)) {
1457            fp = NULL;
1458            goto leave;
1459        }
1460        fp = fopen (outf, "rb");
1461        if (!fp)
1462            log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,
1463                     winpt_strerror (WPTERR_FILE_OPEN));
1464    
1465    leave:
1466        DeleteFile (inf);
1467        DeleteFile (outf);
1468        free_if_alloc (p);
1469        free_if_alloc (ksprg);
1470        return fp;
1471    }
1472    
1473    /* Receive an key via LDAP from host @host with the keyid @keyid.
1474       @key contains the key on success. */
1475    int
1476    ldap_recvkey (const char *host, const char *keyid,
1477                  char **r_key, size_t *r_keylen)
1478    {  
1479        gpgme_data_t raw;
1480        FILE *fp;
1481        const char *s;
1482        char buf[512];
1483        int start_key = 0, failed = 0;
1484        int rc = 0;
1485    
1486        fp = do_spawn_ldap_helper (host, keyid);
1487        if (!fp)
1488            return WPTERR_GENERAL;
1489    
1490        if (gpgme_data_new (&raw))
1491            BUG (0);
1492        while (!feof (fp)) {
1493            s = fgets (buf, DIM (buf)-1, fp);
1494            if (!s)
1495                break;
1496            if (strstr (s, "KEY") && strstr (s, "FAILED")) {
1497                failed = 1;
1498                break;
1499            }
1500            if (!start_key && strstr (s, "KEY") && strstr (s, "BEGIN")) {
1501                start_key = 1;
1502                continue;
1503            }
1504            if (!start_key)
1505                continue;
1506            gpgme_data_write (raw, buf, strlen (buf));
1507            if (strstr (s, "KEY") && strstr (s, "END"))
1508                break;
1509        }
1510        fclose (fp);
1511    
1512        if (failed)
1513            rc = WPTERR_WINSOCK_RECVKEY;
1514        *r_key = data_release_and_get_mem (raw, r_keylen);
1515        return rc;
1516    }
1517    
1518    
1519    /* Receive an key via FINGER from host @host with the user @user.
1520       On success @key contains the key. */
1521    int
1522    finger_recvkey (const char *host, const char *user,
1523                    char **r_key, size_t *r_keylen)
1524    {
1525        gpgme_data_t raw;
1526        char buf[256+1];
1527        int fd, nread;
1528        int start_key = 0;
1529        int rc=0;
1530    
1531        rc = kserver_connect (host, FINGER_PORT, &fd);
1532        if (rc)
1533            return rc;
1534    
1535        sock_write (fd, user, strlen (user));
1536        sock_write (fd, "\r\n", 2);
1537    
1538        if (gpgme_data_new (&raw))
1539            return WPTERR_WINSOCK_RECVKEY;
1540    
1541        for (;;) {
1542            if (sock_getline (fd, buf, DIM (buf)-2, &nread))
1543                break;
1544            strcat (buf, "\n");
1545            if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {
1546                gpgme_data_write (raw, buf, nread);
1547                start_key = 1;
1548            }
1549            else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {
1550                gpgme_data_write (raw, buf, nread);
1551                start_key--;
1552                break;
1553            }
1554            else if (start_key)
1555                gpgme_data_write (raw, buf, nread);
1556        }
1557    
1558        closesocket (fd);
1559        if (start_key != 0)
1560            rc = WPTERR_WINSOCK_RECVKEY;
1561        *r_key = data_release_and_get_mem (raw, r_keylen);
1562        return rc;
1563    }
1564    
1565    
1566    /* Check if the given name @name is a valid inernet address
1567       which means an dotted IP or a valid DNS name.
1568       Return value: 0 on success. */
1569    int
1570    check_inet_address (const char *addr)
1571    {
1572        const char *not_allowed = "=!�$%&@#*~\\/}][{<>|,;:'";
1573        size_t i;
1574    
1575        for (i=0; i < strlen (addr); i++) {
1576            if (strchr (not_allowed, addr[i]))
1577                return -1;
1578        }
1579        return 0;
1580    }
1581    
1582    
1583    /* Split the URL @r_keyserver into the host and the port
1584       part if possible. */
1585    gpgme_error_t
1586    parse_keyserver_url (char **r_keyserver, unsigned short *r_port)
1587    {
1588        char *p;
1589        char *url = *r_keyserver;
1590        int off = 0;
1591    
1592        /* no port is given so use the default port. */
1593        p = strrchr (url, ':');
1594        if (p == strchr (url, ':')) {
1595            int port = port_from_proto (proto_from_URL (url));
1596            if (!port)
1597                port = HKP_PORT;
1598            *r_port = port;
1599            return 0;
1600        }
1601    
1602        if (url[(p-url)-1] == '/') /* remove / in .de/:11371 */
1603            off = 1;
1604    
1605        *r_keyserver = substr (url, 0, (p-url)-off);
1606        *r_port = atoi (url+(p-url)+1);
1607        free_if_alloc (url);
1608        return 0;
1609    }

Legend:
Removed from v.2  
changed lines
  Added in v.276

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26