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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26