/[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 13 by twoaday, Mon Apr 25 07:15:30 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 + strlen (proxy_pass)];      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          if (r_port)      }
534              *r_port = proxy.port;      return str;
535          return proxy.host;  }
536      }  
537      return NULL;  
538  } /* kserver_get_proxy */  /* Save the keyserver config file in @conf. */
539    int
540    kserver_save_conf (const char *conf)
541  const char *  {
542  kserver_get_proxy_info (int id)      FILE *fp;
543  {      int pos;
544      switch (id) {    
545      case PROXY_USER: return proxy.user;      fp = fopen (conf, "wb");
546      case PROXY_PASS: return proxy.pass;      if (!fp) {
547      }          msg_box (NULL, _("Could not save keyserver.conf file"),
548      return NULL;                   _("Keyserver"), MB_ERR);
549  } /* kserver_get_proxy_info */          return -1;
550        }
551    
552  /*      fprintf (fp, "# do NOT manually modify this file, it will be "
553   * Connect to the keyserver 'hostname'.                   "generated automatically!!\r\n");
554   * We always use the HKP port.      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
555   */          if (!server[pos].used)
556  int              continue;
557  kserver_connect (const char *hostname, u16 port, int *conn_fd)          fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
558  {      }
559      int rc, fd;      fclose (fp);
560      u32 iaddr;      return 0;
561      char host[128] = {0};  }
562      struct hostent *hp;  
563      struct sockaddr_in sock;  
564    /* Load the keyserver config file @conf. */
565      if (debug)  int
566          log_f ("kserver_connect: %s:%d\r\n", hostname, port);  kserver_load_conf (const char *conf)
567      if (!port)  {
568          port = HKP_PORT;      struct stat statbuf;
569      if (conn_fd)      FILE *fp;
570          *conn_fd = 0;      char buf[1024], *s, *p;
571      hostname = skip_type_prefix (hostname);      char *user = NULL, *pass = NULL;    
572            int no_config=0, chk_pos=0;
573      memset (&sock, 0, sizeof (sock));      int pos;
574      sock.sin_family = AF_INET;      
575      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
576      if (proxy.host)          server[pos].used = 0;
577          strncpy (host, proxy.host, 127);          server[pos].port = HKP_PORT;
578      else      }
579          strncpy (host, hostname, 127);      
580            fp = fopen (conf, "rb");
581      if ((iaddr = inet_addr (host)) != INADDR_NONE)      if (!fp) {
582          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));          for (pos = 0; server_list[pos]; pos++) {
583      else if ((hp = gethostbyname (host))) {              server[pos].used = 1;
584          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {              server[pos].name = m_strdup (server_list[pos]);
585              log_f ("gethostbyname: unknown address type.\r\n");              server[pos].proto = proto_from_URL (server_list[pos]);
586              return WPTERR_WINSOCK_RESOLVE;          }
587          }          no_config=1;
588          memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);      }
589      }      get_reg_proxy_prefs (&proxy);
590      else {      if (user && pass)
591          if (debug)          update_proxy_user (user, pass);
592              log_f ("gethostbyname: failed.\r\n");      else if (user && !pass || !user && pass) {
593          return WPTERR_WINSOCK_RESOLVE;          msg_box (NULL, _("Invalid proxy configuration."
594      }                           "You need to set a user and a password"
595      fd = socket (AF_INET, SOCK_STREAM, 0);                           "to use proxy authentication!"),
596      if (fd == INVALID_SOCKET)                             _("Proxy Error"), MB_ERR);
597          return WPTERR_WINSOCK_SOCKET;      }
598      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));      /* check if the host has a http:// prefix and skip it */
599      if (rc == SOCKET_ERROR) {      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
600          if (debug)          char *host = m_strdup (proxy.host+7);
601              log_f ("connect: failed.\r\n");          if (!host)
602          closesocket (fd);              BUG (0);
603          return WPTERR_WINSOCK_CONNECT;          free_if_alloc (proxy.host);
604      }          proxy.host = host;
605        }
606      if (conn_fd)      free_if_alloc (user);
607          *conn_fd = fd;      free_if_alloc (pass);
608      WSASetLastError (0);      
609      return 0;      pos = 0;
610  } /* kserver_connect */      while (fp && !feof (fp)) {
611            s = fgets (buf, sizeof (buf)-1, fp);
612            if (!s)
613  static char*              break;
614  kserver_urlencode (const char *pubkey, int octets, int *newlen)          if (strstr (buf, "\r\n"))
615  {              buf[strlen (buf)-2] = '\0';
616      char *p, numbuf[5];          if (strstr (buf, "\n"))
617      size_t j = 0;              buf[strlen (buf)-1] = '\0';
618      int i, size;          s = (char *)skip_whitespace (buf);
619                if (*s == '#' || strlen (s) < 7)
620      p = new char [2*octets];              continue;
621      if (!p)          if (check_URL (s)) {
622          BUG (0);              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
623                                 "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
624      for (size=0, i=0; i<octets; i++) {                               _("Keyserver Error"), MB_ERR);
625          if (isalnum (pubkey[i]) || pubkey[i] == '-') {              continue;
626              p[size] = pubkey[i];          }
627              size++;          chk_pos = 6;
628          }          if (strstr (s, "finger"))
629          else if (pubkey[i] == ' ') {              chk_pos = 10;
630              p[size] = '+';          p = strchr (s+chk_pos, ':');
631              size++;          server[pos].used = 1;
632          }          server[pos].proto = proto_from_URL (s);
633          else {          server[pos].port = port_from_proto (server[pos].proto);
634              sprintf(numbuf, "%%%02X", pubkey[i]);          if (!p)
635              for (j = 0; j<strlen(numbuf); j++) {              server[pos].name = m_strdup (s);
636                  p[size] = numbuf[j];          else {      
637                  size++;              server[pos].port = atol (p+1);
638              }              if (server[pos].port < 0 || server[pos].port > 65536)
639          }                  server[pos].port = HKP_PORT;
640      }              server[pos].name = new char [(p-s)+2];
641      p[size] = '\0';              if (!server[pos].name)
642      *newlen = size;                  BUG (0);
643      return p;              memset (server[pos].name, 0, (p-s)+2);
644  } /* kserver_urlencode */              memcpy (server[pos].name, s, (p-s));
645            }
646            pos++;
647  /*          if (pos > MAX_KEYSERVERS) {
648   * Format a request for the given keyid (send).              msg_box (NULL, _("The keyserver limit is exceeded"),
649   */                       _("Keyserver Warning"), MB_INFO);
650  static char*              break;
651  kserver_send_request (const char *hostname, u16 port, const char *pubkey, int octets)          }
652  {      }
653      char *request = NULL, *enc_pubkey = NULL;      if (fp)
654      int reqlen, enc_octets;          fclose (fp);
655            if (!pos) {
656      if (debug)          /* only issue an error if the config file exist but
657          log_f ("kserver_send_request: %s:%d\n", hostname, port);             it has no valid entries. */
658      if (!port)          keyserver_set_default (NULL, HKP_PORT);
659          port = HKP_PORT;          if (!no_config)
660      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);              return WPTERR_CONFIG_FILE;
661      request = new char[reqlen];      }
662      if (!request)  
663          BUG (0);      if (!stat (conf, &statbuf))
664      enc_pubkey = kserver_urlencode (pubkey, octets, &enc_octets);          conf_timestamp = statbuf.st_mtime;
665      if (!enc_pubkey || !enc_octets) {      return 0;
666          free_if_alloc (request);  }
667          return NULL;  
668      }  
669        /* Connect to the keyserver @hostname (port @port).
670      if (proxy.user) {     Return value: 0 on success */
671          _snprintf (request, reqlen-1,  int
672                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"  kserver_connect (const char *hostname, WORD port, int *conn_fd)
673                     "Referer: \r\n"  {
674                     "User-Agent: WinPT/W32\r\n"      int rc, fd;
675                     "Host: %s:%d\r\n"      DWORD iaddr;
676                     "Proxy-Authorization: Basic %s\r\n"      char host[128] = {0};
677                     "Content-type: application/x-www-form-urlencoded\r\n"      struct hostent *hp;
678                     "Content-length: %d\r\n"      struct sockaddr_in sock;
679                     "\r\n"  
680                     "keytext=%s"      log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
681                     "\n",  
682                     skip_type_prefix (hostname), port, hostname, port,      if (!port)
683                     proxy.base64_user, enc_octets+9, enc_pubkey);          port = HKP_PORT;
684      }      if (conn_fd)
685      else {          *conn_fd = 0;
686          _snprintf (request, reqlen-1,      hostname = skip_type_prefix (hostname);
687                     "POST /pks/add HTTP/1.0\r\n"      
688                     "Referer: \r\n"      memset (&sock, 0, sizeof (sock));
689                     "User-Agent: WinPT/W32\r\n"      sock.sin_family = AF_INET;
690                     "Host: %s:%d\r\n"      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);
691                     "Content-type: application/x-www-form-urlencoded\r\n"      if (proxy.host)
692                     "Content-length: %d\r\n"          strncpy (host, proxy.host, 127);
693                     "\r\n"      else
694                     "keytext=%s"          strncpy (host, hostname, 127);
695                     "\n",      
696                     skip_type_prefix (hostname), port, enc_octets+9, enc_pubkey);      if ((iaddr = inet_addr (host)) != INADDR_NONE)
697      }          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
698      free_if_alloc (enc_pubkey);      else if ((hp = gethostbyname (host))) {
699      if (debug)          if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
700          log_f ("%s\n", request);              log_debug ("gethostbyname: unknown address type.\r\n");
701      return request;              return WPTERR_WINSOCK_RESOLVE;
702  } /* kserver_send_request */          }
703            memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
704        }
705  /*      else {
706   * Interface receiving a public key.          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
707   */          return WPTERR_WINSOCK_RESOLVE;
708  int      }
709  kserver_recvkey (const char *hostname, u16 port, const char *keyid, char *key, int maxkeylen)      fd = socket (AF_INET, SOCK_STREAM, 0);
710  {            if (fd == INVALID_SOCKET)  
711      int rc, n;          return WPTERR_WINSOCK_SOCKET;
712      int conn_fd;      rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
713      char *request = NULL;      if (rc == SOCKET_ERROR) {
714                log_debug ("connect: failed ec=%d.\r\n", net_errno);
715      if (!port)          closesocket (fd);
716          port = HKP_PORT;          return WPTERR_WINSOCK_CONNECT;
717      hkp_err = 0; /* reset */          }
718      rc = kserver_connect (hostname, port, &conn_fd);  
719      if (rc)      if (proxy.proto != PROXY_PROTO_HTTP) {
720          goto leave;          rc = socks_handshake (&proxy, fd, hostname, port);
721                if (rc) {
722      request = new char[300+1];              closesocket (fd);
723      if (!request)              return WPTERR_GENERAL; /* XXX: use better code. */
724          BUG (0);          }
725            }
726      if (proxy.host && proxy.user) {  
727          _snprintf (request, 300,      if (conn_fd)
728              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"          *conn_fd = fd;
729              "Proxy-Authorization: Basic %s\r\n\r\n",      WSASetLastError (0);
730              skip_type_prefix (hostname), port, keyid, proxy.base64_user);      return 0;
731      }  }
732      else if (proxy.host) {  
733          _snprintf (request, 300,  
734              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",  static bool
735              skip_type_prefix (hostname), port, keyid);  URL_must_encoded (const char *url)
736      }      {
737      else {      if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
738          _snprintf (request, 300,          return true;
739              "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);      return false;
740      }    }
741      if (debug)  
742          log_f ("%s\r\n", request);  
743        /* Perform URL encoding of the given data. */
744      rc = sock_write (conn_fd, request, strlen (request));  static char*
745      if (rc == SOCKET_ERROR) {  URL_encode (const char *url, size_t ulen, size_t *ret_nlen)
746          rc = WPTERR_WINSOCK_RECVKEY;  {
747          goto leave;      gpgme_data_t hd;
748      }      char numbuf[5], *pp, *p;
749            size_t i, n;
750      rc = sock_read( conn_fd, key, maxkeylen, &n );  
751      if( rc == SOCKET_ERROR ) {      gpgme_data_new (&hd);
752          rc = WPTERR_WINSOCK_RECVKEY;      for (i=0; i < ulen; i++) {
753          goto leave;          if (isalnum (url[i]) || url[i] == '-')
754      }              gpg_data_putc (hd, url[i]);
755                else if (url[i] == ' ')
756      if (debug)              gpg_data_putc (hd, '+');
757          log_f("%s\r\n", key);          else {
758      rc = check_hkp_response (key, 1);              sprintf (numbuf, "%%%02X", url[i]);
759      if (rc)              gpgme_data_write (hd, numbuf, strlen (numbuf));
760          goto leave;          }
761            }
762      WSASetLastError (0);      gpg_data_putc (hd, '\0');
763        
764  leave:      /* Copy memory to avoid that we need to use gpgme_free later. */
765      closesocket (conn_fd);      pp = gpgme_data_release_and_get_mem (hd, &n);
766      free_if_alloc (request);      p = m_strdup (pp);
767      return rc;      gpgme_free (pp);
768  } /* kserver_recvkey */      if (ret_nlen)
769            *ret_nlen = n;
770        return p;
771  /*  }
772   * Interface to send a public key.  
773   */  
774  int  /* Format a request for the given keyid (send). */
775  kserver_sendkey (const char *hostname, u16 port, const char *pubkey, int len )  static char*
776  {  kserver_send_request (const char *hostname, WORD port,
777      int n, rc;                        const char *pubkey, int octets)
778      int conn_fd;  {
779      char *request = NULL;      char *request = NULL;
780      char log[2048];      char *enc_pubkey = NULL;
781            size_t enc_octets;
782      hkp_err = 0; /* reset */      int reqlen;
783      rc = kserver_connect (hostname, port, &conn_fd);  
784      if (rc)      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
785          goto leave;  
786            if (!port)
787      request = kserver_send_request (hostname, port, pubkey, len);          port = HKP_PORT;
788      if (request == NULL) {      reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);
789          rc = WPTERR_GENERAL;      request = new char[reqlen];
790          goto leave;          if (!request)
791      }          BUG (0);
792            enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
793      rc = sock_write( conn_fd, request, lstrlen(request) );      if (!enc_pubkey || !enc_octets) {
794      if( rc == SOCKET_ERROR ) {          free_if_alloc (request);
795          rc = WPTERR_WINSOCK_SENDKEY;          return NULL;
796          goto leave;          }
797      }      
798            if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
799      rc = sock_read( conn_fd, log, sizeof (log)-1, &n );          _snprintf (request, reqlen-1,
800      if( rc == SOCKET_ERROR ) {                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"
801          rc = WPTERR_WINSOCK_SENDKEY;                     "Referer: \r\n"
802          goto leave;                     "User-Agent: WinPT/W32\r\n"
803      }                     "Host: %s:%d\r\n"
804      if (debug)                     "Proxy-Authorization: Basic %s\r\n"
805          log_f ("kserver_sendkey:\r\n%s\r\n", log);                     "Content-type: application/x-www-form-urlencoded\r\n"
806                           "Content-length: %d\r\n"
807      rc = check_hkp_response (log, 0);                     "\r\n"
808      if( rc )                     "keytext=%s"
809          goto leave;                     "\n",
810                           skip_type_prefix (hostname), port, hostname, port,
811      WSASetLastError (0);                     proxy.base64_user, enc_octets+9, enc_pubkey);
812            }
813  leave:      else {
814      closesocket (conn_fd);          _snprintf (request, reqlen-1,
815      free_if_alloc (request);                     "POST /pks/add HTTP/1.0\r\n"
816      return rc;                     "Referer: \r\n"
817  } /* kserver_sendkey */                     "User-Agent: WinPT/W32\r\n"
818                       "Host: %s:%d\r\n"
819                       "Content-type: application/x-www-form-urlencoded\r\n"
820  int                     "Content-length: %d\r\n"
821  kserver_search_init (const char * hostname, u16 port, const char * keyid, int * conn_fd)                     "\r\n"
822  {                     "keytext=%s"
823      int rc, sock_fd;                     "\n",
824      int n=0;                     skip_type_prefix (hostname), port,
825      char * request = NULL;                     enc_octets+9, enc_pubkey);
826            }
827      rc = kserver_connect (hostname, port, &sock_fd);      free_if_alloc (enc_pubkey);
828      if (rc) {  
829          *conn_fd = 0;      log_debug ("%s\r\n", request);
830          goto leave;      return request;
831      }  }
832        
833      n=300;  
834      request = new char[n+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, n,      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, n,      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, n,      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 ("kserver_search_init:\r\n%s\r\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 (debug)          rc = WPTERR_WINSOCK_RECVKEY;
880          log_f ("kserver_search_chkpresp: %s\r\n", buf);          goto leave;
881      if (strncmp (buf, "HTTP/1.", 7))      }
882          return WPTERR_KEYSERVER_NOTFOUND;  
883      if (strncmp (buf+(8+1), "200", 3))      if (r_keylen)
884          return WPTERR_KEYSERVER_NOTFOUND;          *r_keylen = n;
885      return 0;      log_debug("%s\r\n", *r_key);
886  } /* kserver_search_chkresp */      rc = check_hkp_response (*r_key, 1);
887        if (rc)
888            goto leave;
889  int      
890  kserver_search (int fd, keyserver_key * key)      WSASetLastError (0);
891  {      
892      char buf[1024], *p;  leave:
893      int uidlen, nbytes, pos = 0;      closesocket (conn_fd);
894            free_if_alloc (request);
895      if (debug)      return rc;
896          log_f ("keyserver_search:\n");  }
897        
898      if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))  /* Interface for receiving a public key. */
899          return WPTERR_GENERAL;  int
900        kserver_recvkey (const char *hostname, WORD port, const char *keyid,
901      if (debug)                   char *key, int maxkeylen)
902          log_f ("%s\n", buf);  {
903            char *tmpkey;
904      if (!strncmp (buf, "pub", 3)) {      int rc, nread=0;
905          int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;  
906          key->bits = atol (buf+3);      /* XXX: just a wrapper around the new method, replace it
907          p = strchr (buf, '>');              soon as possible. */
908          if (!p)      rc = kserver_recvkey_ext (hostname, port, keyid, &tmpkey, &nread);
909              goto fail;      if (rc)
910          pos = p - buf + 1;          return rc;
911          memcpy (key->keyid, buf + pos, 8);  
912          key->keyid[8] = '\0';      if (nread > maxkeylen) {
913          p = strstr (buf, "</a>");          free_if_alloc (tmpkey);
914          if (!p)          return WPTERR_GENERAL;
915              goto fail;      }
916          pos = p - buf + 5;      strcpy (key, tmpkey);
917          memcpy (key->date, buf + pos, 10);      free_if_alloc (tmpkey);
918          key->date[10] = '\0';      return 0;
919          if (revoked) {  }
920              strcpy (key->uid, "KEY REVOKED: not checked");  
921              return 0;  
922          }  /* Interface to send a public key. */
923          pos += 10;  int
924          p = buf + pos + 1;  kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )
925          while (p && *p != '>')  {
926              p++;      char *request = NULL;
927          p++;      char log[2048];
928          uidlen = strlen (p) - 10;      int conn_fd, n;
929          memcpy (key->uid, p, uidlen);      int rc;
930          key->uid[uidlen] = '\0';      
931          strcat (key->uid, ">");      hkp_err = 0; /* reset */
932          p = strchr (key->uid, '&');      rc = kserver_connect (hostname, port, &conn_fd);
933          if (p) {      if (rc)
934              key->uid[(p-key->uid)] = '<';          goto leave;
935              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4, strlen (key->uid)-3);      
936          }      request = kserver_send_request (hostname, port, pubkey, len);
937          return 0;      if (request == NULL) {
938      }          rc = WPTERR_GENERAL;
939            goto leave;    
940  fail:      }
941      key->bits = 0;      
942      memset (key, 0, sizeof *key);      rc = sock_write (conn_fd, request, strlen (request));
943      return 0;      if (rc == SOCKET_ERROR) {
944  } /* kserver_search */          rc = WPTERR_WINSOCK_SENDKEY;
945            goto leave;    
946        }
947  static int      
948  add_node( keyserver_cfgfile *cfg, const char *entry )      rc = sock_read (conn_fd, log, sizeof (log)-1, &n);
949  {      if (rc == SOCKET_ERROR) {
950      keyserver_node *node;          rc = WPTERR_WINSOCK_SENDKEY;
951      char *p = NULL;          goto leave;
952            }
953      p = strchr( entry, '=' );  
954      if( p == NULL )      log_debug ("kserver_sendkey:\r\n%s\r\n", log);
955          return WPTERR_GENERAL;        rc = check_hkp_response (log, 0);
956      node = new keyserver_node;      if (rc)
957      if( !node )          goto leave;
958          BUG( NULL );      
959            WSASetLastError (0);
960      memset( node, 0, sizeof *node );      
961      node->used = 1;  leave:
962            closesocket (conn_fd);
963      node->host.used = 1;      free_if_alloc (request);
964      node->host.proto = proto_from_URL( entry );      return rc;
965      memcpy( node->host.name, entry+7, p-entry-7 );  }
966      node->next = cfg->list;  
967      cfg->list = node;  
968        int
969      return 0;  kserver_search_init (const char *hostname, WORD port,
970  } /* add_node */                       const char *keyid, int *conn_fd)
971    {
972        char *request = NULL;
973  void      char *enc_keyid = NULL;
974  kserver_change_proxy( keyserver_proxy_ctx *ctx )      int n = 0;
975  {          int rc, sock_fd;
976      proxy.port = ctx->port;      
977      free_if_alloc (proxy.host);      rc = kserver_connect (hostname, port, &sock_fd);
978      proxy.host = ctx->host? m_strdup( ctx->host ) : NULL;      if (rc) {
979      free_if_alloc( proxy.pass );          *conn_fd = 0;
980      proxy.pass = ctx->pass? m_strdup( ctx->pass ) : NULL;          goto leave;
981      free_if_alloc( proxy.user );      }
982      proxy.user = ctx->user? m_strdup( ctx->user ) : NULL;  
983      set_reg_proxy_prefs( proxy.host, proxy.port, proxy.user, proxy.pass );      enc_keyid = URL_encode (keyid, strlen (keyid), NULL);
984  } /* kserver_change_proxy */      n=300;
985        request = new char[n+1];
986        if (!request)
987  int          BUG (0);
988  kserver_read_config( const char *fname, keyserver_cfgfile **ret_cfg )      
989  {      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
990      FILE *fp;          _snprintf (request, n,
991      keyserver_cfgfile *cfg;              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"
992      char buf[256];              "Proxy-Authorization: Basic %s\r\n\r\n",
993      int rc = 0;              skip_type_prefix (hostname), port, enc_keyid, proxy.base64_user);
994            }    
995      *ret_cfg = NULL;      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
996      fp = fopen( fname, "rb" );          _snprintf (request, n,
997      if( fp == NULL )              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",
998          return WPTERR_FILE_OPEN;              skip_type_prefix (hostname), port, enc_keyid);
999            }
1000      cfg = new keyserver_cfgfile;      else {
1001      if ( !cfg )          _snprintf (request, n,
1002          BUG( NULL );                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",
1003      memset( cfg, 0, sizeof *cfg );                     enc_keyid);
1004            }
1005      while ( !feof( fp ) ) {      
1006          if ( fgets( buf, sizeof(buf)-1, fp ) == NULL )      log_debug ("kserver_search_init:\r\n%s\r\n", request);
1007              break;      
1008          if ( *buf == '\r' || *buf == '\n' || *buf == '#' )      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1009              continue;          rc = WPTERR_GENERAL;
1010          buf[strlen(buf) -2] = '\0';          goto leave;
1011          if ( !strncmp( buf, "use_proxy=", 10 ) ) {      }
1012              char *p = strchr(buf, ':');      
1013              if (!p)      *conn_fd = sock_fd;
1014                  continue;      
1015              cfg->proxy.port = atol( buf+(p-buf+1) );  leave:
1016              buf[p-buf] = '\0';      free_if_alloc (request);
1017              cfg->proxy.host = m_strdup( buf+10 );      free_if_alloc (enc_keyid);
1018          }      return rc;
1019          else if ( !strncmp( buf, "proxy_user=", 11 ) )  }
1020              cfg->proxy.user = m_strdup( buf+11 );  
1021          else if ( !strncmp( buf, "proxy_pass=", 11 ) )  
1022              cfg->proxy.pass = m_strdup( buf+11 );  /* Check keyserver response. */
1023          if ( !strncmp( buf, "http://", 7 )  int
1024              || !strncmp( buf, "hkp://", 6 )  kserver_search_chkresp (int fd)
1025              || !strncmp( buf, "ldap://", 7 ) ) {  {
1026              add_node( cfg, buf );      char buf[128];
1027              cfg->nlist++;      int n=0;
1028          }      
1029      }      /* parse response 'HTTP/1.0 500 OK' */
1030            if (sock_getline (fd, buf, 127, &n))
1031      fclose( fp );          return WPTERR_KEYSERVER_NOTFOUND;
1032      *ret_cfg = cfg;  
1033            log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1034      return rc;      if (strncmp (buf, "HTTP/1.", 7))
1035  } /* kserver_read_config */          return WPTERR_KEYSERVER_NOTFOUND;
1036        if (strncmp (buf+(8+1), "200", 3))
1037            return WPTERR_KEYSERVER_NOTFOUND;
1038  int      return 0;
1039  kserver_write_config( const char * fname, keyserver_cfgfile * cfg )  }
1040  {  
1041        
1042      return 0;  /* Convert an iso date @iso_date (YYYY-MM-DD) into the locale
1043  }     representation and store it into @loc_date.
1044       Return value: 0 on success. */
1045    static int
1046  void  parse_iso_date (const char *iso_date, char *loc_date, size_t loclen)
1047  kserver_cfgfile_release( keyserver_cfgfile *cfg )  {
1048  {            SYSTEMTIME st;
1049      keyserver_node *k, *k2;      char buf[16] = {0}, *p;
1050        int pos=0;
1051      proxy_release( &cfg->proxy );  
1052      for( k = cfg->list; cfg->nlist--; k = k2 ) {      strncpy (buf, iso_date, sizeof (buf)-1);
1053          k2 = k->next;      p = strtok (buf, "-");
1054          free_if_alloc( k );          while (p != NULL) {
1055      }          switch (pos) {
1056      free_if_alloc( cfg );          case 0: st.wYear  = (WORD)atoi (p); pos++; break;
1057  } /* kserver_cfgfile_release */          case 1: st.wMonth = (WORD)atoi (p); pos++; break;
1058            case 2: st.wDay   = (WORD)atoi (p); pos++; break;
1059            default: break;
1060  void          }
1061  proxy_release( keyserver_proxy_ctx *ctx )          p = strtok (NULL, "-");
1062  {      }
1063      free_if_alloc( ctx->host );      if (pos != 3)
1064      free_if_alloc( ctx->pass );          return -1;
1065      free_if_alloc( ctx->user );      
1066  } /* proxy_release */      if (!GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
1067                            NULL, loc_date, loclen))
1068            return -1;
1069  int      return 0;
1070  ldap_recvkey (const char * host, const char * keyid, char * key, int maxkeylen)  }
1071  {  
1072      const char *s;  
1073      char *ksprg = NULL, *p = NULL;  int
1074      char temp[512], outf[512];  kserver_search (int fd, keyserver_key *key)
1075      FILE * inp;  {
1076      int rc, start_key = 0;      char buf[1024], *p;
1077      STARTUPINFO si;      int uidlen, nbytes, pos = 0;
1078      PROCESS_INFORMATION pi;  
1079        log_debug ("keyserver_search:\r\n");
1080      p = get_gnupg_path ();      
1081      ksprg = new char[strlen (p) + 1 + 128];      if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))
1082      if (!ksprg)          return WPTERR_GENERAL;
1083          BUG (0);  
1084      strcpy (ksprg, p);      log_debug ("%s\r\n", buf);
1085      strcat (ksprg, "\\");      
1086      strcat (ksprg, "gpgkeys_ldap.exe");      if (!strncmp (buf, "pub", 3)) {
1087      free_if_alloc (p);          int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;
1088      if (file_exist_check (ksprg)) {          key->bits = atol (buf+3);
1089          log_box ( "LDAP Keyserver Plugin", MB_ERR, "Could not find LDAP keyserver module!");          p = strchr (buf, '>');
1090          rc = -1;          if (!p)
1091          goto leave;              goto fail;
1092      }          pos = p - buf + 1;
1093      GetTempPath (sizeof (temp)-1, temp);          memcpy (key->keyid, buf + pos, 8);
1094      strcpy (outf, temp);          key->keyid[8] = '\0';
1095      strcat (outf, keyid);          p = strstr (buf, "</a>");
1096      strcat (outf, ".out");          if (!p)
1097      strcat (temp, keyid);              goto fail;
1098      inp = fopen (temp, "w+b");          pos = p - buf + 5;
1099      if( !inp ) {          memcpy (key->date, buf + pos, 10);
1100          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", temp,          key->date[10] = '\0';
1101                   winpt_strerror (WPTERR_FILE_OPEN));          parse_iso_date (key->date, key->date, sizeof (key->date)-1);
1102          rc = -1;          if (revoked) {
1103          goto leave;              strcpy (key->uid, "KEY REVOKED: not checked");
1104      }              return 0;
1105      fprintf (inp,          }
1106          "VERSION 0\n"          pos += 10;
1107          "HOST %s\n"          p = buf + pos + 1;
1108          "OPTION verbose\n"          while (p && *p != '>')
1109          "COMMAND GET\n"              p++;
1110          "\n"          p++;
1111          "%s\n", host? skip_type_prefix (host): "64.94.85.200", keyid);          uidlen = strlen (p) - 10;
1112      fclose (inp);          if (!strstr (p, "&lt;") && !strstr (p, "&gt;")) {
1113                pos=0;
1114      memset (&si, 0, sizeof (si));              while (p && *p && pos < sizeof (key->uid)-1) {
1115      si.cb = sizeof (si);                  if (*p == '<')
1116      si.dwFlags = STARTF_USESHOWWINDOW;                      break;
1117      si.wShowWindow = SW_HIDE;                  key->uid[pos++] = *p++;
1118      memset (&pi, 0, sizeof (pi));              }
1119      p = new char[strlen (ksprg) + strlen (temp) + strlen (outf) + 32];              key->uid[pos] ='\0';
1120      sprintf (p, "%s -o %s %s", ksprg, outf, temp);              return 0;
1121      rc = CreateProcess (NULL, p, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);          }
1122      if (!rc) {  
1123          log_box ("LDAP Keyserver Plugin", MB_ERR, "Could not spawn process");          if (uidlen > sizeof (key->uid)-1)
1124          rc = -1;              uidlen = sizeof (key->uid)-1;
1125          goto leave;          memcpy (key->uid, p, uidlen);
1126      }          key->uid[uidlen] = '\0';
1127      CloseHandle (pi.hThread);          strcat (key->uid, ">");
1128      WaitForSingleObject (pi.hProcess, INFINITE);          p = strchr (key->uid, '&');
1129      CloseHandle (pi.hProcess);          if (p) {
1130                key->uid[(p-key->uid)] = '<';
1131      inp = fopen (outf, "rb");              memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4,
1132      if (!inp) {                       strlen (key->uid)-3);
1133          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,          }
1134                   winpt_strerror (WPTERR_FILE_OPEN));          return 0;
1135          rc = -1;      }
1136          goto leave;  
1137      }  fail:
1138      memset (key, 0, maxkeylen);      key->bits = 0;
1139      while( !feof( inp ) ) {      memset (key, 0, sizeof *key);
1140          s = fgets( temp, sizeof (temp)-1, inp );      return 0;
1141          if( !s )  }
1142              break;  
1143          if( !start_key && strstr( s, "KEY" ) && strstr( s, "BEGIN" ) ) {  
1144              start_key = 1;  /* Release mbmers in the proxy context @ctx. */
1145              continue;  void
1146          }        kserver_proxy_release (keyserver_proxy_t ctx)
1147          if( !start_key )  {
1148              continue;      free_if_alloc (ctx->host);
1149          strcat( key, temp );      free_if_alloc (ctx->pass);
1150          maxkeylen -= strlen( temp );      free_if_alloc (ctx->user);
1151          if( maxkeylen < 0 || (strstr( s, "KEY" ) && strstr( s, "END" )) )            }
1152              break;  
1153      }  
1154      fclose( inp );      /* Spawn a process given by @cmdl. */
1155    static int
1156  leave:  spawn_application (char *cmdl)
1157      if( !strlen( key ) )  {
1158          rc = WPTERR_WINSOCK_RECVKEY;      STARTUPINFO si;
1159      free_if_alloc( p );      PROCESS_INFORMATION pi;
1160      free_if_alloc( ksprg );      int rc = 0;
1161      return rc;  
1162  } /* ldap_recvkey */      memset (&si, 0, sizeof (si));
1163        si.cb = sizeof (si);
1164        si.dwFlags = STARTF_USESHOWWINDOW;
1165  static int      si.wShowWindow = SW_HIDE;
1166  finger_readline (int fd, char * buf, int nbytes)      memset (&pi, 0, sizeof (pi));
1167  {  
1168      char c = 0;      if (!CreateProcess (NULL, cmdl, NULL, NULL, FALSE, 0,
1169      int n, pos = 0;                          NULL, NULL, &si, &pi)) {
1170                log_box ("Keyserver Plugin", MB_ERR, "Could not spawn helper process");
1171      while (nbytes > 0) {          rc = -1;
1172          n = recv (fd, &c, 1, 0);      }
1173          if (n <= 0)  
1174              break;      CloseHandle (pi.hThread);
1175          if (c == '\n')      WaitForSingleObject (pi.hProcess, INFINITE);
1176              break;      CloseHandle (pi.hProcess);
1177          buf[pos++] = c;      return rc;
1178          nbytes--;  }
1179      }  
1180      if (nbytes > 0)  
1181          buf[pos++] = '\0';  /* Receive an key via LDAP from host @host with the keyid @keyid.
1182      if (n <= 0)     @key contains the key on success. */
1183          pos = n;  int
1184      return pos;  ldap_recvkey (const char *host, const char *keyid, char *key, int maxkeylen)
1185  }  {    
1186        FILE *fp;
1187        const char *s;
1188  int      char *ksprg = NULL, *p = NULL, *sep;
1189  finger_recvkey (const char * host, const char * user, char * key, int maxkeylen)      char inf[256], outf[256], buf[512];
1190  {      DWORD n;
1191      struct hostent * hp;      int start_key = 0, failed = 0;
1192      struct sockaddr_in saddr;      int rc = 0;
1193      char buf[128];  
1194      int fd, nread;      p = get_gnupg_prog ();
1195      int start_key = 0;      n = strlen (p) + 1 + 128;
1196      int rc=0;      ksprg = new char[n+1];
1197        if (!ksprg)
1198      fd = socket (PF_INET, SOCK_STREAM, 0);          BUG (0);
1199      if (fd == -1)      sep = strrchr (p, '\\');
1200          return WPTERR_WINSOCK_SOCKET;      if (sep != NULL)
1201      hp = gethostbyname (skip_type_prefix (host));          p[(sep-p)] = 0;
1202      if (!hp) {  
1203          closesocket (fd);      _snprintf (ksprg, n, "%s\\gpgkeys_ldap.exe", p);
1204          return WPTERR_WINSOCK_RESOLVE;      free_if_alloc (p);
1205      }      if (file_exist_check (ksprg)) {
1206            log_box ("LDAP Keyserver Plugin", MB_ERR,
1207      memset (&saddr, 0, sizeof (saddr));                   "%s: could not find LDAP keyserver module!", ksprg);
1208      saddr.sin_family = AF_INET;          rc = -1;
1209      saddr.sin_port = htons (FINGER_PORT);          goto leave;
1210      saddr.sin_addr = *(struct in_addr *)hp->h_addr;      }
1211      if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {      get_temp_name (outf, sizeof (outf)-1, keyid);
1212          closesocket (fd);      get_temp_name (inf, sizeof (inf)-1, NULL);
1213          return WPTERR_WINSOCK_CONNECT;      fp = fopen (inf, "w+b");
1214      }      if (!fp) {
1215      send (fd, user, strlen (user), 0);          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", inf,
1216      send (fd, "\r\n", 2, 0);                   winpt_strerror (WPTERR_FILE_OPEN));
1217            rc = -1;
1218      memset (key, 0, maxkeylen);          goto leave;
1219      while (maxkeylen > 0) {      }
1220          nread = finger_readline (fd, buf, sizeof (buf)-1);      fprintf (fp,
1221          if (nread <= 0)          "VERSION 1\n"
1222              break;          "PROGRAM 1.4.3-cvs\n"
1223          strcat (buf, "\n");          "SCHEME ldap\n"
1224          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {          "HOST %s\n"
1225              strcat (key, buf);          "COMMAND GET\n"
1226              start_key = 1;          "\n"
1227              maxkeylen -= nread;          "%s\n",
1228          }          host? skip_type_prefix (host): "64.94.85.200", keyid);
1229          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {      fclose (fp);
1230              strcat (key, buf);  
1231              start_key--;      p = new char[strlen (ksprg) + strlen (inf) + strlen (outf) + 32];
1232              maxkeylen -= nread;      if (!p)
1233              break;          BUG (NULL);
1234          }      sprintf (p, "%s -o %s %s", ksprg, outf, inf);
1235          else if (start_key) {      if (spawn_application (p)) {
1236              strcat (key, buf);          rc = -1;
1237              maxkeylen -= nread;          goto leave;
1238          }      }
1239      }  
1240      closesocket (fd);      fp = fopen (outf, "rb");
1241      if (start_key != 0)      if (!fp) {
1242          rc = WPTERR_WINSOCK_RECVKEY;          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,
1243      return rc;                   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.13  
changed lines
  Added in v.181

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26