/[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 22 by twoaday, Wed Aug 10 11:33:35 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      int n = 0;          else {
355                nread = recv (fd, buf, DIM (buf), 0);
356      n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;              if (nread == SOCKET_ERROR)
357      free_if_alloc (proxy.base64_user);                  return SOCKET_ERROR;
358      proxy.base64_user = new char[n];              else if (!nread)
359      if (!proxy.base64_user)                  break;
360          BUG (0);              gpgme_data_write (dh, buf, nread);
361      _snprintf (t, sizeof (t)-1, "%s:%s", proxy_user, proxy_pass);          }
362      base64_encode (t, proxy.base64_user, 257);      }
363      free_if_alloc (proxy.user);  
364      free_if_alloc (proxy.pass);      *buffer = data_release_and_get_mem (dh, r_bufferlen);
365      proxy.user = m_strdup (proxy_user);      return 0;
366      proxy.pass = m_strdup (proxy_pass);  }
367  } /* kserver_update_proxyuser */  
368    
369    /* Write the buffer @buf with the length @buflen to a socket @fd. */
370  static int  static int
371  check_URL (const char * buf)  sock_write (int fd, const char *buf, int buflen)
372  {  {
373      if (strlen (buf) < 7)      DWORD nwritten;
374          return -1;      int nleft = buflen;
375      if (!strstr (buf, "ldap://")  
376          && !strstr (buf, "http://")      while (nleft > 0) {
377          && !strstr (buf, "finger://")          nwritten = send (fd, buf, nleft, 0);
378          && !strstr (buf, "hkp://"))          if (nwritten == SOCKET_ERROR) {
379          return -1;              log_debug ("sock_write: send() failed ec=%d\r\n", net_errno);
380      return 0;              return SOCKET_ERROR;
381  } /* check_URL */          }
382                nleft -= nwritten;
383            buf += nwritten;
384  static int      }
385  port_from_proto (int proto)  
386  {      return 0;
387      switch (proto) {  }
388      case KSPROTO_LDAP: return 0;  
389      case KSPROTO_FINGER: return FINGER_PORT;  
390      case KSPROTO_HTTP: return HKP_PORT;  /* Initialize the Winsock2 interface.*/
391      }  int
392      return 0;  wsock_init (void)
393  }  {
394        WSADATA wsa;
395    
396  static int      if (WSAStartup (0x202, &wsa)) {
397  proto_from_URL (const char * buf)          log_debug ("wsock_init: WSAStartup failed ec=%d\r\n", net_errno);
398  {          return WPTERR_WINSOCK_INIT;
399      if (strstr( buf, "ldap"))      }
400          return KSPROTO_LDAP;      return 0;
401      else if (strstr( buf, "finger"))  }
402          return KSPROTO_FINGER;  
403      return KSPROTO_HTTP;  
404  } /* proto_from_URL */  /* Cleanup the Winsock2 interface. */
405    void
406    wsock_end (void)
407  void  {
408  keyserver_set_default (const char * hostname, u16 port)      char *p;
409  {      int i;
410      if (hostname) {  
411          free_if_alloc (default_keyserver);  #ifdef WINPT_MOBILE
412          default_keyserver = m_strdup (hostname);      p = m_strdup ("keyserver.conf");
413          if (!default_keyserver)  #else
414              BUG (0);      p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);
415          default_keyserver_port = port;  #endif
416      }      kserver_save_conf (p);
417      server[0].name =  m_strdup (default_keyserver);      free_if_alloc (p);
418      server[0].used = 1;      free_if_alloc (default_keyserver);
419      server[0].port = port;      for (i=0; i < MAX_KEYSERVERS; i++) {
420      server[0].proto = proto_from_URL (default_keyserver);          if (server[i].used && server[i].name != NULL)
421  } /* keyserver_set_default */              free_if_alloc (server[i].name);
422        }
423        kserver_proxy_release (&proxy);
424  static const char *      WSACleanup ();
425  skip_whitespace (const char * str)      log_debug ("wsock_end: cleanup finished.\r\n");
426  {  }
427      while (str && *str)  
428      {  
429          if (*str == ' ' ||  /* Return a string representation of a winsock error. */
430              *str == '\t' ||  const char*
431              *str == '\n' ||  wsock_strerror (void)
432              *str == '\r')  {
433          {      int ec = WSAGetLastError ();
434              str++;      
435              continue;      if (!ec)
436          }          return "";
437          break;      switch (ec) {
438      }      case WSAENETDOWN:
439      return str;          return _("Network unreachable");
440  }  
441        case WSAEHOSTUNREACH:
442            return _("Host unreachable");
443  int  
444  kserver_load_conf (const char * conf)      case WSAHOST_NOT_FOUND:
445  {          return _("Could not resolve host name");
446      struct stat statbuf;  
447      FILE *fp;      case WSAECONNREFUSED:
448      char buf[1024], * s, * p;          return _("Connection refused");
449      char *user = NULL, *pass = NULL;      
450      int pos, proxy_auth = 0;      case WSAETIMEDOUT:
451      int no_config=0, chk_pos=0;      case WSAECONNABORTED:
452                return _("Connection timeout");
453      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {  
454          server[pos].used = 0;      case WSAENETRESET:
455          server[pos].port = HKP_PORT;      case WSAECONNRESET:    
456      }          return _("Connection resetted by peer");
457        
458      fp = fopen (conf, "rb");      case WSAESHUTDOWN:
459      if (!fp) {          return _("Socket has been shutdown");
460          for (pos = 0; server_list[pos]; pos++) {  
461              server[pos].used = 1;      default:
462              server[pos].name = m_strdup (server_list[pos]);          break;
463              server[pos].proto = proto_from_URL (server_list[pos]);      }
464          }  
465          no_config=1;      return "";
466      }  }
467      get_reg_proxy_prefs (&proxy.host, &proxy.port, &user, &pass);  
468      if (user && pass)  
469          kserver_update_proxyuser (user, pass);    /* Set default socket timeout for all reading operations. */
470      else if (user && !pass || !user && pass) {  void
471          msg_box( NULL, _("Invalid proxy configuration."  kserver_set_socket_timeout (int nsec)
472                           "You need to set a user and a password"  {
473                           "to use proxy authentication!"), _("Proxy Error"), MB_ERR );      if (nsec < 0 || nsec > 3600)
474      }          nsec = 0;
475      /* check if the host has a http:// prefix and skip it */      default_socket_timeout = nsec;
476      if( proxy.host && !strncmp( proxy.host, "http://", 7 ) ) {  }
477          const char *s = proxy.host+7;  
478          char * p = m_strdup (s);  
479          if (!p)  /* Return the last keyserver error as a string. */
480              BUG (0);  const char*
481          free_if_alloc (proxy.host);  kserver_strerror (void)
482          proxy.host = p;  {      
483      }      if (hkp_err)
484      free_if_alloc (user);          return hkp_errmsg;
485      free_if_alloc (pass);      return NULL;
486        }
487      pos = 0;  
488      while( fp && !feof( fp ) ) {  
489          s = fgets (buf, sizeof (buf)-1, fp);  /* Read a keyserver from the list at index @idx.
490          if (!s)     Return value: keyserver name at the given position. */
491              break;  const char*
492          if (strstr (buf, "\r\n"))  kserver_get_hostname (int idx, int type, WORD *port)
493              buf[strlen (buf)-2] = '\0';  {
494          if (strstr (buf, "\n"))      if (type == -1) {
495              buf[strlen (buf)-1] = '\0';          *port = default_keyserver_port;
496          s = (char *)skip_whitespace (buf);          return default_keyserver;
497          if (*s == '#' || strlen (s) < 7)      }
498              continue;      else if (!type && idx < DIM (server_list)) {
499          if (check_URL (s)) {          /* XXX: handle non HKP servers. */
500              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"          *port = HKP_PORT;
501                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),          return server_list[idx];
502                               _("Keyserver Error"), MB_ERR);      }
503              continue;      return NULL;
504          }  }
505          chk_pos=6;  
506          if (strstr (s, "finger"))  
507              chk_pos = 10;  /* Check if the computer is connected to the internet.
508          p = strchr (s+chk_pos, ':');     Return 0 on success -1 otherwise. */
509          server[pos].used = 1;  int
510          server[pos].proto = proto_from_URL (s);  kserver_check_inet_connection (void)
511          server[pos].port = port_from_proto (server[pos].proto);  {
512          if (!p)      int fd;
513              server[pos].name = m_strdup (s);  
514          else {            if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {
515              server[pos].port = atol (p+1);          closesocket (fd);
516              if (server[pos].port < 0 || server[pos].port > 65536)          return 0;
517                  server[pos].port = HKP_PORT;      }
518              server[pos].name = new char [(p-s)+2];      log_debug ("kserver_check_inet_connection: no inet connection.\r\n");
519              if (!server[pos].name)      return -1;
520                  BUG (0);  }
521              memset (server[pos].name, 0, (p-s)+2);  
522              memcpy (server[pos].name, s, (p-s));  
523          }  /* If the request contains the keyid, it have to be
524          pos++;     always postfix with '0x'+keyid. This code checks
525          if (pos > MAX_KEYSERVERS)     if the keyid is a decimal value and if so if it contains
526          {     the '0x'. If not it is inserted. */
527              msg_box (NULL, _("The keyserver limit is exceeded"), _("Keyserver Warning"), MB_INFO);  const char*
528              break;  kserver_check_keyid (const char *keyid)
529          }  {      
530      }      static char id[22];
531      if (fp)  
532          fclose (fp);      if (strstr (keyid, "@"))
533      if (!pos)          return keyid; /* email address */
534      {      if (strncmp (keyid, "0x", 2)) {
535          /* only issue an error if the config file exist but it has no valid entries. */          memset (&id, 0, sizeof (id));
536          keyserver_set_default (NULL, HKP_PORT);          _snprintf (id, DIM (id)-1, "0x%s", keyid);
537          if (!no_config)          return id;
538              return WPTERR_CONFIG_FILE;        }
539      }      return keyid;
540    }
541      if (!stat (conf, &statbuf))  
542          conf_timestamp = statbuf.st_mtime;  
543      return 0;  /* Update the keyserver proxy user. */
544  } /* kserver_load_conf */  static void
545    update_proxy_user (const char *proxy_user, const char *proxy_pass)
546    {
547  const char *      char t[257]; /* user:pass = 127+1+127+1 = 257 */
548  kserver_get_proxy (int * r_port)      int n = 0;
549  {  
550      if (proxy.host) {      n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;
551          if (r_port)      free_if_alloc (proxy.base64_user);
552              *r_port = proxy.port;      proxy.base64_user = safe_alloc (n+1);
553          return proxy.host;      _snprintf (t, DIM (t)-1, "%s:%s", proxy_user, proxy_pass);
554      }      base64_encode (t, proxy.base64_user);
555      return NULL;      free_if_alloc (proxy.user);
556  } /* kserver_get_proxy */      free_if_alloc (proxy.pass);
557        proxy.user = m_strdup (proxy_user);
558        proxy.pass = m_strdup (proxy_pass);
559  const char *  }
560  kserver_get_proxy_info (int id)      
561  {  
562      switch (id) {    /* Get the port number from the given protocol. */
563      case PROXY_USER: return proxy.user;  static int
564      case PROXY_PASS: return proxy.pass;  port_from_proto (int proto)
565      }  {
566      return NULL;      switch (proto) {
567  } /* kserver_get_proxy_info */      case KSPROTO_LDAP:   return LDAP_PORT;
568        case KSPROTO_FINGER: return FINGER_PORT;
569        case KSPROTO_HTTP:   return HKP_PORT;
570  /*      }
571   * Connect to the keyserver 'hostname'.      return 0;
572   * We always use the HKP port.  }
573   */  
574  int  
575  kserver_connect (const char *hostname, u16 port, int *conn_fd)  /* Get the port number from the given URL. */
576  {  static int
577      int rc, fd;  proto_from_URL (const char *buf)
578      u32 iaddr;  {
579      char host[128] = {0};      if (strstr (buf, "ldap"))
580      struct hostent *hp;          return KSPROTO_LDAP;
581      struct sockaddr_in sock;      else if (strstr (buf, "finger"))
582            return KSPROTO_FINGER;
583      if (debug)      return KSPROTO_HKP;
584          log_f ("kserver_connect: %s:%d\r\n", hostname, port);  }
585      if (!port)  
586          port = HKP_PORT;  
587      if (conn_fd)  /* Set the default keyserver.
588          *conn_fd = 0;     If @hostname is NULL, use the predefined keyserver. */
589      hostname = skip_type_prefix (hostname);  void
590        keyserver_set_default (const char *hostname, WORD port)
591      memset (&sock, 0, sizeof (sock));  {
592      sock.sin_family = AF_INET;      if (!port)
593      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);          port = HKP_PORT;
594      if (proxy.host)      if (hostname != NULL) {
595          strncpy (host, proxy.host, 127);          free_if_alloc (default_keyserver);
596      else          default_keyserver = m_strdup (hostname);
597          strncpy (host, hostname, 127);          default_keyserver_port = port;
598            }
599      if ((iaddr = inet_addr (host)) != INADDR_NONE)      if (!default_keyserver) {
600          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));          default_keyserver = m_strdup (DEF_HKP_KEYSERVER);
601      else if ((hp = gethostbyname (host))) {          default_keyserver_port = HKP_PORT;
602          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {      }
603              log_f ("gethostbyname: unknown address type.\r\n");      server[0].name =  m_strdup (default_keyserver);
604              return WPTERR_WINSOCK_RESOLVE;      server[0].used = 1;
605          }      server[0].port = port;
606          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);      server[0].proto = proto_from_URL (default_keyserver);
607      }  }
608      else {  
609          if (debug)  
610              log_f ("gethostbyname: failed.\r\n");  /* Skip all kind of whitespace chars in @str. */
611          return WPTERR_WINSOCK_RESOLVE;  static const char*
612      }  skip_whitespace (const char *str)
613      fd = socket (AF_INET, SOCK_STREAM, 0);  {
614      if (fd == INVALID_SOCKET)        while (str && *str) {
615          return WPTERR_WINSOCK_SOCKET;          if (*str == ' ' ||
616      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));              *str == '\t' ||
617      if (rc == SOCKET_ERROR) {              *str == '\n' ||
618          if (debug)              *str == '\r') {
619              log_f ("connect: failed.\r\n");              str++;
620          closesocket (fd);              continue;
621          return WPTERR_WINSOCK_CONNECT;          }
622      }          break;
623        }
624      if (conn_fd)      return str;
625          *conn_fd = fd;  }
626      WSASetLastError (0);  
627      return 0;  
628  } /* kserver_connect */  /* Save the keyserver config file in @conf. */
629    int
630    kserver_save_conf (const char *conf)
631  static char*  {
632  kserver_urlencode (const char *pubkey, size_t octets, size_t *newlen)      FILE *fp;
633  {      int pos;
634      char *p, numbuf[5];  
635      size_t j = 0;      fp = fopen (conf, "wb");
636      size_t i, size;      if (!fp) {
637                msg_box (NULL, _("Could not save keyserver.conf file"),
638      p = new char [2*octets];                   _("Keyserver"), MB_ERR);
639      if (!p)          return -1;
640          BUG (0);      }
641    
642      for (size=0, i=0; i < octets; i++) {      fprintf (fp, "# do NOT manually modify this file, it will be "
643          if (isalnum (pubkey[i]) || pubkey[i] == '-') {                   "generated automatically!!\r\n");
644              p[size] = pubkey[i];      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
645              size++;          if (!server[pos].used)
646          }              continue;
647          else if (pubkey[i] == ' ') {          fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
648              p[size] = '+';      }
649              size++;      fclose (fp);
650          }      return 0;
651          else {  }
652              sprintf(numbuf, "%%%02X", pubkey[i]);  
653              for (j = 0; j<strlen(numbuf); j++) {  
654                  p[size] = numbuf[j];  /* Return the specified keyserver config setting @key as an integer. */
655                  size++;  static int
656              }  get_conf_kserver_int (const char *key)
657          }  {
658      }      char *p;
659      p[size] = '\0';      int val = 0;
660      *newlen = size;  
661      return p;      p = get_reg_entry_keyserver (key);
662  } /* kserver_urlencode */      if (p && *p)
663            val = atoi (p);
664        free_if_alloc (p);
665  /*      return val;
666   * Format a request for the given keyid (send).  }
667   */  
668  static char*  
669  kserver_send_request (const char *hostname, u16 port, const char *pubkey, int octets)  /* Read the proxy configuration and store it into @prox. */
670  {  static void
671      char *request = NULL, *enc_pubkey = NULL;  read_proxy_config (keyserver_proxy_t prox)
672      int reqlen;  {
673      size_t enc_octets;      char *proto;
674        
675      if (debug)      if (!prox)
676          log_f ("kserver_send_request: %s:%d\n", hostname, port);          return;
677      if (!port)      
678          port = HKP_PORT;      proto = get_reg_entry_keyserver("Proto");
679      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);      if (proto != NULL && strlen (proto) > 0)
680      request = new char[reqlen];          prox->proto = atoi (proto);
681      if (!request)      else
682          BUG (0);          prox->proto = PROXY_PROTO_NONE;
683      enc_pubkey = kserver_urlencode (pubkey, octets, &enc_octets);      free_if_alloc (proto);
684      if (!enc_pubkey || !enc_octets) {      free_if_alloc (prox->host);
685          free_if_alloc (request);      prox->host = get_reg_entry_keyserver ("Host");
686          return NULL;      free_if_alloc (prox->user);
687      }      prox->user = get_reg_entry_keyserver ("User");
688            free_if_alloc (prox->pass);
689      if (proxy.user) {      prox->pass = get_reg_entry_keyserver ("Pass");
690          _snprintf (request, reqlen-1,      prox->port = get_conf_kserver_int ("Port");
691                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"  }
692                     "Referer: \r\n"  
693                     "User-Agent: WinPT/W32\r\n"  
694                     "Host: %s:%d\r\n"  /* Load the keyserver config file @conf. */
695                     "Proxy-Authorization: Basic %s\r\n"  int
696                     "Content-type: application/x-www-form-urlencoded\r\n"  kserver_load_conf (const char *conf)
697                     "Content-length: %d\r\n"  {    
698                     "\r\n"      FILE *fp;
699                     "keytext=%s"      char buf[1024], *s, *p;
700                     "\n",      char *user = NULL, *pass = NULL;    
701                     skip_type_prefix (hostname), port, hostname, port,      int no_config=0, chk_pos=0;
702                     proxy.base64_user, enc_octets+9, enc_pubkey);      int pos;
703      }      
704      else {      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
705          _snprintf (request, reqlen-1,          server[pos].used = 0;
706                     "POST /pks/add HTTP/1.0\r\n"          server[pos].port = HKP_PORT;
707                     "Referer: \r\n"      }
708                     "User-Agent: WinPT/W32\r\n"      
709                     "Host: %s:%d\r\n"      fp = fopen (conf, "rb");
710                     "Content-type: application/x-www-form-urlencoded\r\n"      if (!fp) {
711                     "Content-length: %d\r\n"          for (pos = 0; server_list[pos]; pos++) {
712                     "\r\n"              server[pos].used = 1;
713                     "keytext=%s"              server[pos].name = m_strdup (server_list[pos]);
714                     "\n",              server[pos].proto = proto_from_URL (server_list[pos]);
715                     skip_type_prefix (hostname), port, enc_octets+9, enc_pubkey);          }
716      }          no_config=1;
717      free_if_alloc (enc_pubkey);      }
718      if (debug)      read_proxy_config (&proxy);
719          log_f ("%s\n", request);      if (user && pass)
720      return request;          update_proxy_user (user, pass);
721  } /* kserver_send_request */      else if (user && !pass || !user && pass) {
722            msg_box (NULL, _("Invalid proxy configuration. "
723                             "You need to set a user and a password "
724  /*                           "to use proxy authentication!"),
725   * Interface receiving a public key.                           _("Proxy Error"), MB_ERR);
726   */      }
727  int      /* check if the host has a http:// prefix and skip it */
728  kserver_recvkey (const char *hostname, u16 port, const char *keyid, char *key, int maxkeylen)      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
729  {                char *host = m_strdup (proxy.host+7);
730      int rc, n;          free_if_alloc (proxy.host);
731      int conn_fd;          proxy.host = host;
732      char *request = NULL;      }
733            free_if_alloc (user);
734      if (!port)      free_if_alloc (pass);
735          port = HKP_PORT;      
736      hkp_err = 0; /* reset */          pos = 0;
737      rc = kserver_connect (hostname, port, &conn_fd);      while (fp && !feof (fp)) {
738      if (rc)          s = fgets (buf, DIM (buf)-1, fp);
739          goto leave;          if (!s)
740                    break;
741      request = new char[300+1];          if (strstr (buf, "\r\n"))
742      if (!request)              buf[strlen (buf)-2] = '\0';
743          BUG (0);          if (strstr (buf, "\n"))
744                    buf[strlen (buf)-1] = '\0';
745      if (proxy.host && proxy.user) {          s = (char *)skip_whitespace (buf);
746          _snprintf (request, 300,          if (*s == '#' || strlen (s) < 7)
747              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"              continue;
748              "Proxy-Authorization: Basic %s\r\n\r\n",          chk_pos = check_URL (s);
749              skip_type_prefix (hostname), port, keyid, proxy.base64_user);          if (!chk_pos) {
750      }              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
751      else if (proxy.host) {                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
752          _snprintf (request, 300,                               _("Keyserver Error"), MB_ERR);
753              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",              continue;
754              skip_type_prefix (hostname), port, keyid);          }
755      }              p = strchr (s+chk_pos, ':');
756      else {          server[pos].used = 1;
757          _snprintf (request, 300,          server[pos].proto = proto_from_URL (s);
758              "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);          server[pos].port = port_from_proto (server[pos].proto);
759      }            if (!p)
760      if (debug)              server[pos].name = m_strdup (s);
761          log_f ("%s\r\n", request);          else {      
762                    server[pos].port = atol (p+1);
763      rc = sock_write (conn_fd, request, strlen (request));              if (server[pos].port < 0 || server[pos].port > 65536)
764      if (rc == SOCKET_ERROR) {                  server[pos].port = HKP_PORT;
765          rc = WPTERR_WINSOCK_RECVKEY;              server[pos].name = safe_alloc ((p-s)+2);
766          goto leave;              memset (server[pos].name, 0, (p-s)+2);
767      }              memcpy (server[pos].name, s, (p-s));
768                }
769      rc = sock_read( conn_fd, key, maxkeylen, &n );          pos++;
770      if( rc == SOCKET_ERROR ) {          if (pos > MAX_KEYSERVERS) {
771          rc = WPTERR_WINSOCK_RECVKEY;              msg_box (NULL, _("The keyserver limit is exceeded"),
772          goto leave;                       _("Keyserver Warning"), MB_INFO);
773      }              break;
774                }
775      if (debug)      }
776          log_f("%s\r\n", key);      if (fp)
777      rc = check_hkp_response (key, 1);          fclose (fp);
778      if (rc)      if (!pos) {
779          goto leave;          /* only issue an error if the config file exist but
780                   it has no valid entries. */
781      WSASetLastError (0);          keyserver_set_default (NULL, HKP_PORT);
782                if (!no_config)
783  leave:              return WPTERR_CONFIG_FILE;
784      closesocket (conn_fd);      }
785      free_if_alloc (request);  
786      return rc;      return 0;
787  } /* kserver_recvkey */  }
788    
789    
790  /*  /* Connect to the keyserver @hostname (port @port).
791   * Interface to send a public key.     Return value: 0 on success */
792   */  int
793  int  kserver_connect (const char *hostname, WORD port, int *conn_fd)
794  kserver_sendkey (const char *hostname, u16 port, const char *pubkey, int len )  {        
795  {      struct hostent *hp;
796      int n, rc;      struct sockaddr_in sock;
797      int conn_fd;      char host[128] = {0};
798      char *request = NULL;      DWORD iaddr;
799      char log[2048];      bool use_proxy = proxy.host != NULL;
800            int rc, fd;
801      hkp_err = 0; /* reset */  
802      rc = kserver_connect (hostname, port, &conn_fd);      if (!port)
803      if (rc)          port = HKP_PORT;
804          goto leave;      if (conn_fd)
805                *conn_fd = 0;
806      request = kserver_send_request (hostname, port, pubkey, len);      hostname = skip_type_prefix (hostname);
807      if (request == NULL) {      log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
808          rc = WPTERR_GENERAL;      
809          goto leave;          if (use_proxy && proxy.proto == PROXY_PROTO_HTTP)
810      }          port = proxy.port;
811            memset (&sock, 0, sizeof (sock));
812      rc = sock_write( conn_fd, request, lstrlen(request) );      sock.sin_family = AF_INET;
813      if( rc == SOCKET_ERROR ) {      sock.sin_port = htons (port);
814          rc = WPTERR_WINSOCK_SENDKEY;      if (use_proxy)
815          goto leave;              strncpy (host, proxy.host, DIM (host)-1);
816      }      else
817                strncpy (host, hostname, DIM (host)-1);
818      rc = sock_read( conn_fd, log, sizeof (log)-1, &n );  
819      if( rc == SOCKET_ERROR ) {      if ((iaddr = inet_addr (host)) != INADDR_NONE)
820          rc = WPTERR_WINSOCK_SENDKEY;          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
821          goto leave;      else if ((hp = gethostbyname (host))) {
822      }          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
823      if (debug)              log_debug ("gethostbyname: unknown address type.\r\n");
824          log_f ("kserver_sendkey:\r\n%s\r\n", log);              return WPTERR_WINSOCK_RESOLVE;
825                }
826      rc = check_hkp_response (log, 0);          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
827      if( rc )      }
828          goto leave;      else {
829                log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
830      WSASetLastError (0);          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_RESOLVE;
831            }
832  leave:      fd = socket (AF_INET, SOCK_STREAM, 0);
833      closesocket (conn_fd);      if (fd == INVALID_SOCKET)  
834      free_if_alloc (request);          return WPTERR_WINSOCK_SOCKET;
835      return rc;      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
836  } /* kserver_sendkey */      if (rc == SOCKET_ERROR) {
837            log_debug ("connect: failed ec=%d.\r\n", net_errno);
838            closesocket (fd);
839  int          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_CONNECT;
840  kserver_search_init (const char * hostname, u16 port, const char * keyid, int * conn_fd)      }
841  {  
842      int rc, sock_fd;      if (proxy.proto == PROXY_PROTO_SOCKS5) {
843      int n=0;          /* XXX: finish code and provide errors constants. */
844      char * request = NULL;          rc = socks_handshake (&proxy, fd, hostname, port);
845                if (rc) {
846      rc = kserver_connect (hostname, port, &sock_fd);              closesocket (fd);
847      if (rc) {              return WPTERR_GENERAL;
848          *conn_fd = 0;          }
849          goto leave;      }
850      }  
851            if (conn_fd)
852      n=300;          *conn_fd = fd;
853      request = new char[n+1];      WSASetLastError (0);
854      if (!request)      return 0;
855          BUG (0);  }
856        
857      if (proxy.host && proxy.user) {  
858          _snprintf (request, n,  /* Check if the URL needs to be encoded or not. */
859              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"  static bool
860              "Proxy-Authorization: Basic %s\r\n\r\n",  URL_must_encoded (const char *url)
861              skip_type_prefix (hostname), port, keyid, proxy.base64_user);  {
862      }          if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
863      else if (proxy.host) {          return true;
864          _snprintf (request, n,      return false;
865              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",  }
866              skip_type_prefix (hostname), port, keyid);  
867      }  
868      else {  /* Perform URL encoding of the given data. */
869          _snprintf (request, n,  static char*
870                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n", keyid);  URL_encode (const char *url, DWORD ulen, DWORD *ret_nlen)
871      }  {
872            gpgme_data_t hd;
873      if (debug)      char numbuf[5], *p;
874          log_f ("kserver_search_init:\r\n%s\r\n", request);      size_t i;
875            int nlen;
876      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {  
877          rc = WPTERR_GENERAL;      if (gpgme_data_new (&hd))
878          goto leave;          BUG (0);
879      }      for (i=0; i < ulen; i++) {
880                if (isalnum (url[i]) || url[i] == '-')
881      *conn_fd = sock_fd;              gpg_data_putc (hd, url[i]);
882                else if (url[i] == ' ')
883  leave:              gpg_data_putc (hd, '+');
884      free_if_alloc (request);          else {
885      return rc;              sprintf (numbuf, "%%%02X", url[i]);
886  } /* kserver_search_init */              gpgme_data_write (hd, numbuf, strlen (numbuf));
887            }
888        }
889  int  
890  kserver_search_chkresp (int fd)      p = data_release_and_get_mem (hd, &nlen);
891  {      if (ret_nlen)
892      char buf[128];          *ret_nlen = nlen;
893      int n=0;      return p;
894        }
895      /* parse response 'HTTP/1.0 500 OK' */  
896      if (sock_getline (fd, buf, 127, &n))  
897          return WPTERR_KEYSERVER_NOTFOUND;  /* Format a request for the given keyid (send). */
898      if (debug)  static char*
899          log_f ("kserver_search_chkpresp: %s\r\n", buf);  kserver_send_request (const char *hostname, WORD port,
900      if (strncmp (buf, "HTTP/1.", 7))                        const char *pubkey, DWORD octets)
901          return WPTERR_KEYSERVER_NOTFOUND;  {
902      if (strncmp (buf+(8+1), "200", 3))      const char *fmt;
903          return WPTERR_KEYSERVER_NOTFOUND;      char *request;
904      return 0;      char *enc_pubkey;
905  } /* kserver_search_chkresp */      DWORD enc_octets;
906        int reqlen;
907    
908  int      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
909  kserver_search (int fd, keyserver_key * key)  
910  {      if (!port)
911      char buf[1024], *p;          port = HKP_PORT;
912      int uidlen, nbytes, pos = 0;      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
913            reqlen = 2*strlen (hostname) + 2*32/*port*/ + enc_octets + 32 /*len*/ + 1;
914      if (debug)      
915          log_f ("keyserver_search:\n");      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
916                fmt = "POST http://%s:%d/pks/add HTTP/1.0\r\n"
917      if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))                "Referer: \r\n"
918          return WPTERR_GENERAL;                "User-Agent: WinPT/W32\r\n"
919                      "Host: %s:%d\r\n"
920      if (debug)                "Proxy-Authorization: Basic %s\r\n"
921          log_f ("%s\n", buf);                "Content-type: application/x-www-form-urlencoded\r\n"
922                      "Content-length: %d\r\n"
923      if (!strncmp (buf, "pub", 3)) {                "\r\n"
924          int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;                "keytext=%s"
925          key->bits = atol (buf+3);                "\r\n";
926          p = strchr (buf, '>');          reqlen += strlen (fmt) + strlen (proxy.base64_user) + 1;
927          if (!p)          request = safe_alloc (reqlen+1);
928              goto fail;          _snprintf (request, reqlen, fmt,
929          pos = p - buf + 1;                     skip_type_prefix (hostname), port, hostname, port,
930          memcpy (key->keyid, buf + pos, 8);                     proxy.base64_user, enc_octets+9, enc_pubkey);
931          key->keyid[8] = '\0';      }
932          p = strstr (buf, "</a>");      else {
933          if (!p)          fmt = "POST /pks/add HTTP/1.0\r\n"
934              goto fail;                "Referer: \r\n"
935          pos = p - buf + 5;                "User-Agent: WinPT/W32\r\n"
936          memcpy (key->date, buf + pos, 10);                "Host: %s:%d\r\n"
937          key->date[10] = '\0';                "Content-type: application/x-www-form-urlencoded\r\n"
938          if (revoked) {                "Content-length: %d\r\n"
939              strcpy (key->uid, "KEY REVOKED: not checked");                "\r\n"
940              return 0;                "keytext=%s"
941          }                "\r\n";
942          pos += 10;          reqlen += strlen (fmt)+1;
943          p = buf + pos + 1;          request = safe_alloc (reqlen+1);
944          while (p && *p != '>')          _snprintf (request, reqlen, fmt,
945              p++;                     skip_type_prefix (hostname), port,
946          p++;                     enc_octets+9, enc_pubkey);
947          uidlen = strlen (p) - 10;      }
948          memcpy (key->uid, p, uidlen);  
949          key->uid[uidlen] = '\0';      free_if_alloc (enc_pubkey);
950          strcat (key->uid, ">");      log_debug ("request:\r\n%s\r\n", request);
951          p = strchr (key->uid, '&');      return request;
952          if (p) {  }
953              key->uid[(p-key->uid)] = '<';  
954              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4, strlen (key->uid)-3);  
955          }  /* Interface for receiving a public key. */
956          return 0;  int
957      }  kserver_recvkey (const char *hostname, WORD port, const char *keyid,
958                     char **r_key, int *r_keylen)
959  fail:  {
960      key->bits = 0;      const char *fmt;
961      memset (key, 0, sizeof *key);      char *request = NULL;
962      return 0;      int conn_fd;
963  } /* kserver_search */      int rc, reqlen;
964    
965        if (!port)
966  static int          port = HKP_PORT;
967  add_node( keyserver_cfgfile *cfg, const char *entry )      hkp_err = 0; /* reset */
968  {      rc = kserver_connect (hostname, port, &conn_fd);
969      keyserver_node *node;      if (rc)
970      char *p = NULL;          goto leave;
971        
972      p = strchr( entry, '=' );      reqlen = strlen (hostname)+32+strlen (keyid)+1;
973      if( p == NULL )      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
974          return WPTERR_GENERAL;            fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"
975      node = new keyserver_node;                "Proxy-Authorization: Basic %s\r\n\r\n";
976      if( !node )          reqlen =+ strlen (fmt) + strlen (proxy.base64_user)+1;
977          BUG( NULL );          request = safe_alloc (reqlen+1);
978                _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
979      memset( node, 0, sizeof *node );                     keyid, proxy.base64_user);
980      node->used = 1;      }
981            else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
982      node->host.used = 1;          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
983      node->host.proto = proto_from_URL( entry );          reqlen += strlen (fmt)+1;
984      memcpy( node->host.name, entry+7, p-entry-7 );          request = safe_alloc (reqlen+1);
985      node->next = cfg->list;          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname),
986      cfg->list = node;                                           port, keyid);
987            }
988      return 0;      else {
989  } /* add_node */          fmt = "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
990            reqlen += strlen (fmt)+1;
991            request = safe_alloc (reqlen+1);
992  void          _snprintf (request, reqlen, fmt, keyid);
993  kserver_change_proxy( keyserver_proxy_ctx *ctx )      }
994  {      
995      proxy.port = ctx->port;      log_debug ("request:\r\n%s\r\n", request);
996      free_if_alloc (proxy.host);      
997      proxy.host = ctx->host? m_strdup( ctx->host ) : NULL;      rc = sock_write (conn_fd, request, strlen (request));
998      free_if_alloc( proxy.pass );      if (rc == SOCKET_ERROR) {
999      proxy.pass = ctx->pass? m_strdup( ctx->pass ) : NULL;          rc = WPTERR_WINSOCK_RECVKEY;
1000      free_if_alloc( proxy.user );          goto leave;
1001      proxy.user = ctx->user? m_strdup( ctx->user ) : NULL;      }
1002      set_reg_proxy_prefs( proxy.host, proxy.port, proxy.user, proxy.pass );      
1003  } /* kserver_change_proxy */      rc = sock_read_ext (conn_fd, r_key, r_keylen);
1004        if (rc == SOCKET_ERROR) {
1005            rc = WPTERR_WINSOCK_RECVKEY;
1006  int          goto leave;
1007  kserver_read_config( const char *fname, keyserver_cfgfile **ret_cfg )      }
1008  {  
1009      FILE *fp;      log_debug ("response:\r\n%s\r\n", *r_key);
1010      keyserver_cfgfile *cfg;      rc = check_hkp_response (*r_key, 1);
1011      char buf[256];      if (rc)
1012      int rc = 0;          goto leave;
1013            
1014      *ret_cfg = NULL;      WSASetLastError (0);
1015      fp = fopen( fname, "rb" );      
1016      if( fp == NULL )  leave:
1017          return WPTERR_FILE_OPEN;      closesocket (conn_fd);
1018            free_if_alloc (request);
1019      cfg = new keyserver_cfgfile;      return rc;
1020      if ( !cfg )  }
1021          BUG( NULL );  
1022      memset( cfg, 0, sizeof *cfg );  
1023        /* Interface to send a public key. */
1024      while ( !feof( fp ) ) {  int
1025          if ( fgets( buf, sizeof(buf)-1, fp ) == NULL )  kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )
1026              break;  {
1027          if ( *buf == '\r' || *buf == '\n' || *buf == '#' )      char *request = NULL;
1028              continue;      char log[2048] = {0};
1029          buf[strlen(buf) -2] = '\0';      int conn_fd, n;
1030          if ( !strncmp( buf, "use_proxy=", 10 ) ) {      int rc;
1031              char *p = strchr(buf, ':');      
1032              if (!p)      hkp_err = 0; /* reset */
1033                  continue;      rc = kserver_connect (hostname, port, &conn_fd);
1034              cfg->proxy.port = atol( buf+(p-buf+1) );      if (rc)
1035              buf[p-buf] = '\0';          goto leave;
1036              cfg->proxy.host = m_strdup( buf+10 );      
1037          }      request = kserver_send_request (hostname, port, pubkey, len);
1038          else if ( !strncmp( buf, "proxy_user=", 11 ) )      if (request == NULL) {
1039              cfg->proxy.user = m_strdup( buf+11 );          rc = WPTERR_GENERAL;
1040          else if ( !strncmp( buf, "proxy_pass=", 11 ) )          goto leave;    
1041              cfg->proxy.pass = m_strdup( buf+11 );      }
1042          if ( !strncmp( buf, "http://", 7 )      
1043              || !strncmp( buf, "hkp://", 6 )      rc = sock_write (conn_fd, request, strlen (request));
1044              || !strncmp( buf, "ldap://", 7 ) ) {      if (rc == SOCKET_ERROR) {
1045              add_node( cfg, buf );          rc = WPTERR_WINSOCK_SENDKEY;
1046              cfg->nlist++;          goto leave;    
1047          }      }
1048      }      
1049            rc = sock_read (conn_fd, log, DIM (log)-1, &n);
1050      fclose( fp );      if (rc == SOCKET_ERROR) {
1051      *ret_cfg = cfg;          rc = WPTERR_WINSOCK_SENDKEY;
1052                goto leave;
1053      return rc;      }
1054  } /* kserver_read_config */  
1055        log_debug ("kserver_sendkey: read %d bytes\r\n%s\r\n", n, log);
1056        rc = check_hkp_response (log, 0);
1057  int      if (rc)
1058  kserver_write_config( const char * fname, keyserver_cfgfile * cfg )          goto leave;
1059  {      
1060            WSASetLastError (0);
1061      return 0;      
1062  }  leave:
1063        closesocket (conn_fd);
1064        free_if_alloc (request);
1065  void      return rc;
1066  kserver_cfgfile_release( keyserver_cfgfile *cfg )  }
1067  {        
1068      keyserver_node *k, *k2;  
1069    /* Check keyserver response. */
1070      proxy_release( &cfg->proxy );  static int
1071      for( k = cfg->list; cfg->nlist--; k = k2 ) {  kserver_search_chkresp (int fd)
1072          k2 = k->next;  {
1073          free_if_alloc( k );          char buf[128];
1074      }      int n=0;
1075      free_if_alloc( cfg );      
1076  } /* kserver_cfgfile_release */      /* parse response 'HTTP/1.0 500 OK' */
1077        if (sock_getline (fd, buf, DIM (buf)-1, &n))
1078            return WPTERR_KEYSERVER_NOTFOUND;
1079  void  
1080  proxy_release( keyserver_proxy_ctx *ctx )      log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1081  {      if (strncmp (buf, "HTTP/1.", 7))
1082      free_if_alloc( ctx->host );          return WPTERR_KEYSERVER_NOTFOUND;
1083      free_if_alloc( ctx->pass );      if (strncmp (buf+(8+1), "200", 3))
1084      free_if_alloc( ctx->user );          return WPTERR_KEYSERVER_NOTFOUND;
1085  } /* proxy_release */      return 0;
1086    }
1087    
1088  int  
1089  ldap_recvkey (const char * host, const char * keyid, char * key, int maxkeylen)  /* End the keyserver search procedure. */
1090  {  void
1091      const char *s;  kserver_search_end (int conn_fd)
1092      char *ksprg = NULL, *p = NULL;  {
1093      char temp[512], outf[512];      log_debug ("kserver_search_end: fd=%d\r\n", conn_fd);
1094      FILE * inp;      closesocket (conn_fd);
1095      int rc, start_key = 0;  }
1096      STARTUPINFO si;  
1097      PROCESS_INFORMATION pi;  
1098    /* Extract the amount of keys from the info record. */
1099      p = get_gnupg_path ();  static int
1100      ksprg = new char[strlen (p) + 1 + 128];  count_keys_in_response (char *buf)
1101      if (!ksprg)  {
1102          BUG (0);      char *p;
1103      strcpy (ksprg, p);      int recno = 0;
1104      strcat (ksprg, "\\");      int n = 0;
1105      strcat (ksprg, "gpgkeys_ldap.exe");  
1106      free_if_alloc (p);      /* info:1:4 */
1107      if (file_exist_check (ksprg)) {      if (strncmp (buf, "info", 4))
1108          log_box ( "LDAP Keyserver Plugin", MB_ERR, "Could not find LDAP keyserver module!");          return 0;
1109          rc = -1;      p = strtok (buf, ":");
1110          goto leave;      while (p != NULL) {
1111      }          recno++;
1112      GetTempPath (sizeof (temp)-1, temp);          if (recno == 3)
1113      strcpy (outf, temp);              n = atoi (p);
1114      strcat (outf, keyid);          p = strtok (NULL, ":");
1115      strcat (outf, ".out");      }
1116      strcat (temp, keyid);      return n;
1117      inp = fopen (temp, "w+b");  }
1118      if( !inp ) {  
1119          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", temp,  
1120                   winpt_strerror (WPTERR_FILE_OPEN));  /* Start the keyserver search.
1121          rc = -1;     Connect to host @hostname and port @port.
1122          goto leave;     The pattern are given in @pattern.
1123      }     The socket is returned in @conn_fd and @nkeys contains
1124      fprintf (inp,     the amount of keys which were found. */
1125          "VERSION 0\n"  int
1126          "HOST %s\n"  kserver_search_begin (const char *hostname, WORD port,
1127          "OPTION verbose\n"                        const char *pattern, int *conn_fd, int *nkeys)
1128          "COMMAND GET\n"  {
1129          "\n"      const char *fmt;
1130          "%s\n", host? skip_type_prefix (host): "64.94.85.200", keyid);      char *request = NULL;
1131      fclose (inp);      char *enc_patt = NULL;
1132        char status[128];
1133      memset (&si, 0, sizeof (si));      int rc, sock_fd;
1134      si.cb = sizeof (si);      int reqlen;
1135      si.dwFlags = STARTF_USESHOWWINDOW;      
1136      si.wShowWindow = SW_HIDE;      *conn_fd = 0;
1137      memset (&pi, 0, sizeof (pi));  
1138      p = new char[strlen (ksprg) + strlen (temp) + strlen (outf) + 32];      rc = kserver_connect (hostname, port, &sock_fd);
1139      sprintf (p, "%s -o %s %s", ksprg, outf, temp);      if (rc)
1140      rc = CreateProcess (NULL, p, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);          goto leave;
1141      if (!rc) {  
1142          log_box ("LDAP Keyserver Plugin", MB_ERR, "Could not spawn process");      enc_patt = URL_encode (pattern, strlen (pattern), NULL);
1143          rc = -1;      reqlen = strlen (enc_patt) + strlen (hostname) + 32 + 1;
1144          goto leave;  
1145      }      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
1146      CloseHandle (pi.hThread);          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n"
1147      WaitForSingleObject (pi.hProcess, INFINITE);                "Proxy-Authorization: Basic %s\r\n\r\n";
1148      CloseHandle (pi.hProcess);          reqlen += strlen (proxy.base64_user) + strlen (fmt) + 1;
1149            request = safe_alloc (reqlen+1);
1150      inp = fopen (outf, "rb");          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
1151      if (!inp) {                     enc_patt, proxy.base64_user);
1152          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,      }    
1153                   winpt_strerror (WPTERR_FILE_OPEN));      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
1154          rc = -1;          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1155          goto leave;          reqlen += strlen (fmt)+1;
1156      }          request = safe_alloc (reqlen+1);
1157      memset (key, 0, maxkeylen);          _snprintf (request, reqlen, skip_type_prefix (hostname), port,
1158      while( !feof( inp ) ) {                              enc_patt);
1159          s = fgets( temp, sizeof (temp)-1, inp );      }
1160          if( !s )      else {
1161              break;          fmt = "GET /pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1162          if( !start_key && strstr( s, "KEY" ) && strstr( s, "BEGIN" ) ) {          reqlen += strlen (fmt)+1;
1163              start_key = 1;          request = safe_alloc (reqlen+1);
1164              continue;          _snprintf (request, reqlen, fmt, enc_patt);
1165          }            }
1166          if( !start_key )  
1167              continue;      log_debug ("kserver_search_begin:\r\n%s\r\n", request);
1168          strcat( key, temp );      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1169          maxkeylen -= strlen( temp );          rc = WPTERR_GENERAL;
1170          if( maxkeylen < 0 || (strstr( s, "KEY" ) && strstr( s, "END" )) )                    goto leave;
1171              break;      }
1172      }      
1173      fclose( inp );          rc = kserver_search_chkresp (sock_fd);
1174        if (rc) {
1175  leave:          closesocket (sock_fd);
1176      if( !strlen( key ) )          sock_fd = 0;
1177          rc = WPTERR_WINSOCK_RECVKEY;          goto leave;
1178      free_if_alloc( p );      }
1179      free_if_alloc( ksprg );  
1180      return rc;      /* Skip all lines until we reach the "info:" record. */
1181  } /* ldap_recvkey */      for (;;) {
1182            if (sock_getline (sock_fd, status, DIM (status)-1, &reqlen)) {  
1183                log_debug ("kserver_search_begin: retrieving status line failed.\r\n");
1184  static int              closesocket (sock_fd);
1185  finger_readline (int fd, char * buf, int nbytes)              sock_fd = 0;
1186  {              rc = WPTERR_GENERAL;
1187      char c = 0;              break;
1188      int n, pos = 0;          }
1189                if (!strncmp (status, "info:", 5))
1190      while (nbytes > 0) {              break;
1191          n = recv (fd, &c, 1, 0);      }
1192          if (n <= 0)  
1193              break;      if (!rc)
1194          if (c == '\n')          *nkeys = count_keys_in_response (status);
1195              break;      *conn_fd = sock_fd;
1196          buf[pos++] = c;      
1197          nbytes--;  leave:
1198      }      free_if_alloc (request);
1199      if (nbytes > 0)      free_if_alloc (enc_patt);
1200          buf[pos++] = '\0';      return rc;
1201      if (n <= 0)  }
1202          pos = n;  
1203      return pos;  
1204  }  /* Parse a single pub record returned by the keyserver. */
1205    static void
1206    parse_pub_record (keyserver_key_s *key, char *buf)
1207  int  {
1208  finger_recvkey (const char * host, const char * user, char * key, int maxkeylen)      enum pub_rec_t {ID=1, KEYID, ALGO, SIZE, CREATE, EXPIRE};
1209  {      char *p;
1210      struct hostent * hp;      int recno = 0;
1211      struct sockaddr_in saddr;      int off = 0;
1212      char buf[128];  
1213      int fd, nread;      /* pub:BF3DF9B4:17:1024:925411133:: */
1214      int start_key = 0;      p = strtok (buf, ":");
1215      int rc=0;      while (p != NULL) {
1216            recno++;
1217      fd = socket (PF_INET, SOCK_STREAM, 0);          switch (recno) {
1218      if (fd == -1)          case ID:
1219          return WPTERR_WINSOCK_SOCKET;              break;
1220      hp = gethostbyname (skip_type_prefix (host));  
1221      if (!hp) {          case KEYID:
1222          closesocket (fd);              /* If for any reason the returned record actually contains
1223          return WPTERR_WINSOCK_RESOLVE;                 a fingerprint instead of a key ID, we truncate the fpr. */
1224      }              off = strlen (p) == 40? 32 : 0;
1225                free_if_alloc (key->keyid);
1226      memset (&saddr, 0, sizeof (saddr));              key->keyid = m_strdup (p+off);
1227      saddr.sin_family = AF_INET;              break;
1228      saddr.sin_port = htons (FINGER_PORT);  
1229      saddr.sin_addr = *(struct in_addr *)hp->h_addr;          case ALGO:
1230      if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {              key->algo = atoi (p);
1231          closesocket (fd);              break;
1232          return WPTERR_WINSOCK_CONNECT;              
1233      }          case SIZE:
1234      send (fd, user, strlen (user), 0);              key->bits = atoi (p);
1235      send (fd, "\r\n", 2, 0);              break;
1236    
1237      memset (key, 0, maxkeylen);          case CREATE:
1238      while (maxkeylen > 0) {              key->creation = strtoul (p, NULL, 10);
1239          nread = finger_readline (fd, buf, sizeof (buf)-1);              break;
1240          if (nread <= 0)  
1241              break;          case EXPIRE:
1242          strcat (buf, "\n");              key->expires = strtoul (p, NULL, 10);
1243          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {              break;
1244              strcat (key, buf);          }
1245              start_key = 1;          p = strtok (NULL, ":");
1246              maxkeylen -= nread;      }
1247          }  }
1248          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {  
1249              strcat (key, buf);  
1250              start_key--;  /* Parse a single user id returned by the keyserver. */
1251              maxkeylen -= nread;  static void
1252              break;  parse_uid_record (keyserver_key_s *key, char *buf)
1253          }  {
1254          else if (start_key) {      enum uid_rec_t {ID=1, UID, CREATE, EXPIRE};
1255              strcat (key, buf);      keyserver_uid_s *u, *n;
1256              maxkeylen -= nread;      char *p, *raw;
1257          }      int recno = 0;
1258      }  
1259      closesocket (fd);      /* uid:Timo Schulz <[email protected]>:1138440360:: */
1260      if (start_key != 0)      u = new keyserver_uid_s;
1261          rc = WPTERR_WINSOCK_RECVKEY;      memset (u, 0, sizeof *u);
1262      return rc;  
1263  }      p = strtok (buf, ":");
1264        while (p != NULL) {
1265            recno++;
1266  int  
1267  check_IP_or_hostname (const char *name)          switch (recno) {
1268  {          case ID:
1269      const char *not_allowed = "=!�$%&@#*~\\/}][{<>|,;:'";              break;
1270      size_t i, j;  
1271            case UID:
1272      for (i=0; i < strlen (name); i++) {              unhexify_buffer (p, &raw);
1273          for (j =0; j < strlen (not_allowed); j++) {              u->uid = utf8_to_native (raw);
1274              if (name[i] == not_allowed[j])              free_if_alloc (raw);
1275                  return -1;              break;
1276          }  
1277      }          case CREATE:
1278      return 0;              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.22  
changed lines
  Added in v.271

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26