/[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 23 by twoaday, Fri Sep 30 10:10:16 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. */              _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  } /* sock_write */      
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      if (debug)          default_keyserver_port = HKP_PORT;
602          log_f ("kserver_connect: %s:%d\r\n", hostname, port);      }
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_f ("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          if (debug)  
628              log_f ("gethostbyname: failed.\r\n");  /* Save the keyserver config file in @conf. */
629          return WPTERR_WINSOCK_RESOLVE;  int
630      }  kserver_save_conf (const char *conf)
631      fd = socket (AF_INET, SOCK_STREAM, 0);  {
632      if (fd == INVALID_SOCKET)        FILE *fp;
633          return WPTERR_WINSOCK_SOCKET;      int pos;
634      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));  
635      if (rc == SOCKET_ERROR) {      fp = fopen (conf, "wb");
636          if (debug)      if (!fp) {
637              log_f ("connect: failed.\r\n");          msg_box (NULL, _("Could not save keyserver.conf file"),
638          closesocket (fd);                   _("Keyserver"), MB_ERR);
639          return WPTERR_WINSOCK_CONNECT;          return -1;
640      }      }
641    
642      if (conn_fd)      fprintf (fp, "# do NOT manually modify this file, it will be "
643          *conn_fd = fd;                   "generated automatically!!\r\n");
644      WSASetLastError (0);      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
645      return 0;          if (!server[pos].used)
646  } /* kserver_connect */              continue;
647            fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
648        }
649  /* Perform URL-encoding on the given pubkey blob. */      fclose (fp);
650  static char*      return 0;
651  kserver_urlencode (const char *pubkey, size_t octets, size_t *newlen)  }
652  {  
653      char *p, numbuf[5];  
654      size_t j = 0;  /* Return the specified keyserver config setting @key as an integer. */
655      size_t i, size;  static int
656        get_conf_kserver_int (const char *key)
657      p = new char [2*octets];  {
658      if (!p)      char *p;
659          BUG (0);      int val = 0;
660    
661      for (size=0, i=0; i < octets; i++) {      p = get_reg_entry_keyserver (key);
662          if (isalnum (pubkey[i]) || pubkey[i] == '-') {      if (p && *p)
663              p[size] = pubkey[i];          val = atoi (p);
664              size++;      free_if_alloc (p);
665          }      return val;
666          else if (pubkey[i] == ' ') {  }
667              p[size] = '+';  
668              size++;  
669          }  /* Read the proxy configuration and store it into @prox. */
670          else {  static void
671              sprintf(numbuf, "%%%02X", pubkey[i]);  read_proxy_config (keyserver_proxy_t prox)
672              for (j = 0; j<strlen(numbuf); j++) {  {
673                  p[size] = numbuf[j];      char *proto;
674                  size++;  
675              }      if (!prox)
676          }          return;
677      }      
678      p[size] = '\0';      proto = get_reg_entry_keyserver("Proto");
679      *newlen = size;      if (proto != NULL && strlen (proto) > 0)
680      return p;          prox->proto = atoi (proto);
681  }      else
682            prox->proto = PROXY_PROTO_NONE;
683        free_if_alloc (proto);
684  /* Format a request for the given keyid (send). */      free_if_alloc (prox->host);
685  static char*      prox->host = get_reg_entry_keyserver ("Host");
686  kserver_send_request (const char *hostname, u16 port, const char *pubkey, int octets)      free_if_alloc (prox->user);
687  {      prox->user = get_reg_entry_keyserver ("User");
688      char *request = NULL, *enc_pubkey = NULL;      free_if_alloc (prox->pass);
689      int reqlen;      prox->pass = get_reg_entry_keyserver ("Pass");
690      size_t enc_octets;      prox->port = get_conf_kserver_int ("Port");
691        }
692      if (debug)  
693          log_f ("kserver_send_request: %s:%d\n", hostname, port);  
694      if (!port)  /* Load the keyserver config file @conf. */
695          port = HKP_PORT;  int
696      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);  kserver_load_conf (const char *conf)
697      request = new char[reqlen];  {    
698      if (!request)      FILE *fp;
699          BUG (0);      char buf[1024], *s, *p;
700      enc_pubkey = kserver_urlencode (pubkey, octets, &enc_octets);      char *user = NULL, *pass = NULL;    
701      if (!enc_pubkey || !enc_octets) {      int no_config=0, chk_pos=0;
702          free_if_alloc (request);      int pos;
703          return NULL;      
704      }      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
705                server[pos].used = 0;
706      if (proxy.user) {          server[pos].port = HKP_PORT;
707          _snprintf (request, reqlen-1,      }
708                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"      
709                     "Referer: \r\n"      fp = fopen (conf, "rb");
710                     "User-Agent: WinPT/W32\r\n"      if (!fp) {
711                     "Host: %s:%d\r\n"          for (pos = 0; server_list[pos]; pos++) {
712                     "Proxy-Authorization: Basic %s\r\n"              server[pos].used = 1;
713                     "Content-type: application/x-www-form-urlencoded\r\n"              server[pos].name = m_strdup (server_list[pos]);
714                     "Content-length: %d\r\n"              server[pos].proto = proto_from_URL (server_list[pos]);
715                     "\r\n"          }
716                     "keytext=%s"          no_config=1;
717                     "\n",      }
718                     skip_type_prefix (hostname), port, hostname, port,      read_proxy_config (&proxy);
719                     proxy.base64_user, enc_octets+9, enc_pubkey);      if (user && pass)
720      }          update_proxy_user (user, pass);
721      else {      else if (user && !pass || !user && pass) {
722          _snprintf (request, reqlen-1,          msg_box (NULL, _("Invalid proxy configuration. "
723                     "POST /pks/add HTTP/1.0\r\n"                           "You need to set a user and a password "
724                     "Referer: \r\n"                           "to use proxy authentication!"),
725                     "User-Agent: WinPT/W32\r\n"                           _("Proxy Error"), MB_ERR);
726                     "Host: %s:%d\r\n"      }
727                     "Content-type: application/x-www-form-urlencoded\r\n"      /* check if the host has a http:// prefix and skip it */
728                     "Content-length: %d\r\n"      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
729                     "\r\n"          char *host = m_strdup (proxy.host+7);
730                     "keytext=%s"          free_if_alloc (proxy.host);
731                     "\n",          proxy.host = host;
732                     skip_type_prefix (hostname), port, enc_octets+9, enc_pubkey);      }
733      }      free_if_alloc (user);
734      free_if_alloc (enc_pubkey);      free_if_alloc (pass);
735      if (debug)      
736          log_f ("%s\n", request);      pos = 0;
737      return request;      while (fp && !feof (fp)) {
738  } /* kserver_send_request */          s = fgets (buf, DIM (buf)-1, fp);
739            if (!s)
740                break;
741  /* Interface receiving a public key. */          if (strstr (buf, "\r\n"))
742  int              buf[strlen (buf)-2] = '\0';
743  kserver_recvkey (const char *hostname, u16 port, const char *keyid, char *key, int maxkeylen)          if (strstr (buf, "\n"))
744  {                    buf[strlen (buf)-1] = '\0';
745      int rc, n;          s = (char *)skip_whitespace (buf);
746      int conn_fd;          if (*s == '#' || strlen (s) < 7)
747      char *request = NULL;              continue;
748                chk_pos = check_URL (s);
749      if (!port)          if (!chk_pos) {
750          port = HKP_PORT;              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
751      hkp_err = 0; /* reset */                                   "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
752      rc = kserver_connect (hostname, port, &conn_fd);                               _("Keyserver Error"), MB_ERR);
753      if (rc)              continue;
754          goto leave;          }
755                p = strchr (s+chk_pos, ':');
756      request = new char[300+1];          server[pos].used = 1;
757      if (!request)          server[pos].proto = proto_from_URL (s);
758          BUG (0);          server[pos].port = port_from_proto (server[pos].proto);
759                if (!p)
760      if (proxy.host && proxy.user) {              server[pos].name = m_strdup (s);
761          _snprintf (request, 300,          else {      
762              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"              server[pos].port = atol (p+1);
763              "Proxy-Authorization: Basic %s\r\n\r\n",              if (server[pos].port < 0 || server[pos].port > 65536)
764              skip_type_prefix (hostname), port, keyid, proxy.base64_user);                  server[pos].port = HKP_PORT;
765      }              server[pos].name = safe_alloc ((p-s)+2);
766      else if (proxy.host) {              memset (server[pos].name, 0, (p-s)+2);
767          _snprintf (request, 300,              memcpy (server[pos].name, s, (p-s));
768              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",          }
769              skip_type_prefix (hostname), port, keyid);          pos++;
770      }              if (pos > MAX_KEYSERVERS) {
771      else {              msg_box (NULL, _("The keyserver limit is exceeded"),
772          _snprintf (request, 300,                       _("Keyserver Warning"), MB_INFO);
773              "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);              break;
774      }            }
775      if (debug)      }
776          log_f ("%s\r\n", request);      if (fp)
777                fclose (fp);
778      rc = sock_write (conn_fd, request, strlen (request));      if (!pos) {
779      if (rc == SOCKET_ERROR) {          /* only issue an error if the config file exist but
780          rc = WPTERR_WINSOCK_RECVKEY;             it has no valid entries. */
781          goto leave;          keyserver_set_default (NULL, HKP_PORT);
782      }          if (!no_config)
783                    return WPTERR_CONFIG_FILE;
784      rc = sock_read( conn_fd, key, maxkeylen, &n );      }
785      if( rc == SOCKET_ERROR ) {  
786          rc = WPTERR_WINSOCK_RECVKEY;      return 0;
787          goto leave;  }
788      }  
789        
790      if (debug)  /* Connect to the keyserver @hostname (port @port).
791          log_f("%s\r\n", key);     Return value: 0 on success */
792      rc = check_hkp_response (key, 1);  int
793      if (rc)  kserver_connect (const char *hostname, WORD port, int *conn_fd)
794          goto leave;  {        
795            struct hostent *hp;
796      WSASetLastError (0);      struct sockaddr_in sock;
797            char host[128] = {0};
798  leave:      DWORD iaddr;
799      closesocket (conn_fd);      bool use_proxy = proxy.host != NULL;
800      free_if_alloc (request);      int rc, fd;
801      return rc;  
802  } /* kserver_recvkey */      if (!port)
803            port = HKP_PORT;
804        if (conn_fd)
805  /* Interface to send a public key. */          *conn_fd = 0;
806  int      hostname = skip_type_prefix (hostname);
807  kserver_sendkey (const char *hostname, u16 port, const char *pubkey, int len )      log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
808  {      
809      int n, rc;      if (use_proxy && proxy.proto == PROXY_PROTO_HTTP)
810      int conn_fd;          port = proxy.port;
811      char *request = NULL;      memset (&sock, 0, sizeof (sock));
812      char log[2048];      sock.sin_family = AF_INET;
813            sock.sin_port = htons (port);
814      hkp_err = 0; /* reset */      if (use_proxy)
815      rc = kserver_connect (hostname, port, &conn_fd);          strncpy (host, proxy.host, DIM (host)-1);
816      if (rc)      else
817          goto leave;          strncpy (host, hostname, DIM (host)-1);
818        
819      request = kserver_send_request (hostname, port, pubkey, len);      if ((iaddr = inet_addr (host)) != INADDR_NONE)
820      if (request == NULL) {          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
821          rc = WPTERR_GENERAL;      else if ((hp = gethostbyname (host))) {
822          goto leave;              if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
823      }              log_debug ("gethostbyname: unknown address type.\r\n");
824                    return WPTERR_WINSOCK_RESOLVE;
825      rc = sock_write( conn_fd, request, lstrlen(request) );          }
826      if( rc == SOCKET_ERROR ) {          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
827          rc = WPTERR_WINSOCK_SENDKEY;      }
828          goto leave;          else {
829      }          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
830                return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_RESOLVE;
831      rc = sock_read( conn_fd, log, sizeof (log)-1, &n );      }
832      if( rc == SOCKET_ERROR ) {      fd = socket (AF_INET, SOCK_STREAM, 0);
833          rc = WPTERR_WINSOCK_SENDKEY;      if (fd == INVALID_SOCKET)  
834          goto leave;          return WPTERR_WINSOCK_SOCKET;
835      }      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
836      if (debug)      if (rc == SOCKET_ERROR) {
837          log_f ("kserver_sendkey:\r\n%s\r\n", log);          log_debug ("connect: failed ec=%d.\r\n", net_errno);
838                closesocket (fd);
839      rc = check_hkp_response (log, 0);          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_CONNECT;
840      if( rc )      }
841          goto leave;  
842            if (proxy.proto == PROXY_PROTO_SOCKS5) {
843      WSASetLastError (0);          /* XXX: finish code and provide errors constants. */
844                rc = socks_handshake (&proxy, fd, hostname, port);
845  leave:          if (rc) {
846      closesocket (conn_fd);              closesocket (fd);
847      free_if_alloc (request);              return WPTERR_GENERAL;
848      return rc;          }
849  } /* kserver_sendkey */      }
850    
851        if (conn_fd)
852  int          *conn_fd = fd;
853  kserver_search_init (const char * hostname, u16 port, const char * keyid, int * conn_fd)      WSASetLastError (0);
854  {      return 0;
855      int rc, sock_fd;  }
856      int n=0;  
857      char * request = NULL;  
858        /* Check if the URL needs to be encoded or not. */
859      rc = kserver_connect (hostname, port, &sock_fd);  static bool
860      if (rc) {  URL_must_encoded (const char *url)
861          *conn_fd = 0;  {
862          goto leave;      if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
863      }          return true;
864            return false;
865      n=300;  }
866      request = new char[n+1];  
867      if (!request)  
868          BUG (0);  /* Perform URL encoding of the given data. */
869        static char*
870      if (proxy.host && proxy.user) {  URL_encode (const char *url, DWORD ulen, DWORD *ret_nlen)
871          _snprintf (request, n,  {
872              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"      gpgme_data_t hd;
873              "Proxy-Authorization: Basic %s\r\n\r\n",      char numbuf[5], *p;
874              skip_type_prefix (hostname), port, keyid, proxy.base64_user);      size_t i;
875      }          int nlen;
876      else if (proxy.host) {  
877          _snprintf (request, n,      if (gpgme_data_new (&hd))
878              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",          BUG (0);
879              skip_type_prefix (hostname), port, keyid);      for (i=0; i < ulen; i++) {
880      }          if (isalnum (url[i]) || url[i] == '-')
881      else {              gpg_data_putc (hd, url[i]);
882          _snprintf (request, n,          else if (url[i] == ' ')
883                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n", keyid);              gpg_data_putc (hd, '+');
884      }          else {
885                    sprintf (numbuf, "%%%02X", url[i]);
886      if (debug)              gpgme_data_write (hd, numbuf, strlen (numbuf));
887          log_f ("kserver_search_init:\r\n%s\r\n", request);          }
888            }
889      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {  
890          rc = WPTERR_GENERAL;      p = data_release_and_get_mem (hd, &nlen);
891          goto leave;      if (ret_nlen)
892      }          *ret_nlen = nlen;
893            return p;
894      *conn_fd = sock_fd;  }
895        
896  leave:  
897      free_if_alloc (request);  /* Format a request for the given keyid (send). */
898      return rc;  static char*
899  } /* kserver_search_init */  kserver_send_request (const char *hostname, WORD port,
900                          const char *pubkey, DWORD octets)
901    {
902  int      const char *fmt;
903  kserver_search_chkresp (int fd)      char *request;
904  {      char *enc_pubkey;
905      char buf[128];      DWORD enc_octets;
906      int n=0;      int reqlen;
907        
908      /* parse response 'HTTP/1.0 500 OK' */      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
909      if (sock_getline (fd, buf, 127, &n))  
910          return WPTERR_KEYSERVER_NOTFOUND;      if (!port)
911      if (debug)          port = HKP_PORT;
912          log_f ("kserver_search_chkpresp: %s\r\n", buf);      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
913      if (strncmp (buf, "HTTP/1.", 7))      reqlen = 2*strlen (hostname) + 2*32/*port*/ + enc_octets + 32 /*len*/ + 1;
914          return WPTERR_KEYSERVER_NOTFOUND;      
915      if (strncmp (buf+(8+1), "200", 3))      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
916          return WPTERR_KEYSERVER_NOTFOUND;          fmt = "POST http://%s:%d/pks/add HTTP/1.0\r\n"
917      return 0;                "Referer: \r\n"
918  } /* kserver_search_chkresp */                "User-Agent: WinPT/W32\r\n"
919                  "Host: %s:%d\r\n"
920                  "Proxy-Authorization: Basic %s\r\n"
921  int                "Content-type: application/x-www-form-urlencoded\r\n"
922  kserver_search (int fd, keyserver_key * key)                "Content-length: %d\r\n"
923  {                "\r\n"
924      char buf[1024], *p;                "keytext=%s"
925      int uidlen, nbytes, pos = 0;                "\r\n";
926                reqlen += strlen (fmt) + strlen (proxy.base64_user) + 1;
927      if (debug)          request = safe_alloc (reqlen+1);
928          log_f ("keyserver_search:\n");          _snprintf (request, reqlen, fmt,
929                           skip_type_prefix (hostname), port, hostname, port,
930      if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))                     proxy.base64_user, enc_octets+9, enc_pubkey);
931          return WPTERR_GENERAL;      }
932            else {
933      if (debug)          fmt = "POST /pks/add HTTP/1.0\r\n"
934          log_f ("%s\n", buf);                "Referer: \r\n"
935                      "User-Agent: WinPT/W32\r\n"
936      if (!strncmp (buf, "pub", 3)) {                "Host: %s:%d\r\n"
937          int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;                "Content-type: application/x-www-form-urlencoded\r\n"
938          key->bits = atol (buf+3);                "Content-length: %d\r\n"
939          p = strchr (buf, '>');                "\r\n"
940          if (!p)                "keytext=%s"
941              goto fail;                "\r\n";
942          pos = p - buf + 1;          reqlen += strlen (fmt)+1;
943          memcpy (key->keyid, buf + pos, 8);          request = safe_alloc (reqlen+1);
944          key->keyid[8] = '\0';          _snprintf (request, reqlen, fmt,
945          p = strstr (buf, "</a>");                     skip_type_prefix (hostname), port,
946          if (!p)                     enc_octets+9, enc_pubkey);
947              goto fail;      }
948          pos = p - buf + 5;  
949          memcpy (key->date, buf + pos, 10);      free_if_alloc (enc_pubkey);
950          key->date[10] = '\0';      log_debug ("request:\r\n%s\r\n", request);
951          if (revoked) {      return request;
952              strcpy (key->uid, "KEY REVOKED: not checked");  }
953              return 0;  
954          }  
955          pos += 10;  /* Interface for receiving a public key. */
956          p = buf + pos + 1;  int
957          while (p && *p != '>')  kserver_recvkey (const char *hostname, WORD port, const char *keyid,
958              p++;                   char **r_key, int *r_keylen)
959          p++;  {
960          uidlen = strlen (p) - 10;      const char *fmt;
961          memcpy (key->uid, p, uidlen);      char *request = NULL;
962          key->uid[uidlen] = '\0';      int conn_fd;
963          strcat (key->uid, ">");      int rc, reqlen;
964          p = strchr (key->uid, '&');  
965          if (p) {      if (!port)
966              key->uid[(p-key->uid)] = '<';          port = HKP_PORT;
967              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4, strlen (key->uid)-3);      hkp_err = 0; /* reset */
968          }      rc = kserver_connect (hostname, port, &conn_fd);
969          return 0;      if (rc)
970      }          goto leave;
971    
972  fail:      reqlen = strlen (hostname)+32+strlen (keyid)+1;
973      key->bits = 0;      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
974      memset (key, 0, sizeof *key);          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"
975      return 0;                "Proxy-Authorization: Basic %s\r\n\r\n";
976  } /* kserver_search */          reqlen =+ strlen (fmt) + strlen (proxy.base64_user)+1;
977            request = safe_alloc (reqlen+1);
978            _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
979  static int                     keyid, proxy.base64_user);
980  add_node( keyserver_cfgfile *cfg, const char *entry )      }
981  {      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
982      keyserver_node *node;          fmt = "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
983      char *p = NULL;          reqlen += strlen (fmt)+1;
984                request = safe_alloc (reqlen+1);
985      p = strchr( entry, '=' );          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname),
986      if( p == NULL )                                           port, keyid);
987          return WPTERR_GENERAL;        }
988      node = new keyserver_node;      else {
989      if( !node )          fmt = "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n";
990          BUG( NULL );          reqlen += strlen (fmt)+1;
991                request = safe_alloc (reqlen+1);
992      memset( node, 0, sizeof *node );          _snprintf (request, reqlen, fmt, keyid);
993      node->used = 1;      }
994        
995      node->host.used = 1;      log_debug ("request:\r\n%s\r\n", request);
996      node->host.proto = proto_from_URL( entry );      
997      memcpy( node->host.name, entry+7, p-entry-7 );      rc = sock_write (conn_fd, request, strlen (request));
998      node->next = cfg->list;      if (rc == SOCKET_ERROR) {
999      cfg->list = node;          rc = WPTERR_WINSOCK_RECVKEY;
1000                goto leave;
1001      return 0;      }
1002  } /* add_node */      
1003        rc = sock_read_ext (conn_fd, r_key, r_keylen);
1004        if (rc == SOCKET_ERROR) {
1005  void          rc = WPTERR_WINSOCK_RECVKEY;
1006  kserver_change_proxy( keyserver_proxy_ctx *ctx )          goto leave;
1007  {          }
1008      proxy.port = ctx->port;  
1009      free_if_alloc (proxy.host);      log_debug ("response:\r\n%s\r\n", *r_key);
1010      proxy.host = ctx->host? m_strdup( ctx->host ) : NULL;      rc = check_hkp_response (*r_key, 1);
1011      free_if_alloc( proxy.pass );      if (rc)
1012      proxy.pass = ctx->pass? m_strdup( ctx->pass ) : NULL;          goto leave;
1013      free_if_alloc( proxy.user );      
1014      proxy.user = ctx->user? m_strdup( ctx->user ) : NULL;      WSASetLastError (0);
1015      set_reg_proxy_prefs( proxy.host, proxy.port, proxy.user, proxy.pass );      
1016  } /* kserver_change_proxy */  leave:
1017        closesocket (conn_fd);
1018        free_if_alloc (request);
1019  int      return rc;
1020  kserver_read_config( const char *fname, keyserver_cfgfile **ret_cfg )  }
1021  {  
1022      FILE *fp;  
1023      keyserver_cfgfile *cfg;  /* Interface to send a public key. */
1024      char buf[256];  int
1025      int rc = 0;  kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )
1026        {
1027      *ret_cfg = NULL;      char *request = NULL;
1028      fp = fopen( fname, "rb" );      char log[2048] = {0};
1029      if( fp == NULL )      int conn_fd, n;
1030          return WPTERR_FILE_OPEN;      int rc;
1031            
1032      cfg = new keyserver_cfgfile;      hkp_err = 0; /* reset */
1033      if ( !cfg )      rc = kserver_connect (hostname, port, &conn_fd);
1034          BUG( NULL );      if (rc)
1035      memset( cfg, 0, sizeof *cfg );          goto leave;
1036            
1037      while ( !feof( fp ) ) {      request = kserver_send_request (hostname, port, pubkey, len);
1038          if ( fgets( buf, sizeof(buf)-1, fp ) == NULL )      if (request == NULL) {
1039              break;          rc = WPTERR_GENERAL;
1040          if ( *buf == '\r' || *buf == '\n' || *buf == '#' )          goto leave;    
1041              continue;      }
1042          buf[strlen(buf) -2] = '\0';      
1043          if ( !strncmp( buf, "use_proxy=", 10 ) ) {      rc = sock_write (conn_fd, request, strlen (request));
1044              char *p = strchr(buf, ':');      if (rc == SOCKET_ERROR) {
1045              if (!p)          rc = WPTERR_WINSOCK_SENDKEY;
1046                  continue;          goto leave;    
1047              cfg->proxy.port = atol( buf+(p-buf+1) );      }
1048              buf[p-buf] = '\0';      
1049              cfg->proxy.host = m_strdup( buf+10 );      rc = sock_read (conn_fd, log, DIM (log)-1, &n);
1050          }      if (rc == SOCKET_ERROR) {
1051          else if ( !strncmp( buf, "proxy_user=", 11 ) )          rc = WPTERR_WINSOCK_SENDKEY;
1052              cfg->proxy.user = m_strdup( buf+11 );          goto leave;
1053          else if ( !strncmp( buf, "proxy_pass=", 11 ) )      }
1054              cfg->proxy.pass = m_strdup( buf+11 );  
1055          if ( !strncmp( buf, "http://", 7 )      log_debug ("kserver_sendkey: read %d bytes\r\n%s\r\n", n, log);
1056              || !strncmp( buf, "hkp://", 6 )      rc = check_hkp_response (log, 0);
1057              || !strncmp( buf, "ldap://", 7 ) ) {      if (rc)
1058              add_node( cfg, buf );          goto leave;
1059              cfg->nlist++;      
1060          }      WSASetLastError (0);
1061      }      
1062        leave:
1063      fclose( fp );      closesocket (conn_fd);
1064      *ret_cfg = cfg;      free_if_alloc (request);
1065            return rc;
1066      return rc;  }
1067  } /* kserver_read_config */  
1068    
1069    /* Check keyserver response. */
1070  int  static int
1071  kserver_write_config( const char * fname, keyserver_cfgfile * cfg )  kserver_search_chkresp (int fd)
1072  {  {
1073            char buf[128];
1074      return 0;      int n=0;
1075  }      
1076        /* parse response 'HTTP/1.0 500 OK' */
1077        if (sock_getline (fd, buf, DIM (buf)-1, &n))
1078  void          return WPTERR_KEYSERVER_NOTFOUND;
1079  kserver_cfgfile_release( keyserver_cfgfile *cfg )  
1080  {            log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1081      keyserver_node *k, *k2;      if (strncmp (buf, "HTTP/1.", 7))
1082            return WPTERR_KEYSERVER_NOTFOUND;
1083      proxy_release( &cfg->proxy );      if (strncmp (buf+(8+1), "200", 3))
1084      for( k = cfg->list; cfg->nlist--; k = k2 ) {          return WPTERR_KEYSERVER_NOTFOUND;
1085          k2 = k->next;      return 0;
1086          free_if_alloc( k );      }
1087      }  
1088      free_if_alloc( cfg );  
1089  } /* kserver_cfgfile_release */  /* End the keyserver search procedure. */
1090    void
1091    kserver_search_end (int conn_fd)
1092  void  {
1093  proxy_release( keyserver_proxy_ctx *ctx )      log_debug ("kserver_search_end: fd=%d\r\n", conn_fd);
1094  {      closesocket (conn_fd);
1095      free_if_alloc( ctx->host );  }
1096      free_if_alloc( ctx->pass );  
1097      free_if_alloc( ctx->user );  
1098  } /* proxy_release */  /* Extract the amount of keys from the info record. */
1099    static int
1100    count_keys_in_response (char *buf)
1101  int  {
1102  ldap_recvkey (const char * host, const char * keyid, char * key, int maxkeylen)      char *p;
1103  {      int recno = 0;
1104      const char *s;      int n = 0;
1105      char *ksprg = NULL, *p = NULL;  
1106      char temp[512], outf[512];      /* info:1:4 */
1107      FILE * inp;      if (strncmp (buf, "info", 4))
1108      int rc, start_key = 0;          return 0;
1109      STARTUPINFO si;      p = strtok (buf, ":");
1110      PROCESS_INFORMATION pi;      while (p != NULL) {
1111            recno++;
1112      p = get_gnupg_path ();          if (recno == 3)
1113      ksprg = new char[strlen (p) + 1 + 128];              n = atoi (p);
1114      if (!ksprg)          p = strtok (NULL, ":");
1115          BUG (0);      }
1116      strcpy (ksprg, p);      return n;
1117      strcat (ksprg, "\\");  }
1118      strcat (ksprg, "gpgkeys_ldap.exe");  
1119      free_if_alloc (p);  
1120      if (file_exist_check (ksprg)) {  /* Start the keyserver search.
1121          log_box ( "LDAP Keyserver Plugin", MB_ERR, "Could not find LDAP keyserver module!");     Connect to host @hostname and port @port.
1122          rc = -1;     The pattern are given in @pattern.
1123          goto leave;     The socket is returned in @conn_fd and @nkeys contains
1124      }     the amount of keys which were found. */
1125      GetTempPath (sizeof (temp)-1, temp);  int
1126      strcpy (outf, temp);  kserver_search_begin (const char *hostname, WORD port,
1127      strcat (outf, keyid);                        const char *pattern, int *conn_fd, int *nkeys)
1128      strcat (outf, ".out");  {
1129      strcat (temp, keyid);      const char *fmt;
1130      inp = fopen (temp, "w+b");      char *request = NULL;
1131      if( !inp ) {      char *enc_patt = NULL;
1132          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", temp,      char status[128];
1133                   winpt_strerror (WPTERR_FILE_OPEN));      int rc, sock_fd;
1134          rc = -1;      int reqlen;
1135          goto leave;      
1136      }      *conn_fd = 0;
1137      fprintf (inp,  
1138          "VERSION 0\n"      rc = kserver_connect (hostname, port, &sock_fd);
1139          "HOST %s\n"      if (rc)
1140          "OPTION verbose\n"          goto leave;
1141          "COMMAND GET\n"  
1142          "\n"      enc_patt = URL_encode (pattern, strlen (pattern), NULL);
1143          "%s\n", host? skip_type_prefix (host): "64.94.85.200", keyid);      reqlen = strlen (enc_patt) + strlen (hostname) + 32 + 1;
1144      fclose (inp);  
1145        if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
1146      memset (&si, 0, sizeof (si));          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n"
1147      si.cb = sizeof (si);                "Proxy-Authorization: Basic %s\r\n\r\n";
1148      si.dwFlags = STARTF_USESHOWWINDOW;          reqlen += strlen (proxy.base64_user) + strlen (fmt) + 1;
1149      si.wShowWindow = SW_HIDE;          request = safe_alloc (reqlen+1);
1150      memset (&pi, 0, sizeof (pi));          _snprintf (request, reqlen, fmt, skip_type_prefix (hostname), port,
1151      p = new char[strlen (ksprg) + strlen (temp) + strlen (outf) + 32];                     enc_patt, proxy.base64_user);
1152      sprintf (p, "%s -o %s %s", ksprg, outf, temp);      }    
1153      rc = CreateProcess (NULL, p, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
1154      if (!rc) {          fmt = "GET http://%s:%d/pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1155          log_box ("LDAP Keyserver Plugin", MB_ERR, "Could not spawn process");          reqlen += strlen (fmt)+1;
1156          rc = -1;          request = safe_alloc (reqlen+1);
1157          goto leave;          _snprintf (request, reqlen, skip_type_prefix (hostname), port,
1158      }                              enc_patt);
1159      CloseHandle (pi.hThread);      }
1160      WaitForSingleObject (pi.hProcess, INFINITE);      else {
1161      CloseHandle (pi.hProcess);          fmt = "GET /pks/lookup?options=mr&op=index&search=%s HTTP/1.0\r\n\r\n";
1162            reqlen += strlen (fmt)+1;
1163      inp = fopen (outf, "rb");          request = safe_alloc (reqlen+1);
1164      if (!inp) {          _snprintf (request, reqlen, fmt, enc_patt);
1165          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,      }
1166                   winpt_strerror (WPTERR_FILE_OPEN));  
1167          rc = -1;      log_debug ("kserver_search_begin:\r\n%s\r\n", request);
1168          goto leave;      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1169      }          rc = WPTERR_GENERAL;
1170      memset (key, 0, maxkeylen);          goto leave;
1171      while( !feof( inp ) ) {      }
1172          s = fgets( temp, sizeof (temp)-1, inp );      
1173          if( !s )      rc = kserver_search_chkresp (sock_fd);
1174              break;      if (rc) {
1175          if( !start_key && strstr( s, "KEY" ) && strstr( s, "BEGIN" ) ) {          closesocket (sock_fd);
1176              start_key = 1;          sock_fd = 0;
1177              continue;          goto leave;
1178          }            }
1179          if( !start_key )  
1180              continue;      /* Skip all lines until we reach the "info:" record. */
1181          strcat( key, temp );      for (;;) {
1182          maxkeylen -= strlen( temp );          if (sock_getline (sock_fd, status, DIM (status)-1, &reqlen)) {  
1183          if( maxkeylen < 0 || (strstr( s, "KEY" ) && strstr( s, "END" )) )                        log_debug ("kserver_search_begin: retrieving status line failed.\r\n");
1184              break;              closesocket (sock_fd);
1185      }              sock_fd = 0;
1186      fclose( inp );                  rc = WPTERR_GENERAL;
1187                break;
1188  leave:          }
1189      if( !strlen( key ) )          if (!strncmp (status, "info:", 5))
1190          rc = WPTERR_WINSOCK_RECVKEY;              break;
1191      free_if_alloc( p );      }
1192      free_if_alloc( ksprg );  
1193      return rc;      if (!rc)
1194  } /* ldap_recvkey */          *nkeys = count_keys_in_response (status);
1195        *conn_fd = sock_fd;
1196        
1197  static int  leave:
1198  finger_readline (int fd, char * buf, int nbytes)      free_if_alloc (request);
1199  {      free_if_alloc (enc_patt);
1200      char c = 0;      return rc;
1201      int n, pos = 0;  }
1202        
1203      while (nbytes > 0) {  
1204          n = recv (fd, &c, 1, 0);  /* Parse a single pub record returned by the keyserver. */
1205          if (n <= 0)  static void
1206              break;  parse_pub_record (keyserver_key_s *key, char *buf)
1207          if (c == '\n')  {
1208              break;      enum pub_rec_t {ID=1, KEYID, ALGO, SIZE, CREATE, EXPIRE};
1209          buf[pos++] = c;      char *p;
1210          nbytes--;      int recno = 0;
1211      }      int off = 0;
1212      if (nbytes > 0)  
1213          buf[pos++] = '\0';      /* pub:BF3DF9B4:17:1024:925411133:: */
1214      if (n <= 0)      p = strtok (buf, ":");
1215          pos = n;      while (p != NULL) {
1216      return pos;          recno++;
1217  }          switch (recno) {
1218            case ID:
1219                break;
1220  int  
1221  finger_recvkey (const char * host, const char * user, char * key, int maxkeylen)          case KEYID:
1222  {              /* If for any reason the returned record actually contains
1223      struct hostent * hp;                 a fingerprint instead of a key ID, we truncate the fpr. */
1224      struct sockaddr_in saddr;              off = strlen (p) == 40? 32 : 0;
1225      char buf[128];              free_if_alloc (key->keyid);
1226      int fd, nread;              key->keyid = m_strdup (p+off);
1227      int start_key = 0;              break;
1228      int rc=0;  
1229            case ALGO:
1230      fd = socket (PF_INET, SOCK_STREAM, 0);              key->algo = atoi (p);
1231      if (fd == -1)              break;
1232          return WPTERR_WINSOCK_SOCKET;              
1233      hp = gethostbyname (skip_type_prefix (host));          case SIZE:
1234      if (!hp) {              key->bits = atoi (p);
1235          closesocket (fd);              break;
1236          return WPTERR_WINSOCK_RESOLVE;  
1237      }          case CREATE:
1238                key->creation = strtoul (p, NULL, 10);
1239      memset (&saddr, 0, sizeof (saddr));              break;
1240      saddr.sin_family = AF_INET;  
1241      saddr.sin_port = htons (FINGER_PORT);          case EXPIRE:
1242      saddr.sin_addr = *(struct in_addr *)hp->h_addr;              key->expires = strtoul (p, NULL, 10);
1243      if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {              break;
1244          closesocket (fd);          }
1245          return WPTERR_WINSOCK_CONNECT;          p = strtok (NULL, ":");
1246      }      }
1247      send (fd, user, strlen (user), 0);  }
1248      send (fd, "\r\n", 2, 0);  
1249    
1250      memset (key, 0, maxkeylen);  /* Parse a single user id returned by the keyserver. */
1251      while (maxkeylen > 0) {  static void
1252          nread = finger_readline (fd, buf, sizeof (buf)-1);  parse_uid_record (keyserver_key_s *key, char *buf)
1253          if (nread <= 0)  {
1254              break;      enum uid_rec_t {ID=1, UID, CREATE, EXPIRE};
1255          strcat (buf, "\n");      keyserver_uid_s *u, *n;
1256          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {      char *p, *raw;
1257              strcat (key, buf);      int recno = 0;
1258              start_key = 1;  
1259              maxkeylen -= nread;      /* uid:Timo Schulz <[email protected]>:1138440360:: */
1260          }      u = new keyserver_uid_s;
1261          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {      memset (u, 0, sizeof *u);
1262              strcat (key, buf);  
1263              start_key--;      p = strtok (buf, ":");
1264              maxkeylen -= nread;      while (p != NULL) {
1265              break;          recno++;
1266          }  
1267          else if (start_key) {          switch (recno) {
1268              strcat (key, buf);          case ID:
1269              maxkeylen -= nread;              break;
1270          }  
1271      }          case UID:
1272      closesocket (fd);              unhexify_buffer (p, &raw);
1273      if (start_key != 0)              u->uid = utf8_to_native (raw);
1274          rc = WPTERR_WINSOCK_RECVKEY;              free_if_alloc (raw);
1275      return rc;              break;
1276  }  
1277            case CREATE:
1278                u->creation = strtoul (p, NULL, 10);
1279  int              break;
1280  check_IP_or_hostname (const char *name)  
1281  {          case EXPIRE:
1282      const char *not_allowed = "=!�$%&@#*~\\/}][{<>|,;:'";              u->expires = strtoul (p, NULL, 10);
1283      size_t i, j;              break;
1284            }
1285      for (i=0; i < strlen (name); i++) {  
1286          for (j =0; j < strlen (not_allowed); j++) {          p = strtok (NULL, ":");
1287              if (name[i] == not_allowed[j])      }
1288                  return -1;      if (!key->uids)
1289          }          key->uids = u;
1290      }      else {
1291      return 0;          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.23  
changed lines
  Added in v.271

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26