/[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 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")) /* http error */      }
119          return ec;  
120      if (strstr (resp, "Public Key Server -- Error")      outbuf[len] = '\0';
121          || strstr (resp, "Public Key Server -- Error")  }
122          || strstr (resp, "No matching keys in database")) {  
123          p = strstr (resp, "<p>");  
124          if (p && strlen (p) < sizeof (hkp_errmsg)) {  /* Check that the given buffer contains a valid keyserver URL
125              end = strstr (p, "</p>");     and return the prefix length, 0 in case of an error. */
126              len = end? (end - p + 1) : strlen (p);  static int
127              strncpy (hkp_errmsg, p, len);  check_URL (const char *buf)
128              hkp_err = 1;  {
129          }      const char *proto[] = {
130          return ec;          "ldap://",
131      }          "http://",
132      return 0;          "finger://",
133  } /* check_hkp_response */          "hkp://",
134            NULL};
135        int i;
136  static int  
137  sock_getline (int fd, char *buf, int buflen, int *nbytes)      if (strlen (buf) < 7)
138  {          return 0;
139      char ch;  
140      int count = 0;            for (i=0; proto[i] != NULL; i++) {
141                if (strstr (buf, proto[i]))
142      if (nbytes)              return strlen (proto[i]);
143          *nbytes = 0;      }
144      *buf = 0;      return 0;
145      while (recv (fd, &ch, 1, 0) > 0) {  }
146          *buf++ = ch;  
147          count++;  
148          if (ch == '\n' || count == (buflen - 1)) {  /* Skip the URL schema and return only the host part of it. */
149              *buf = 0;  static const char*
150              if (nbytes)  skip_type_prefix (const char *hostname)
151                  *nbytes = count;  {
152              return 0;      int pos;
153          }  
154      }      if (!hostname)
155            return hostname;
156      return -1;  
157  } /* sock_getline */      pos = check_URL (hostname);
158        if (pos > 0)
159            hostname += pos;
160  static int      return hostname;
161  sock_select( int fd )  }
162  {  
163      FD_SET rfd;  /* Parse the keyserver response and extract the human
164      timeval tv = {1, 0};     readable text passages. */
165    static int
166      FD_ZERO( &rfd );  parse_keyserver_error (const char *resp, char *txt, size_t txtlen)
167      FD_SET( fd, &rfd );  {
168      if( select( fd + 1, &rfd, NULL, NULL, &tv ) == SOCKET_ERROR )      char *p, *p2;
169          return SOCKET_ERROR;  
170      if( FD_ISSET( fd, &rfd ) )      /* If we find no 'Error' substring, we assume a success. */
171          return 1;      if (!stristr (resp, "Error"))
172      return 0;          return -1;
173  } /* sock_select */  
174        memset (txt, 0, txtlen);
175        p = strstr (resp, "\r\n\r\n");
176  static int      if (!p)
177  sock_read( int fd, char *buf, int buflen, int *nbytes )          return -1;
178  {            resp += (p-resp);
179      DWORD nread;      p = strstr (resp, "<h1>");
180      int nleft = buflen;      if (!p)
181      int rc, n = 0;          return -1;
182        resp += (p-resp)+strlen ("<h1>");
183      while (nleft > 0) {      p = strstr (resp, "</h1>");
184          if (n >= 10)      if (!p)
185              return WPTERR_WINSOCK_TIMEOUT;          return -1;
186          if ( (rc = sock_select( fd )) == SOCKET_ERROR )      resp += (p-resp)+strlen ("</h1>");
187              return SOCKET_ERROR;      p2 = strstr (resp, "</body>");
188          else if( !rc )      if (p2 != NULL)
189              n++;          memcpy (txt, resp, (p2-resp));
190          else {      else {
191              nread = recv(fd, buf, nleft, 0);          if (!strnicmp (resp, "<p>", 3))
192              if (nread == SOCKET_ERROR)              resp += 3;
193                  return SOCKET_ERROR;          while (resp && *resp == '\r' || *resp == '\n')
194              else if (!nread)              resp++;
195                  break;          memcpy (txt, resp, strlen (resp));
196              nleft -= nread;      }
197              buf += nread;      return 0;
198          }        }
199      }  
200      if (nbytes)  
201          *nbytes = buflen - nleft;  /* Check that the keyserver response indicates an OK.
202               Return 0 on success. */
203      return 0;  static int
204  } /* sock_read */  check_hkp_response (const char *resp, int recv)
205    {
206        int ec;
207  static int  
208  sock_write( int fd, const char *buf, int buflen )      log_debug ("check_hkp_response: '%s'\r\n", resp);
209  {      ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;
210      DWORD nwritten;      if (!strstr (resp, "HTTP/1.0 200 OK") &&
211      int nleft = buflen;          !strstr (resp, "HTTP/1.1 200 OK") &&
212            !strstr (resp, "HTTP/1.0 500 OK") &&
213      while (nleft > 0) {          !strstr (resp, "HTTP/1.1 500 OK"))
214          nwritten = send (fd, buf, nleft, 0);          return ec; /* http error */
215          if (nwritten == SOCKET_ERROR)  
216              return SOCKET_ERROR;      if (!parse_keyserver_error (resp, hkp_errmsg, DIM (hkp_errmsg)-2)) {
217          nleft -= nwritten;          if (!strlen (hkp_errmsg))
218          buf += nwritten;                      _snprintf (hkp_errmsg, DIM (hkp_errmsg)-1,
219      }                          "Unknown keyserver error");
220            hkp_err = 1;
221      return 0;          return ec;
222  } /* sock_write */      }
223        return 0;
224    }
225  void  
226  set_default_kserver (void)  
227  {  /* Read a single line (\r\n) from a socket.
228      char * p = get_reg_entry_keyserver ("Default");     Return 0 on success. */
229      free_if_alloc (default_keyserver);  static int
230      default_keyserver = p && *p != ' ' ? p : m_strdup (DEF_HKP_KEYSERVER);  sock_getline (int fd, char *buf, int buflen, int *nbytes)
231      p = get_reg_entry_keyserver ("Default_Port");  {
232      if (p && *p) {      char ch;
233          default_keyserver_port = (u16)strtoul (p, NULL, 10);      int nread = 0;      
234          free_if_alloc (p);      
235      }      if (nbytes)
236      else          *nbytes = 0;
237          default_keyserver_port = HKP_PORT;      *buf = 0;
238  } /* set_default_kserver */      while (recv (fd, &ch, 1, 0) > 0) {
239            *buf++ = ch;
240            nread++;
241  /*          if (ch == '\r')
242   * Initialize the Winsock2 interface.              continue; /* remove this char. */
243   */          if (ch == '\n' || nread == (buflen - 1)) {
244  int              *buf = 0;
245  wsock_init (void)              if (nbytes)
246  {                  *nbytes = nread;
247      WSADATA wsa;              return 0;
248            }
249      if (WSAStartup (0x202, &wsa))      }
250          return WPTERR_WINSOCK_INIT;  
251      set_default_kserver ();      return -1;
252      return 0;  }
253  } /* wsock_init */  
254    
255    /* Perform a select() on the given fd to find out
256  /*     is there is data for reading. Wait at least @nsecs seconds. */
257   * Should be called after the keyserver access.  static int
258   */  sock_select (int fd, int nsecs)
259  void  {
260  wsock_end (void)      FD_SET rfd;
261  {      timeval tv = {nsecs, 0};
262      int i;  
263        FD_ZERO (&rfd);
264      free_if_alloc (default_keyserver);      FD_SET (fd, &rfd);
265      default_keyserver = NULL;      if (select (fd + 1, &rfd, NULL, NULL, &tv) == SOCKET_ERROR) {
266      for (i=0; i < MAX_KEYSERVERS; i++) {          log_debug ("sock_select: select() failed ec=%d.\r\n", net_errno);
267          if (server[i].used)          return SOCKET_ERROR;
268              free_if_alloc (server[i].name);      }
269      }      if (FD_ISSET (fd, &rfd))
270      WSACleanup ();          return 1;
271  } /* wsock_end */      return 0;
272    }
273    
274  const char*  
275  wsock_strerror( void )  /* Read from a socket @fd to buffer @buf with a fixed timeout
276  {         of 10 seconds. The amount of bytes which were read are
277      static char buf[384];     returned in @nbytes.
278      int ec = WSAGetLastError( );     Return value: 0 on success. */
279        static int
280      switch ( ec ) {  sock_read (int fd, char *buf, int buflen, int *nbytes)
281      case WSAENETDOWN: return _("The network subsystem has failed");      {
282      case WSAHOST_NOT_FOUND: return _("Authoritative Answer Host not found");                  DWORD nread;
283      case WSAETIMEDOUT: return _("The connection has been dropped because of a network failure");      int nleft = buflen;
284      default: _snprintf( buf, sizeof (buf) -1, _("Unknown Winsock error ec=%d"),ec); return buf;      int rc, n = 0;
285      }      
286      return NULL;      if (nbytes)
287  } /* wsock_strerror */          *nbytes = 0;
288        while (nleft > 0) {
289            if (n >= default_socket_timeout)
290  const char*              return WPTERR_WINSOCK_TIMEOUT;
291  kserver_strerror( void )          rc = sock_select (fd, 1);
292  {                if (rc == SOCKET_ERROR)
293      if( hkp_err )              return rc;
294          return hkp_errmsg;          else if (!rc)
295      return NULL;              n++;
296  } /* kserver_strerror */          else {
297                nread = recv (fd, buf, nleft, 0);
298                if (nread == SOCKET_ERROR) {
299  const char *                  log_debug ("sock_read: recv() failed ec=%d.\r\n", net_errno);
300  kserver_get_hostname (int idx, int type, u16 *port)                  return SOCKET_ERROR;
301  {              }
302      if (type == -1) {              else if (!nread)
303          *port = default_keyserver_port;                  break;
304          return default_keyserver;              nleft -= nread;
305      }              buf += nread;
306      else if (!type && idx < DIM (server_list)) {          }      
307          *port = HKP_PORT;      }
308          return server_list[idx];      if (nbytes)
309      }          *nbytes = buflen - nleft;
310      return NULL;          
311  }      return 0;
312    }
313    
314  int  
315  kserver_check_inet_connection (void)  /* Helper to create a string from the gpgme data and
316  {     then release the gpgme data object. */
317      int fd;  char*
318    data_release_and_get_mem (gpgme_data_t in, int *r_bufferlen)
319      if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {  {
320          closesocket (fd);      size_t n;
321          return 0;      char *buffer, *p;
322      }  
323      return -1;      gpg_data_putc (in, '\0');
324  }      p = gpgme_data_release_and_get_mem (in, &n);
325        buffer = m_strdup (p);
326        if (r_bufferlen)
327  /*          *r_bufferlen = (int)n;
328   * If the request contains the keyid, it have to be      gpgme_free (p);
329   * always postfix with '0x'+keyid. This code checks      return buffer;
330   * if the keyid is a decimal value and if so if it contains  }
331   * the '0x'. If not it is inserted.  
332   */  
333  const char*  /* Read much data as possible from the socket @fd and
334  kserver_check_keyid (const char *keyid)     return the data in @buffer. Caller must free data.
335  {           Return value: 0 on success. */
336      static char id[20];  int
337    sock_read_ext (int fd, char **buffer, int *r_bufferlen)
338      if (strstr (keyid, "@"))  {
339          return keyid; /* email address */      gpgme_data_t dh;
340      if (strncmp (keyid, "0x", 2)) {      char buf[1024];
341          memset (&id, 0, sizeof (id));      size_t n=0;
342          _snprintf (id, sizeof (id)-1, "0x%s", keyid);      int nread, rc;
343          return id;  
344      }      if (gpgme_data_new (&dh))
345      return keyid;          BUG (0);
346  } /* kserver_check_keyid */      while (n < 10) {
347            rc = sock_select (fd, 1);
348            if (rc == SOCKET_ERROR) {
349  static void              gpgme_data_release (dh);
350  kserver_update_proxyuser (const char *proxy_user, const char *proxy_pass)              return rc;
351  {          }
352      char t[257]; /* user:pass = 127+1+127+1 = 257 */          else if (!rc)
353                n++;
354      free_if_alloc (proxy.base64_user);          else {
355      proxy.base64_user = new char[4*strlen( proxy_user ) / 3 + 32];              nread = recv (fd, buf, DIM (buf), 0);
356      if( !proxy.base64_user )              if (nread == SOCKET_ERROR)
357          BUG (0);                  return SOCKET_ERROR;
358      _snprintf (t, sizeof (t)-1, "%s:%s", proxy_user, proxy_pass);              else if (!nread)
359      base64_encode (t, proxy.base64_user, 257);                  break;
360      free_if_alloc (proxy.user);              gpgme_data_write (dh, buf, nread);
361      free_if_alloc (proxy.pass);          }
362      proxy.user = m_strdup (proxy_user);      }
363      proxy.pass = m_strdup (proxy_pass);  
364  } /* kserver_update_proxyuser */      *buffer = data_release_and_get_mem (dh, r_bufferlen);
365        return 0;
366    }
367  static int  
368  check_URL (const char * buf)  
369  {  /* Write the buffer @buf with the length @buflen to a socket @fd. */
370      if (strlen (buf) < 7)  static int
371          return -1;  sock_write (int fd, const char *buf, int buflen)
372      if( !strstr (buf, "ldap://")  {
373          && !strstr (buf, "http://")      DWORD nwritten;
374          && !strstr (buf, "finger://")      int nleft = buflen;
375          && !strstr (buf, "hkp://"))  
376          return -1;      while (nleft > 0) {
377      return 0;          nwritten = send (fd, buf, nleft, 0);
378  } /* check_URL */          if (nwritten == SOCKET_ERROR) {
379                    log_debug ("sock_write: send() failed ec=%d\r\n", net_errno);
380                return SOCKET_ERROR;
381  static int          }
382  proto_from_URL (const char * buf)          nleft -= nwritten;
383  {          buf += nwritten;
384      if (strstr( buf, "ldap"))      }
385          return KSPROTO_LDAP;  
386      else if (strstr( buf, "finger"))      return 0;
387          return KSPROTO_FINGER;  }
388      return KSPROTO_HTTP;  
389  } /* proto_from_URL */  
390    /* Initialize the Winsock2 interface.*/
391    int
392  void  wsock_init (void)
393  keyserver_set_default (const char * hostname, u16 port)  {
394  {      WSADATA wsa;
395      if (hostname) {  
396          free_if_alloc (default_keyserver);      if (WSAStartup (0x202, &wsa)) {
397          default_keyserver = m_strdup (hostname);          log_debug ("wsock_init: WSAStartup failed ec=%d\r\n", net_errno);
398          if (!default_keyserver)          return WPTERR_WINSOCK_INIT;
399              BUG (0);      }
400          default_keyserver_port = port;      return 0;
401      }  }
402      server[0].name =  default_keyserver;  
403      server[0].used = 1;  
404      server[0].port = port;  /* Cleanup the Winsock2 interface. */
405      server[0].proto = proto_from_URL (default_keyserver);  void
406  } /* keyserver_set_default */  wsock_end (void)
407    {
408        char *p;
409  static const char *      int i;
410  skip_whitespace (const char * str)  
411  {  #ifdef WINPT_MOBILE
412      while (str && *str)      p = m_strdup ("keyserver.conf");
413      {  #else
414          if (*str == ' ' ||      p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);
415              *str == '\t' ||  #endif
416              *str == '\n' ||      kserver_save_conf (p);
417              *str == '\r')      free_if_alloc (p);
418          {      free_if_alloc (default_keyserver);
419              str++;      for (i=0; i < MAX_KEYSERVERS; i++) {
420              continue;          if (server[i].used && server[i].name != NULL)
421          }              free_if_alloc (server[i].name);
422          break;      }
423      }      kserver_proxy_release (&proxy);
424      return str;      WSACleanup ();
425  }      log_debug ("wsock_end: cleanup finished.\r\n");
426    }
427    
428  int  
429  kserver_load_conf (const char * conf)  /* Return a string representation of a winsock error. */
430  {  const char*
431      struct stat statbuf;  wsock_strerror (void)
432      FILE *fp;  {
433      char buf[1024], * s, * p;      int ec = WSAGetLastError ();
434      char *user = NULL, *pass = NULL;          
435      int pos, proxy_auth = 0;      if (!ec)
436      int no_config=0;          return "";
437            switch (ec) {
438      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {      case WSAENETDOWN:
439          server[pos].used = 0;          return _("Network unreachable");
440          server[pos].port = HKP_PORT;  
441      }      case WSAEHOSTUNREACH:
442                return _("Host unreachable");
443      fp = fopen (conf, "rb");  
444      if (!fp) {      case WSAHOST_NOT_FOUND:
445          for( pos = 0; server_list[pos]; pos++ ) {          return _("Could not resolve host name");
446              server[pos].used = 1;  
447              server[pos].name = (char *)server_list[pos];      case WSAECONNREFUSED:
448              server[pos].proto = proto_from_URL( server_list[pos] );          return _("Connection refused");
449          }  
450          no_config=1;      case WSAETIMEDOUT:
451      }      case WSAECONNABORTED:
452      get_reg_proxy_prefs( &proxy.host, &proxy.port, &user, &pass );          return _("Connection timeout");
453      if( user && pass )  
454          kserver_update_proxyuser( user, pass );      case WSAENETRESET:
455      else if( user && !pass || !user && pass ) {      case WSAECONNRESET:    
456          msg_box( NULL, _("Invalid proxy configuration."          return _("Connection resetted by peer");
457                           "You need to set a user and a password"  
458                           "to use proxy authentication!"), _("Proxy Error"), MB_ERR );      case WSAESHUTDOWN:
459      }          return _("Socket has been shutdown");
460      /* check if the host has a http:// prefix and skip it */  
461      if( proxy.host && !strncmp( proxy.host, "http://", 7 ) ) {      default:
462          const char *s = proxy.host+7;          break;
463          char * p = m_strdup (s);      }
464          if (!p)  
465              BUG (0);      return "";
466          free_if_alloc (proxy.host);  }
467          proxy.host = p;  
468      }  
469      free_if_alloc (user);  /* Set default socket timeout for all reading operations. */
470      free_if_alloc (pass);  void
471        kserver_set_socket_timeout (int nsec)
472      pos = 0;  {
473      while( fp && !feof( fp ) ) {      if (nsec < 0 || nsec > 3600)
474          s = fgets (buf, sizeof (buf)-1, fp);          nsec = 0;
475          if (!s)      default_socket_timeout = nsec;
476              break;  }
477          if (strstr (buf, "\r\n"))  
478              buf[strlen (buf)-2] = '\0';  
479          if (strstr (buf, "\n"))  /* Return the last keyserver error as a string. */
480              buf[strlen (buf)-1] = '\0';  const char*
481          s = (char *)skip_whitespace (buf);  kserver_strerror (void)
482          if (*s == '#' || strlen (s) < 7)  {      
483              continue;      if (hkp_err)
484          if (check_URL (s)) {          return hkp_errmsg;
485              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"      return NULL;
486                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),  }
487                               _("Keyserver Error"), MB_ERR);  
488              continue;  
489          }  /* Read a keyserver from the list at index @idx.
490          p = strchr (s+6, ':');     Return value: keyserver name at the given position. */
491          server[pos].used = 1;  const char*
492          server[pos].proto = proto_from_URL (s);  kserver_get_hostname (int idx, int type, WORD *port)
493          if (!p)  {
494              server[pos].name = m_strdup (s);      if (type == -1) {
495          else {                *port = default_keyserver_port;
496              server[pos].port = atol (p+1);          return default_keyserver;
497              if (server[pos].port < 0 || server[pos].port > 65536)      }
498                  server[pos].port = HKP_PORT;      else if (!type && idx < DIM (server_list)) {
499              server[pos].name = new char [(p-s)+2];          /* XXX: handle non HKP servers. */
500              if (!server[pos].name)          *port = HKP_PORT;
501                  BUG (0);          return server_list[idx];
502              memset (server[pos].name, 0, (p-s)+2);      }
503              memcpy (server[pos].name, s, (p-s));      return NULL;
504          }  }
505          pos++;  
506          if (pos > MAX_KEYSERVERS)  
507          {  /* Check if the computer is connected to the internet.
508              msg_box (NULL, _("The keyserver limit is exceeded"), _("Keyserver Warning"), MB_INFO);     Return 0 on success -1 otherwise. */
509              break;  int
510          }  kserver_check_inet_connection (void)
511      }  {
512      if (fp)      int fd;
513          fclose (fp);  
514      if (!pos)      if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {
515      {          closesocket (fd);
516          /* only issue an error if the config file exist but it has no valid entries. */          return 0;
517          keyserver_set_default (NULL, HKP_PORT);      }
518          if (!no_config)      log_debug ("kserver_check_inet_connection: no inet connection.\r\n");
519              return WPTERR_CONFIG_FILE;        return -1;
520      }  }
521    
522      if (!stat (conf, &statbuf))  
523          conf_timestamp = statbuf.st_mtime;  /* If the request contains the keyid, it have to be
524      return 0;     always postfix with '0x'+keyid. This code checks
525  } /* kserver_load_conf */     if the keyid is a decimal value and if so if it contains
526       the '0x'. If not it is inserted. */
527    const char*
528  const char *  kserver_check_keyid (const char *keyid)
529  kserver_get_proxy (int * r_port)  {      
530  {      static char id[22];
531      if (proxy.host)  
532      {      if (strstr (keyid, "@"))
533          if (r_port)          return keyid; /* email address */
534              *r_port = proxy.port;      if (strncmp (keyid, "0x", 2)) {
535          return proxy.host;          memset (&id, 0, sizeof (id));
536      }          _snprintf (id, DIM (id)-1, "0x%s", keyid);
537      return NULL;          return id;
538  } /* kserver_get_proxy */      }
539        return keyid;
540    }
541  const char *  
542  kserver_get_proxy_info( int id )  
543  {  /* Update the keyserver proxy user. */
544      switch( id ) {    static void
545      case PROXY_USER: return proxy.user;  update_proxy_user (const char *proxy_user, const char *proxy_pass)
546      case PROXY_PASS: return proxy.pass;  {
547      }      char t[257]; /* user:pass = 127+1+127+1 = 257 */
548      return NULL;      int n = 0;
549  } /* kserver_get_proxy_info */  
550        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   * Connect to the keyserver 'hostname'.      _snprintf (t, DIM (t)-1, "%s:%s", proxy_user, proxy_pass);
554   * We always use the HKP port.      base64_encode (t, proxy.base64_user);
555   */      free_if_alloc (proxy.user);
556  int      free_if_alloc (proxy.pass);
557  kserver_connect (const char *hostname, u16 port, int *conn_fd)      proxy.user = m_strdup (proxy_user);
558  {      proxy.pass = m_strdup (proxy_pass);
559      int rc, fd;  }
560      u32 iaddr;      
561      char host[128] = {0};  
562      struct hostent *hp;  /* Get the port number from the given protocol. */
563      struct sockaddr_in sock;  static int
564    port_from_proto (int proto)
565      if (debug)  {
566          log_f ("kserver_connect: %s:%d\r\n", hostname, port);      switch (proto) {
567      if (!port)      case KSPROTO_LDAP:   return LDAP_PORT;
568          port = HKP_PORT;      case KSPROTO_FINGER: return FINGER_PORT;
569      if (conn_fd)      case KSPROTO_HTTP:   return HKP_PORT;
570          *conn_fd = 0;      }
571      hostname = skip_type_prefix (hostname);      return 0;
572        }
573      memset (&sock, 0, sizeof (sock));  
574      sock.sin_family = AF_INET;  
575      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);  /* Get the port number from the given URL. */
576      if (proxy.host)  static int
577          strncpy (host, proxy.host, 127);  proto_from_URL (const char *buf)
578      else  {
579          strncpy (host, hostname, 127);      if (strstr (buf, "ldap"))
580                return KSPROTO_LDAP;
581      if ((iaddr = inet_addr (host)) != INADDR_NONE)      else if (strstr (buf, "finger"))
582          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));          return KSPROTO_FINGER;
583      else if ((hp = gethostbyname (host))) {      return KSPROTO_HKP;
584          if (hp->h_addrtype != AF_INET)  }
585              return WPTERR_WINSOCK_RESOLVE;  
586          else if (hp->h_length != 4)  
587              return WPTERR_WINSOCK_RESOLVE;  /* Set the default keyserver.
588          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);     If @hostname is NULL, use the predefined keyserver. */
589      }  void
590      else {  keyserver_set_default (const char *hostname, WORD port)
591          if (debug)  {
592              log_f ("gethostbyname: failed.\r\n");      if (!port)
593          return WPTERR_WINSOCK_RESOLVE;          port = HKP_PORT;
594      }      if (hostname != NULL) {
595      fd = socket (AF_INET, SOCK_STREAM, 0);          free_if_alloc (default_keyserver);
596      if (fd == INVALID_SOCKET)            default_keyserver = m_strdup (hostname);
597          return WPTERR_WINSOCK_SOCKET;          default_keyserver_port = port;
598      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));      }
599      if (rc == SOCKET_ERROR) {      if (!default_keyserver) {
600          if (debug)          default_keyserver = m_strdup (DEF_HKP_KEYSERVER);
601              log_f ("connect: failed.\r\n");          default_keyserver_port = HKP_PORT;
602          closesocket(fd);      }
603          return WPTERR_WINSOCK_CONNECT;      server[0].name =  m_strdup (default_keyserver);
604      }      server[0].used = 1;
605        server[0].port = port;
606      if (conn_fd)      server[0].proto = proto_from_URL (default_keyserver);
607          *conn_fd = fd;  }
608      WSASetLastError(0);  
609      return 0;  
610  } /* kserver_connect */  /* Skip all kind of whitespace chars in @str. */
611    static const char*
612    skip_whitespace (const char *str)
613  static char*  {
614  kserver_urlencode (const char *pubkey, int octets, int *newlen)      while (str && *str) {
615  {          if (*str == ' ' ||
616      char *p, numbuf[5];              *str == '\t' ||
617      size_t j = 0;              *str == '\n' ||
618      int i, size;              *str == '\r') {
619                    str++;
620      p = new char [2*octets];              continue;
621      if (!p)          }
622          BUG (0);          break;
623        }
624      for (size=0, i=0; i<octets; i++) {      return str;
625          if (isalnum (pubkey[i]) || pubkey[i] == '-') {  }
626              p[size] = pubkey[i];  
627              size++;  
628          }  /* Save the keyserver config file in @conf. */
629          else if (pubkey[i] == ' ') {  int
630              p[size] = '+';  kserver_save_conf (const char *conf)
631              size++;  {
632          }      FILE *fp;
633          else {      int pos;
634              sprintf(numbuf, "%%%02X", pubkey[i]);  
635              for (j = 0; j<strlen(numbuf); j++) {      fp = fopen (conf, "wb");
636                  p[size] = numbuf[j];      if (!fp) {
637                  size++;          msg_box (NULL, _("Could not save keyserver.conf file"),
638              }                   _("Keyserver"), MB_ERR);
639          }          return -1;
640      }      }
641      p[size] = '\0';  
642      *newlen = size;      fprintf (fp, "# do NOT manually modify this file, it will be "
643      return p;                   "generated automatically!!\r\n");
644  } /* kserver_urlencode */      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
645            if (!server[pos].used)
646                continue;
647  /*          fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
648   * Format a request for the given keyid (send).      }
649   */      fclose (fp);
650  static char*      return 0;
651  kserver_send_request (const char *hostname, u16 port, const char *pubkey, int octets)  }
652  {  
653      char *request = NULL, *enc_pubkey = NULL;  
654      int reqlen, enc_octets;  /* Return the specified keyserver config setting @key as an integer. */
655        static int
656      if (debug)  get_conf_kserver_int (const char *key)
657          log_f ("kserver_send_request: %s:%d\n", hostname, port);  {
658      if (!port)      char *p;
659          port = HKP_PORT;      int val = 0;
660      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);  
661      request = new char[reqlen];      p = get_reg_entry_keyserver (key);
662      if (!request)      if (p && *p)
663          BUG (0);          val = atoi (p);
664      enc_pubkey = kserver_urlencode (pubkey, octets, &enc_octets);      free_if_alloc (p);
665      if (!enc_pubkey || !enc_octets) {      return val;
666          free_if_alloc (request);  }
667          return NULL;  
668      }  
669        /* Read the proxy configuration and store it into @prox. */
670      if (proxy.user) {  static void
671          _snprintf (request, reqlen-1,  read_proxy_config (keyserver_proxy_t prox)
672                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"  {
673                     "Referer: \r\n"      char *proto;
674                     "User-Agent: WinPT/W32\r\n"  
675                     "Host: %s:%d\r\n"      if (!prox)
676                     "Proxy-Authorization: Basic %s\r\n"          return;
677                     "Content-type: application/x-www-form-urlencoded\r\n"      
678                     "Content-length: %d\r\n"      proto = get_reg_entry_keyserver("Proto");
679                     "\r\n"      if (proto != NULL && strlen (proto) > 0)
680                     "keytext=%s"          prox->proto = atoi (proto);
681                     "\n",      else
682                     skip_type_prefix (hostname), port, hostname, port,          prox->proto = PROXY_PROTO_NONE;
683                     proxy.base64_user, enc_octets+9, enc_pubkey);      free_if_alloc (proto);
684      }      free_if_alloc (prox->host);
685      else {      prox->host = get_reg_entry_keyserver ("Host");
686          _snprintf (request, reqlen-1,      free_if_alloc (prox->user);
687                     "POST /pks/add HTTP/1.0\r\n"      prox->user = get_reg_entry_keyserver ("User");
688                     "Referer: \r\n"      free_if_alloc (prox->pass);
689                     "User-Agent: WinPT/W32\r\n"      prox->pass = get_reg_entry_keyserver ("Pass");
690                     "Host: %s:%d\r\n"      prox->port = get_conf_kserver_int ("Port");
691                     "Content-type: application/x-www-form-urlencoded\r\n"  }
692                     "Content-length: %d\r\n"  
693                     "\r\n"  
694                     "keytext=%s"  /* Load the keyserver config file @conf. */
695                     "\n",  int
696                     skip_type_prefix (hostname), port, enc_octets+9, enc_pubkey);  kserver_load_conf (const char *conf)
697      }  {    
698      free_if_alloc (enc_pubkey);      FILE *fp;
699      if (debug)      char buf[1024], *s, *p;
700          log_f("%s\n", request);      char *user = NULL, *pass = NULL;    
701      return request;      int no_config=0, chk_pos=0;
702  } /* kserver_send_request */      int pos;
703        
704        for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
705  /*          server[pos].used = 0;
706   * Interface receiving a public key.          server[pos].port = HKP_PORT;
707   */      }
708  int      
709  kserver_recvkey (const char *hostname, u16 port, const char *keyid, char *key, int maxkeylen)      fp = fopen (conf, "rb");
710  {            if (!fp) {
711      int rc, n;          for (pos = 0; server_list[pos]; pos++) {
712      int conn_fd;              server[pos].used = 1;
713      char *request = NULL;              server[pos].name = m_strdup (server_list[pos]);
714                    server[pos].proto = proto_from_URL (server_list[pos]);
715      if (!port)          }
716          port = HKP_PORT;          no_config=1;
717      hkp_err = 0; /* reset */          }
718      rc = kserver_connect (hostname, port, &conn_fd);      read_proxy_config (&proxy);
719      if (rc)      if (user && pass)
720          goto leave;          update_proxy_user (user, pass);
721            else if (user && !pass || !user && pass) {
722      request = new char[300+1];          msg_box (NULL, _("Invalid proxy configuration. "
723      if (!request)                           "You need to set a user and a password "
724          BUG (0);                           "to use proxy authentication!"),
725                                 _("Proxy Error"), MB_ERR);
726      if (proxy.host && proxy.user) {      }
727          _snprintf (request, 300,      /* check if the host has a http:// prefix and skip it */
728              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
729              "Proxy-Authorization: Basic %s\r\n\r\n",          char *host = m_strdup (proxy.host+7);
730              skip_type_prefix (hostname), port, keyid, proxy.base64_user);          free_if_alloc (proxy.host);
731      }          proxy.host = host;
732      else if (proxy.host) {      }
733          _snprintf (request, 300,      free_if_alloc (user);
734              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",      free_if_alloc (pass);
735              skip_type_prefix (hostname), port, keyid);      
736      }          pos = 0;
737      else {      while (fp && !feof (fp)) {
738          _snprintf (request, 300,          s = fgets (buf, DIM (buf)-1, fp);
739              "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);          if (!s)
740      }                break;
741      if (debug)          if (strstr (buf, "\r\n"))
742          log_f ("%s\n", request);              buf[strlen (buf)-2] = '\0';
743                if (strstr (buf, "\n"))
744      rc = sock_write (conn_fd, request, strlen (request));              buf[strlen (buf)-1] = '\0';
745      if (rc == SOCKET_ERROR) {          s = (char *)skip_whitespace (buf);
746          rc = WPTERR_WINSOCK_RECVKEY;          if (*s == '#' || strlen (s) < 7)
747          goto leave;              continue;
748      }          chk_pos = check_URL (s);
749                if (!chk_pos) {
750      rc = sock_read( conn_fd, key, maxkeylen, &n );              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
751      if( rc == SOCKET_ERROR ) {                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
752          rc = WPTERR_WINSOCK_RECVKEY;                               _("Keyserver Error"), MB_ERR);
753          goto leave;              continue;
754      }          }
755                p = strchr (s+chk_pos, ':');
756      if( debug )          server[pos].used = 1;
757          log_f("%s\n", key);          server[pos].proto = proto_from_URL (s);
758                server[pos].port = port_from_proto (server[pos].proto);
759      rc = check_hkp_response( key, 1 );          if (!p)
760      if( rc )              server[pos].name = m_strdup (s);
761          goto leave;          else {      
762                    server[pos].port = atol (p+1);
763      WSASetLastError( 0 );              if (server[pos].port < 0 || server[pos].port > 65536)
764                        server[pos].port = HKP_PORT;
765  leave:              server[pos].name = safe_alloc ((p-s)+2);
766      closesocket( conn_fd );              memset (server[pos].name, 0, (p-s)+2);
767      free_if_alloc( request );              memcpy (server[pos].name, s, (p-s));
768      return rc;          }
769  } /* kserver_recvkey */          pos++;
770            if (pos > MAX_KEYSERVERS) {
771                msg_box (NULL, _("The keyserver limit is exceeded"),
772  /*                       _("Keyserver Warning"), MB_INFO);
773   * Interface to send a public key.              break;
774   */          }
775  int      }
776  kserver_sendkey (const char *hostname, u16 port, const char *pubkey, int len )      if (fp)
777  {          fclose (fp);
778      int n, rc;      if (!pos) {
779      int conn_fd;          /* only issue an error if the config file exist but
780      char *request = NULL;             it has no valid entries. */
781      char log[2048];          keyserver_set_default (NULL, HKP_PORT);
782                if (!no_config)
783      hkp_err = 0; /* reset */              return WPTERR_CONFIG_FILE;
784      rc = kserver_connect (hostname, port, &conn_fd);      }
785      if (rc)  
786          goto leave;      return 0;
787        }
788      request = kserver_send_request (hostname, port, pubkey, len);  
789      if( request == NULL ) {  
790          rc = WPTERR_GENERAL;  /* Connect to the keyserver @hostname (port @port).
791          goto leave;         Return value: 0 on success */
792      }  int
793        kserver_connect (const char *hostname, WORD port, int *conn_fd)
794      rc = sock_write( conn_fd, request, lstrlen(request) );  {        
795      if( rc == SOCKET_ERROR ) {      struct hostent *hp;
796          rc = WPTERR_WINSOCK_SENDKEY;      struct sockaddr_in sock;
797          goto leave;          char host[128] = {0};
798      }      DWORD iaddr;
799            bool use_proxy = proxy.host != NULL;
800      rc = sock_read( conn_fd, log, sizeof (log)-1, &n );      int rc, fd;
801      if( rc == SOCKET_ERROR ) {  
802          rc = WPTERR_WINSOCK_SENDKEY;      if (!port)
803          goto leave;          port = HKP_PORT;
804      }      if (conn_fd)
805      if (debug)          *conn_fd = 0;
806          log_f("%s\n", log);      hostname = skip_type_prefix (hostname);
807            log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
808      rc = check_hkp_response( log, 0 );      
809      if( rc )      if (use_proxy && proxy.proto == PROXY_PROTO_HTTP)
810          goto leave;          port = proxy.port;
811            memset (&sock, 0, sizeof (sock));
812      WSASetLastError( 0 );      sock.sin_family = AF_INET;
813            sock.sin_port = htons (port);
814  leave:      if (use_proxy)
815      closesocket( conn_fd );          strncpy (host, proxy.host, DIM (host)-1);
816      free_if_alloc( request );      else
817      return rc;          strncpy (host, hostname, DIM (host)-1);
818  } /* kserver_sendkey */  
819        if ((iaddr = inet_addr (host)) != INADDR_NONE)
820            memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
821  int      else if ((hp = gethostbyname (host))) {
822  kserver_search_init (const char * hostname, u16 port, const char * keyid, int * conn_fd)          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
823  {              log_debug ("gethostbyname: unknown address type.\r\n");
824      int rc, sock_fd;              return WPTERR_WINSOCK_RESOLVE;
825      char * request = NULL;          }
826                memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
827      rc = kserver_connect (hostname, port, &sock_fd);      }
828      if (rc) {      else {
829          *conn_fd = 0;          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
830          goto leave;          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_RESOLVE;
831      }      }
832            fd = socket (AF_INET, SOCK_STREAM, 0);
833      request = new char[300+1];      if (fd == INVALID_SOCKET)  
834      if (!request)          return WPTERR_WINSOCK_SOCKET;
835          BUG (0);      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
836            if (rc == SOCKET_ERROR) {
837      if (proxy.host && proxy.user) {          log_debug ("connect: failed ec=%d.\r\n", net_errno);
838          _snprintf (request, 300,          closesocket (fd);
839              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_CONNECT;
840              "Proxy-Authorization: Basic %s\r\n\r\n",      }
841              skip_type_prefix (hostname), port, keyid, proxy.base64_user);  
842      }          if (proxy.proto == PROXY_PROTO_SOCKS5) {
843      else if (proxy.host) {          /* XXX: finish code and provide errors constants. */
844          _snprintf (request, 300,          rc = socks_handshake (&proxy, fd, hostname, port);
845              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",          if (rc) {
846              skip_type_prefix (hostname), port, keyid);              closesocket (fd);
847      }              return WPTERR_GENERAL;
848      else {          }
849          _snprintf (request, 300,      }
850                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n", keyid);  
851      }      if (conn_fd)
852                *conn_fd = fd;
853      if (debug)      WSASetLastError (0);
854          log_f("%s\n", request);      return 0;
855        }
856      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {  
857          rc = WPTERR_GENERAL;  
858          goto leave;  /* Check if the URL needs to be encoded or not. */
859      }  static bool
860        URL_must_encoded (const char *url)
861      *conn_fd = sock_fd;  {
862            if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
863  leave:          return true;
864      free_if_alloc (request);      return false;
865      return rc;  }
866  } /* kserver_search_init */  
867    
868    /* Perform URL encoding of the given data. */
869  int  static char*
870  kserver_search_chkresp (int fd)  URL_encode (const char *url, DWORD ulen, DWORD *ret_nlen)
871  {  {
872      char buf[128];      gpgme_data_t hd;
873      int n=0, i=0;      char numbuf[5], *p;
874        size_t i;
875      /* parse response 'HTTP/1.0 500 OK' */      int nlen;
876      if (sock_getline (fd, buf, 127, &n))  
877          return WPTERR_KEYSERVER_NOTFOUND;      if (gpgme_data_new (&hd))
878      if (strncmp (buf, "HTTP/1.", 7))          BUG (0);
879          return WPTERR_KEYSERVER_NOTFOUND;      for (i=0; i < ulen; i++) {
880      i = 8+1;          if (isalnum (url[i]) || url[i] == '-')
881      if (strncmp (buf+i, "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 uid_len, 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), &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              pos = p-buf+1;      int reqlen;
907          memcpy (key->keyid, buf+pos, 8);  
908          key->keyid[8] = '\0';      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
909          p = strstr (buf, "</a>");  
910          if (p)      if (!port)
911              pos = p-buf+5;          port = HKP_PORT;
912          memcpy (key->date, buf+pos, 10);      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
913          key->date[10] = '\0';      reqlen = 2*strlen (hostname) + 2*32/*port*/ + enc_octets + 32 /*len*/ + 1;
914          pos += 10;      
915          p = buf+pos+1;      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
916          while (p && *p != '>')          fmt = "POST http://%s:%d/pks/add HTTP/1.0\r\n"
917              p++;                "Referer: \r\n"
918          p++;                "User-Agent: WinPT/W32\r\n"
919          uid_len = strlen (p) - 10;                "Host: %s:%d\r\n"
920          memcpy (key->uid, p, uid_len);                "Proxy-Authorization: Basic %s\r\n"
921          key->uid[uid_len] = '\0';                "Content-type: application/x-www-form-urlencoded\r\n"
922          strcat (key->uid, ">");                "Content-length: %d\r\n"
923          p = strchr (key->uid, '&');                "\r\n"
924          if (p) {                "keytext=%s"
925              key->uid[(p-key->uid)] = '<';                "\r\n";
926              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4, strlen (key->uid)-3);          reqlen += strlen (fmt) + strlen (proxy.base64_user) + 1;
927          }          request = safe_alloc (reqlen+1);
928      }          _snprintf (request, reqlen, fmt,
929      else {                     skip_type_prefix (hostname), port, hostname, port,
930          key->bits = 0;                     proxy.base64_user, enc_octets+9, enc_pubkey);
931          memset (key, 0, sizeof *key);      }
932      }      else {
933                fmt = "POST /pks/add HTTP/1.0\r\n"
934      return 0;                "Referer: \r\n"
935  } /* kserver_search */                "User-Agent: WinPT/W32\r\n"
936                  "Host: %s:%d\r\n"
937                  "Content-type: application/x-www-form-urlencoded\r\n"
938  static int                "Content-length: %d\r\n"
939  add_node( keyserver_cfgfile *cfg, const char *entry )                "\r\n"
940  {                "keytext=%s"
941      keyserver_node *node;                "\r\n";
942      char *p = NULL;          reqlen += strlen (fmt)+1;
943                request = safe_alloc (reqlen+1);
944      p = strchr( entry, '=' );          _snprintf (request, reqlen, fmt,
945      if( p == NULL )                     skip_type_prefix (hostname), port,
946          return WPTERR_GENERAL;                       enc_octets+9, enc_pubkey);
947      node = new keyserver_node;      }
948      if( !node )  
949          BUG( NULL );      free_if_alloc (enc_pubkey);
950            log_debug ("request:\r\n%s\r\n", request);
951      memset( node, 0, sizeof *node );      return request;
952      node->used = 1;  }
953        
954      node->host.used = 1;  
955      node->host.proto = proto_from_URL( entry );  /* Interface for receiving a public key. */
956      memcpy( node->host.name, entry+7, p-entry-7 );  int
957      node->next = cfg->list;  kserver_recvkey (const char *hostname, WORD port, const char *keyid,
958      cfg->list = node;                   char **r_key, int *r_keylen)
959        {
960      return 0;      const char *fmt;
961  } /* add_node */      char *request = NULL;
962        int conn_fd;
963        int rc, reqlen;
964  void  
965  kserver_change_proxy( keyserver_proxy_ctx *ctx )      if (!port)
966  {              port = HKP_PORT;
967      proxy.port = ctx->port;      hkp_err = 0; /* reset */
968      free_if_alloc (proxy.host);      rc = kserver_connect (hostname, port, &conn_fd);
969      proxy.host = ctx->host? m_strdup( ctx->host ) : NULL;      if (rc)
970      free_if_alloc( proxy.pass );          goto leave;
971      proxy.pass = ctx->pass? m_strdup( ctx->pass ) : NULL;  
972      free_if_alloc( proxy.user );      reqlen = strlen (hostname)+32+strlen (keyid)+1;
973      proxy.user = ctx->user? m_strdup( ctx->user ) : NULL;      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
974      set_reg_proxy_prefs( proxy.host, proxy.port, proxy.user, proxy.pass );          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"
975  } /* kserver_change_proxy */                "Proxy-Authorization: Basic %s\r\n\r\n";
976            reqlen =+ strlen (fmt) + strlen (proxy.base64_user)+1;
977            request = safe_alloc (reqlen+1);
978  int          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
979  kserver_read_config( const char *fname, keyserver_cfgfile **ret_cfg )                     keyid, proxy.base64_user);
980  {      }
981      FILE *fp;      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
982      keyserver_cfgfile *cfg;          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
983      char buf[256];          reqlen += strlen (fmt)+1;
984      int rc = 0;          request = safe_alloc (reqlen+1);
985                _snprintf (request, reqlen, fmt, skip_type_prefix (hostname),
986      *ret_cfg = NULL;                                           port, keyid);
987      fp = fopen( fname, "rb" );      }
988      if( fp == NULL )      else {
989          return WPTERR_FILE_OPEN;          fmt = "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
990                reqlen += strlen (fmt)+1;
991      cfg = new keyserver_cfgfile;          request = safe_alloc (reqlen+1);
992      if ( !cfg )          _snprintf (request, reqlen, fmt, keyid);
993          BUG( NULL );      }
994      memset( cfg, 0, sizeof *cfg );  
995            log_debug ("request:\r\n%s\r\n", request);
996      while ( !feof( fp ) ) {      
997          if ( fgets( buf, sizeof(buf)-1, fp ) == NULL )      rc = sock_write (conn_fd, request, strlen (request));
998              break;      if (rc == SOCKET_ERROR) {
999          if ( *buf == '\r' || *buf == '\n' || *buf == '#' )          rc = WPTERR_WINSOCK_RECVKEY;
1000              continue;          goto leave;
1001          buf[strlen(buf) -2] = '\0';      }
1002          if ( !strncmp( buf, "use_proxy=", 10 ) ) {      
1003              char *p = strchr(buf, ':');      rc = sock_read_ext (conn_fd, r_key, r_keylen);
1004              if (!p)      if (rc == SOCKET_ERROR) {
1005                  continue;          rc = WPTERR_WINSOCK_RECVKEY;
1006              cfg->proxy.port = atol( buf+(p-buf+1) );          goto leave;
1007              buf[p-buf] = '\0';      }
1008              cfg->proxy.host = m_strdup( buf+10 );  
1009          }      log_debug ("response:\r\n%s\r\n", *r_key);
1010          else if ( !strncmp( buf, "proxy_user=", 11 ) )      rc = check_hkp_response (*r_key, 1);
1011              cfg->proxy.user = m_strdup( buf+11 );      if (rc)
1012          else if ( !strncmp( buf, "proxy_pass=", 11 ) )          goto leave;
1013              cfg->proxy.pass = m_strdup( buf+11 );      
1014          if ( !strncmp( buf, "http://", 7 )      WSASetLastError (0);
1015              || !strncmp( buf, "hkp://", 6 )      
1016              || !strncmp( buf, "ldap://", 7 ) ) {  leave:
1017              add_node( cfg, buf );      closesocket (conn_fd);
1018              cfg->nlist++;      free_if_alloc (request);
1019          }      return rc;
1020      }  }
1021        
1022      fclose( fp );  
1023      *ret_cfg = cfg;  /* Interface to send a public key. */
1024        int
1025      return rc;  kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )
1026  } /* kserver_read_config */  {
1027        char *request = NULL;
1028        char log[2048] = {0};
1029  int      int conn_fd, n;
1030  kserver_write_config( const char * fname, keyserver_cfgfile * cfg )      int rc;
1031  {      
1032            hkp_err = 0; /* reset */
1033      return 0;      rc = kserver_connect (hostname, port, &conn_fd);
1034  }      if (rc)
1035            goto leave;
1036        
1037  void      request = kserver_send_request (hostname, port, pubkey, len);
1038  kserver_cfgfile_release( keyserver_cfgfile *cfg )      if (request == NULL) {
1039  {                rc = WPTERR_GENERAL;
1040      keyserver_node *k, *k2;          goto leave;    
1041        }
1042      proxy_release( &cfg->proxy );      
1043      for( k = cfg->list; cfg->nlist--; k = k2 ) {      rc = sock_write (conn_fd, request, strlen (request));
1044          k2 = k->next;      if (rc == SOCKET_ERROR) {
1045          free_if_alloc( k );              rc = WPTERR_WINSOCK_SENDKEY;
1046      }          goto leave;    
1047      free_if_alloc( cfg );      }
1048  } /* kserver_cfgfile_release */      
1049        rc = sock_read (conn_fd, log, DIM (log)-1, &n);
1050        if (rc == SOCKET_ERROR) {
1051  void          rc = WPTERR_WINSOCK_SENDKEY;
1052  proxy_release( keyserver_proxy_ctx *ctx )          goto leave;
1053  {      }
1054      free_if_alloc( ctx->host );  
1055      free_if_alloc( ctx->pass );      log_debug ("kserver_sendkey: read %d bytes\r\n%s\r\n", n, log);
1056      free_if_alloc( ctx->user );      rc = check_hkp_response (log, 0);
1057  } /* proxy_release */      if (rc)
1058            goto leave;
1059        
1060  int      WSASetLastError (0);
1061  ldap_recvkey (const char * host, const char * keyid, char * key, int maxkeylen)      
1062  {  leave:
1063      const char *s;      closesocket (conn_fd);
1064      char *ksprg = NULL, *p = NULL;      free_if_alloc (request);
1065      char temp[512], outf[512];      return rc;
1066      FILE * inp;  }
1067      int rc, start_key = 0;  
1068      STARTUPINFO si;  
1069      PROCESS_INFORMATION pi;  /* Check keyserver response. */
1070    static int
1071      p = get_gnupg_path ();  kserver_search_chkresp (int fd)
1072      ksprg = new char[strlen (p) + 1 + 128];  {
1073      if (!ksprg)      char buf[128];
1074          BUG (0);      int n=0;
1075      strcpy (ksprg, p);      
1076      strcat (ksprg, "\\");      /* parse response 'HTTP/1.0 500 OK' */
1077      strcat (ksprg, "gpgkeys_ldap.exe");      if (sock_getline (fd, buf, DIM (buf)-1, &n))
1078      free_if_alloc (p);          return WPTERR_KEYSERVER_NOTFOUND;
1079      if (file_exist_check (ksprg)) {  
1080          log_box ( "LDAP Keyserver Plugin", MB_ERR, "Could not find LDAP keyserver module!");      log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1081          rc = -1;      if (strncmp (buf, "HTTP/1.", 7))
1082          goto leave;          return WPTERR_KEYSERVER_NOTFOUND;
1083      }      if (strncmp (buf+(8+1), "200", 3))
1084      GetTempPath (sizeof (temp)-1, temp);          return WPTERR_KEYSERVER_NOTFOUND;
1085      strcpy (outf, temp);      return 0;
1086      strcat (outf, keyid);  }
1087      strcat (outf, ".out");  
1088      strcat (temp, keyid);  
1089      inp = fopen (temp, "w+b");  /* End the keyserver search procedure. */
1090      if( !inp ) {  void
1091          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", temp,  kserver_search_end (int conn_fd)
1092                   winpt_strerror (WPTERR_FILE_OPEN));  {
1093          rc = -1;      log_debug ("kserver_search_end: fd=%d\r\n", conn_fd);
1094          goto leave;      closesocket (conn_fd);
1095      }  }
1096      fprintf (inp,  
1097          "VERSION 0\n"  
1098          "HOST %s\n"  /* Extract the amount of keys from the info record. */
1099          "OPTION verbose\n"  static int
1100          "COMMAND GET\n"  count_keys_in_response (char *buf)
1101          "\n"  {
1102          "%s\n", host? skip_type_prefix (host): "64.94.85.200", keyid);      char *p;
1103      fclose (inp);      int recno = 0;
1104        int n = 0;
1105      memset (&si, 0, sizeof (si));  
1106      si.cb = sizeof (si);      /* info:1:4 */
1107      si.dwFlags = STARTF_USESHOWWINDOW;      if (strncmp (buf, "info", 4))
1108      si.wShowWindow = SW_HIDE;          return 0;
1109      memset (&pi, 0, sizeof (pi));      p = strtok (buf, ":");
1110      p = new char[strlen (ksprg) + strlen (temp) + strlen (outf) + 32];      while (p != NULL) {
1111      sprintf (p, "%s -o %s %s", ksprg, outf, temp);          recno++;
1112      rc = CreateProcess (NULL, p, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);          if (recno == 3)
1113      if (!rc) {              n = atoi (p);
1114          log_box ("LDAP Keyserver Plugin", MB_ERR, "Could not spawn process");          p = strtok (NULL, ":");
1115          rc = -1;      }
1116          goto leave;      return n;
1117      }  }
1118      CloseHandle (pi.hThread);  
1119      WaitForSingleObject (pi.hProcess, INFINITE);  
1120      CloseHandle (pi.hProcess);  /* Start the keyserver search.
1121       Connect to host @hostname and port @port.
1122      inp = fopen (outf, "rb");     The pattern are given in @pattern.
1123      if (!inp) {     The socket is returned in @conn_fd and @nkeys contains
1124          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,     the amount of keys which were found. */
1125                   winpt_strerror (WPTERR_FILE_OPEN));  int
1126          rc = -1;  kserver_search_begin (const char *hostname, WORD port,
1127          goto leave;                        const char *pattern, int *conn_fd, int *nkeys)
1128      }  {
1129      memset (key, 0, maxkeylen);      const char *fmt;
1130      while( !feof( inp ) ) {      char *request = NULL;
1131          s = fgets( temp, sizeof (temp)-1, inp );      char *enc_patt = NULL;
1132          if( !s )      char status[128];
1133              break;      int rc, sock_fd;
1134          if( !start_key && strstr( s, "KEY" ) && strstr( s, "BEGIN" ) ) {      int reqlen;
1135              start_key = 1;      
1136              continue;      *conn_fd = 0;
1137          }        
1138          if( !start_key )      rc = kserver_connect (hostname, port, &sock_fd);
1139              continue;      if (rc)
1140          strcat( key, temp );          goto leave;
1141          maxkeylen -= strlen( temp );  
1142          if( maxkeylen < 0 || (strstr( s, "KEY" ) && strstr( s, "END" )) )                enc_patt = URL_encode (pattern, strlen (pattern), NULL);
1143              break;      reqlen = strlen (enc_patt) + strlen (hostname) + 32 + 1;
1144      }  
1145      fclose( inp );          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  leave:                "Proxy-Authorization: Basic %s\r\n\r\n";
1148      if( !strlen( key ) )          reqlen += strlen (proxy.base64_user) + strlen (fmt) + 1;
1149          rc = WPTERR_WINSOCK_RECVKEY;          request = safe_alloc (reqlen+1);
1150      free_if_alloc( p );          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
1151      free_if_alloc( ksprg );                     enc_patt, proxy.base64_user);
1152      return rc;      }    
1153  } /* ldap_recvkey */      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
1154            fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1155            reqlen += strlen (fmt)+1;
1156  static int          request = safe_alloc (reqlen+1);
1157  finger_readline (int fd, char * buf, int nbytes)          _snprintf (request, reqlen, skip_type_prefix (hostname), port,
1158  {                              enc_patt);
1159      char c = 0;      }
1160      int n, pos = 0;      else {
1161                fmt = "GET /pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1162      while (nbytes > 0) {          reqlen += strlen (fmt)+1;
1163          n = recv (fd, &c, 1, 0);          request = safe_alloc (reqlen+1);
1164          if (n <= 0)          _snprintf (request, reqlen, fmt, enc_patt);
1165              break;      }
1166          if (c == '\n')  
1167              break;      log_debug ("kserver_search_begin:\r\n%s\r\n", request);
1168          buf[pos++] = c;      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1169          nbytes--;          rc = WPTERR_GENERAL;
1170      }          goto leave;
1171      if (nbytes > 0)      }
1172          buf[pos++] = '\0';      
1173      if (n <= 0)      rc = kserver_search_chkresp (sock_fd);
1174          pos = n;      if (rc) {
1175      return pos;          closesocket (sock_fd);
1176  }          sock_fd = 0;
1177            goto leave;
1178        }
1179  int  
1180  finger_recvkey (const char * host, const char * user, char * key, int maxkeylen)      /* Skip all lines until we reach the "info:" record. */
1181  {      for (;;) {
1182      struct hostent * hp;          if (sock_getline (sock_fd, status, DIM (status)-1, &reqlen)) {  
1183      struct sockaddr_in saddr;              log_debug ("kserver_search_begin: retrieving status line failed.\r\n");
1184      char buf[128];              closesocket (sock_fd);
1185      int fd, nread;              sock_fd = 0;
1186      int start_key = 0;              rc = WPTERR_GENERAL;
1187      int rc=0;              break;
1188            }
1189      fd = socket (PF_INET, SOCK_STREAM, 0);          if (!strncmp (status, "info:", 5))
1190      if (fd == -1)              break;
1191          return WPTERR_WINSOCK_SOCKET;      }
1192      hp = gethostbyname (skip_type_prefix (host));  
1193      if (!hp) {      if (!rc)
1194          closesocket (fd);          *nkeys = count_keys_in_response (status);
1195          return WPTERR_WINSOCK_RESOLVE;      *conn_fd = sock_fd;
1196      }      
1197    leave:
1198      memset (&saddr, 0, sizeof (saddr));      free_if_alloc (request);
1199      saddr.sin_family = AF_INET;      free_if_alloc (enc_patt);
1200      saddr.sin_port = htons (FINGER_PORT);      return rc;
1201      saddr.sin_addr = *(struct in_addr *)hp->h_addr;  }
1202      if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {  
1203          closesocket (fd);  
1204          return WPTERR_WINSOCK_CONNECT;  /* Parse a single pub record returned by the keyserver. */
1205      }  static void
1206      send (fd, user, strlen (user), 0);  parse_pub_record (keyserver_key_s *key, char *buf)
1207      send (fd, "\r\n", 2, 0);  {
1208        enum pub_rec_t {ID=1, KEYID, ALGO, SIZE, CREATE, EXPIRE};
1209      memset (key, 0, maxkeylen);      char *p;
1210      while (maxkeylen > 0) {      int recno = 0;
1211          nread = finger_readline (fd, buf, sizeof (buf)-1);      int off = 0;
1212          if (nread <= 0)  
1213              break;      /* pub:BF3DF9B4:17:1024:925411133:: */
1214          strcat (buf, "\n");      p = strtok (buf, ":");
1215          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {      while (p != NULL) {
1216              strcat (key, buf);          recno++;
1217              start_key = 1;          switch (recno) {
1218              maxkeylen -= nread;          case ID:
1219          }              break;
1220          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {  
1221              strcat (key, buf);          case KEYID:
1222              start_key--;              /* If for any reason the returned record actually contains
1223              maxkeylen -= nread;                 a fingerprint instead of a key ID, we truncate the fpr. */
1224              break;              off = strlen (p) == 40? 32 : 0;
1225          }              free_if_alloc (key->keyid);
1226          else if (start_key) {              key->keyid = m_strdup (p+off);
1227              strcat (key, buf);              break;
1228              maxkeylen -= nread;  
1229          }          case ALGO:
1230      }              key->algo = atoi (p);
1231      closesocket (fd);              break;
1232      if (start_key != 0)              
1233          rc = WPTERR_WINSOCK_RECVKEY;          case SIZE:
1234      return rc;              key->bits = atoi (p);
1235  }              break;
1236    
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.2  
changed lines
  Added in v.271

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26