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

Diff of /trunk/Src/wptKeyserver.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26