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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26