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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26