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

Legend:
Removed from v.5  
changed lines
  Added in v.271

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26