/[winpt]/trunk/Src/wptKeyserver.cpp
ViewVC logotype

Diff of /trunk/Src/wptKeyserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.2  
changed lines
  Added in v.185

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26