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

Legend:
Removed from v.5  
changed lines
  Added in v.181

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26