/[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 193 by twoaday, Sat Apr 1 12:36:35 2006 UTC revision 290 by twoaday, Sat Mar 10 11:18:34 2007 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-2007 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.
# Line 13  Line 13 
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.
  *  
  * You should have received a copy of the GNU General Public License  
  * along with WinPT; if not, write to the Free Software Foundation,  
  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  
16   */   */
   
17  #ifdef HAVE_CONFIG_H  #ifdef HAVE_CONFIG_H
18  #include <config.h>  #include <config.h>
19  #endif  #endif
# Line 29  Line 24 
24  #include <sys/stat.h>  #include <sys/stat.h>
25  #include <ctype.h>  #include <ctype.h>
26    
27    #include "wptGPG.h"
28  #include "wptKeyserver.h"  #include "wptKeyserver.h"
29  #include "wptErrors.h"  #include "wptErrors.h"
30  #include "wptTypes.h"  #include "wptTypes.h"
31  #include "wptNLS.h"  #include "wptNLS.h"
32  #include "wptW32API.h"  #include "wptW32API.h"
 #include "wptGPG.h"  
33  #include "wptRegistry.h"  #include "wptRegistry.h"
34    #include "wptUTF8.h"
35    #include "wptVersion.h"
36    #include "StringBuffer.h"
37    
38    
39  /* just map net_errno to a winsock error. */  /* Map net_errno to a winsock error. */
40  #define net_errno ((int)WSAGetLastError ())  #define net_errno ((int)WSAGetLastError ())
41    
42    
43  keyserver server[MAX_KEYSERVERS] = {0};  keyserver server[MAX_KEYSERVERS] = {0};
44  keyserver_proxy_s proxy = {0};  keyserver_proxy_s proxy = {0};
45  static const char *server_list[] = {  static const char *server_list[] = {
     "hkp://gnv.us.ks.cryptnet.net",  
     "hkp://keyserver.kjsl.com",  
46      "hkp://sks.keyserver.penguin.de",      "hkp://sks.keyserver.penguin.de",
47      "hkp://subkeys.pgp.net",      "hkp://subkeys.pgp.net",
48      "ldap://keyserver.pgp.com",      "ldap://keyserver.pgp.com",
# Line 60  static int   hkp_err = 0;      /* != 0 indica Line 57  static int   hkp_err = 0;      /* != 0 indica
57  char *default_keyserver = NULL;  char *default_keyserver = NULL;
58  WORD default_keyserver_port = 0;  WORD default_keyserver_port = 0;
59    
60  /* Default socket timeout. */  /* Default socket timeout (secs). */
61  static int default_socket_timeout = 10;  static size_t default_socket_timeout = 6;
62    
63    
64    /* Wrapper for safe memory allocation. */
65    static char*
66    safe_alloc (DWORD n)
67    {
68        char *p;
69    
70        p = new char[n+1];
71        if (!p)
72            BUG (0);
73        memset (p, 0, n);
74        return p;
75    }
76    
77  /* Basic64 encode the input @inbuf to @outbuf. */  /* Basic64 encode the input @inbuf to @outbuf. */
78  static void  static void
# Line 70  base64_encode (const char *inbuf, char * Line 81  base64_encode (const char *inbuf, char *
81      char base64code[] =      char base64code[] =
82          "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";          "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
83      int index = 0, temp = 0, res = 0;      int index = 0, temp = 0, res = 0;
84      int i = 0, inputlen = 0, len = 0;      int i, inputlen, len = 0;
85            
86      inputlen = strlen (inbuf);      inputlen = strlen (inbuf);
87      for (i = 0; i < inputlen; i++) {      for (i = 0; i < inputlen; i++) {
# Line 108  base64_encode (const char *inbuf, char * Line 119  base64_encode (const char *inbuf, char *
119  }  }
120    
121    
122    /* Check that the given buffer contains a valid keyserver URL
123       and return the prefix length, 0 in case of an error. */
124    static int
125    check_URL (const char *buf)
126    {
127        const char *proto[] = {
128            "ldap://",
129            "http://",
130            "finger://",
131            "hkp://",
132            NULL};
133        int i;
134    
135        if (strlen (buf) < 7)
136            return 0;
137    
138        for (i=0; proto[i] != NULL; i++) {
139            if (strstr (buf, proto[i]))
140                return strlen (proto[i]);
141        }
142        return 0;
143    }
144    
145    
146  /* Skip the URL schema and return only the host part of it. */  /* Skip the URL schema and return only the host part of it. */
147  static const char*  static const char*
148  skip_type_prefix (const char *hostname)  skip_type_prefix (const char *hostname)
149  {  {
150      if (hostname && !strncmp (hostname, "http://", 7))      int pos;
151          hostname += 7;  
152      else if (hostname && !strncmp (hostname, "hkp://", 6))      if (!hostname)
153          hostname += 6;          return hostname;
154      else if (hostname && !strncmp (hostname, "finger://", 9))  
155          hostname += 9;      pos = check_URL (hostname);
156      else if (hostname && !strncmp (hostname, "ldap://", 7))      if (pos > 0)
157          hostname += 7;          hostname += pos;
158      return hostname;      return hostname;
159  }  }
160    
161    /* Parse the keyserver response and extract the human
162       readable text passages. */
163    static int
164    parse_keyserver_error (const char *resp, char *txt, size_t txtlen)
165    {
166        char *p, *p2;
167    
168        /* If we find no 'Error' substring, we assume a success. */
169        if (!stristr (resp, "Error"))
170            return -1;
171    
172        memset (txt, 0, txtlen);
173        p = strstr (resp, "\r\n\r\n");
174        if (!p)
175            return -1;
176        resp += (p-resp);
177        p = strstr (resp, "<h1>");
178        if (!p)
179            return -1;
180        resp += (p-resp)+strlen ("<h1>");
181        p = strstr (resp, "</h1>");
182        if (!p)
183            return -1;
184        resp += (p-resp)+strlen ("</h1>");
185        p2 = strstr (resp, "</body>");
186        if (p2 != NULL)
187            memcpy (txt, resp, (p2-resp));
188        else {
189            if (!strnicmp (resp, "<p>", 3))
190                resp += 3;
191            while (resp && *resp == '\r' || *resp == '\n')
192                resp++;
193            memcpy (txt, resp, strlen (resp));
194        }
195        return 0;
196    }
197    
198    
199  /* Check that the keyserver response indicates an OK.  /* Check that the keyserver response indicates an OK.
200     Return 0 on success. */     Return 0 on success. */
201  static int  static int
202  check_hkp_response (const char *resp, int recv)  check_hkp_response (const char *resp, int recv)
203  {      {
204      char *p, *end;      int ec;
     int ec, len;  
205    
206        log_debug ("check_hkp_response: '%s'\r\n", resp);
207      ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;      ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;
208      if (!strstr (resp, "HTTP/1.0 200 OK") &&      if (!strstr (resp, "HTTP/1.0 200 OK") &&
209          !strstr (resp, "HTTP/1.1 200 OK")) /* http error */          !strstr (resp, "HTTP/1.1 200 OK") &&
210          return ec;          !strstr (resp, "HTTP/1.0 500 OK") &&
211      if (strstr (resp, "Public Key Server -- Error")          !strstr (resp, "HTTP/1.1 500 OK"))
212          || strstr (resp, "Public Key Server -- Error")          return ec; /* http error */
213          || strstr (resp, "No matching keys in database")) {  
214          p = strstr (resp, "<p>");      if (!parse_keyserver_error (resp, hkp_errmsg, DIM (hkp_errmsg)-2)) {
215          if (p && strlen (p) < sizeof (hkp_errmsg)) {          if (!strlen (hkp_errmsg))
216              end = strstr (p, "</p>");              _snprintf (hkp_errmsg, DIM (hkp_errmsg)-1,
217              len = end? (end - p + 1) : strlen (p);                          "Unknown keyserver error");
218              memset (hkp_errmsg, 0, sizeof (hkp_errmsg));          hkp_err = 1;
             strncpy (hkp_errmsg, p, len);  
             hkp_err = 1;  
         }  
219          return ec;          return ec;
220      }      }
221      return 0;      return 0;
# Line 206  sock_select (int fd, int nsecs) Line 275  sock_select (int fd, int nsecs)
275     returned in @nbytes.     returned in @nbytes.
276     Return value: 0 on success. */     Return value: 0 on success. */
277  static int  static int
278  sock_read (int fd, char *buf, int buflen, int *nbytes)  sock_read (int fd, char *buf, size_t buflen, int *nbytes)
279  {  {
280      DWORD nread;      int nread;
281      int nleft = buflen;      size_t nleft = buflen;
282      int rc, n = 0;      size_t n = 0;
283        int rc;
284        
285        if (nbytes)
286            *nbytes = 0;
287      while (nleft > 0) {      while (nleft > 0) {
288          if (n >= default_socket_timeout)          if (n >= default_socket_timeout)
289              return WPTERR_WINSOCK_TIMEOUT;              return WPTERR_WINSOCK_TIMEOUT;
# Line 238  sock_read (int fd, char *buf, int buflen Line 310  sock_read (int fd, char *buf, int buflen
310      return 0;      return 0;
311  }  }
312    
313    
314    /* Helper to create a string from the gpgme data and
315       then release the gpgme data object. */
316    char*
317    data_release_and_get_mem (gpgme_data_t in, size_t *r_bufferlen)
318    {
319        size_t n;
320        char *buffer, *p;
321    
322        gpg_data_putc (in, '\0');
323        p = gpgme_data_release_and_get_mem (in, &n);
324        buffer = m_strdup (p);
325        if (r_bufferlen)
326            *r_bufferlen = n;
327        gpgme_free (p);
328        return buffer;
329    }
330    
331    
332  /* Read much data as possible from the socket @fd and  /* Read much data as possible from the socket @fd and
333     return the data in @buffer. Caller must free data.     return the data in @buffer. Caller must free data.
334     Return value: 0 on success. */     Return value: 0 on success. */
335  int  int
336  sock_read_ext (int fd, char **buffer, int *r_bufferlen)  sock_read_ext (int fd, char **buffer, size_t *r_bufferlen)
337  {  {
338      gpgme_data_t dh;      gpgme_data_t dh;
339      char buf[1024], *p;      char buf[1024];
340      size_t n=0;      size_t timeout=0;
341      int nread, rc;      int nread, rc;
342    
343      gpgme_data_new (&dh);      if (gpgme_data_new (&dh))
344      while (n < 10) {          return SOCKET_ERROR;
345        while (timeout < default_socket_timeout) {
346          rc = sock_select (fd, 1);          rc = sock_select (fd, 1);
347          if (rc == SOCKET_ERROR) {          if (rc == SOCKET_ERROR) {
348              gpgme_data_release (dh);              gpgme_data_release (dh);
349              return rc;              return rc;
350          }          }
351          else if (!rc)          else if (!rc)
352              n++;              timeout++; /* socket not ready yet. */
353          else {          else {
354              nread = recv (fd, buf, sizeof (buf), 0);              nread = recv (fd, buf, DIM (buf), 0);
355              if (nread == SOCKET_ERROR)              if (nread == SOCKET_ERROR)
356                  return SOCKET_ERROR;                  return SOCKET_ERROR;
357              else if (!nread)              else if (!nread)
# Line 267  sock_read_ext (int fd, char **buffer, in Line 359  sock_read_ext (int fd, char **buffer, in
359              gpgme_data_write (dh, buf, nread);              gpgme_data_write (dh, buf, nread);
360          }          }
361      }      }
362      gpg_data_putc (dh, '\0');      if (timeout >= default_socket_timeout)
363      p = gpgme_data_release_and_get_mem (dh, &n);          return WPTERR_WINSOCK_TIMEOUT;
364      *buffer = m_strdup (p);      *buffer = data_release_and_get_mem (dh, r_bufferlen);
     if (r_bufferlen)  
         *r_bufferlen = n;  
     gpgme_free (p);  
365      return 0;      return 0;
366  }  }
367    
368    
369  /* Write the buffer @buf with the length @buflen to a socket @fd. */  /* Write the buffer @buf with the length @buflen to a socket @fd. */
370  static int  static int
371  sock_write (int fd, const char *buf, int buflen)  sock_write (int fd, const char *buf, size_t buflen)
372  {  {
373      DWORD nwritten;      int nwritten;
374      int nleft = buflen;      int nleft = buflen;
375    
376      while (nleft > 0) {      while (nleft > 0) {
# Line 319  wsock_end (void) Line 408  wsock_end (void)
408      char *p;      char *p;
409      int i;      int i;
410    
411    #ifdef WINPT_MOBILE
412        p = m_strdup ("keyserver.conf");
413    #else
414      p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);      p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);
415    #endif
416      kserver_save_conf (p);      kserver_save_conf (p);
417      free_if_alloc (p);      free_if_alloc (p);
418      free_if_alloc (default_keyserver);      free_if_alloc (default_keyserver);
419      for (i=0; i < MAX_KEYSERVERS; i++) {      for (i=0; i < MAX_KEYSERVERS; i++) {
420          if (server[i].used && server[i].name != NULL)          if (server[i].name != NULL)
421              free_if_alloc (server[i].name);              free_if_alloc (server[i].name);
422      }      }
423      kserver_proxy_release (&proxy);      kserver_proxy_release (&proxy);
424      WSACleanup ();      WSACleanup ();
425        log_debug ("wsock_end: cleanup finished.\r\n");
426  }  }
427    
428    
429  /* Return a string representation of a winsock error. */  /* Return a string representation of a winsock error. */
430  const char*  const char*
431  wsock_strerror (void)  wsock_strerror (void)
432  {      {
     static char buf[384];  
433      int ec = WSAGetLastError ();      int ec = WSAGetLastError ();
434            
435        if (!ec)
436            return "";
437      switch (ec) {      switch (ec) {
438      case WSAENETDOWN:      case WSAENETDOWN:
439          return _("The network subsystem has failed");          return _("Network unreachable");
440    
441        case WSAEHOSTUNREACH:
442            return _("Host unreachable");
443    
444      case WSAHOST_NOT_FOUND:      case WSAHOST_NOT_FOUND:
445          return _("Authoritative Answer Host not found");          return _("Could not resolve host name");
446    
447        case WSAECONNREFUSED:
448            return _("Connection refused");
449    
450      case WSAETIMEDOUT:      case WSAETIMEDOUT:
451          return _("The connection has been dropped because of a network failure");      case WSAECONNABORTED:
452            return _("Connection timeout");
453    
454        case WSAENETRESET:
455        case WSAECONNRESET:    
456            return _("Connection resetted by peer");
457    
458        case WSAESHUTDOWN:
459            return _("Socket has been shutdown");
460    
461      default:      default:
462          _snprintf (buf, sizeof (buf) -1, _("Unknown Winsock error ec=%d"),ec);          break;
         return buf;  
463      }      }
464      return NULL;  
465        return "";
466  }  }
467    
468    
469  /* Set default socket timeout for all reading operations. */  /* Set default socket timeout for all reading operations. */
470  void  void
471  kserver_set_socket_timeout (int nsec)  kserver_set_socket_timeout (size_t nsec)
472  {  {
473      if (nsec < 0)      if (nsec < 0 || nsec > 3600)
474          nsec = 0;          nsec = 0;
475      default_socket_timeout = nsec;      default_socket_timeout = nsec;
476  }  }
# Line 383  kserver_get_hostname (int idx, int type, Line 495  kserver_get_hostname (int idx, int type,
495          *port = default_keyserver_port;          *port = default_keyserver_port;
496          return default_keyserver;          return default_keyserver;
497      }      }
498      else if (!type && idx < DIM (server_list)) {      else if (!type && (size_t)idx < DIM (server_list)) {
499            /* XXX: handle non HKP servers. */
500          *port = HKP_PORT;          *port = HKP_PORT;
501          return server_list[idx];          return server_list[idx];
502      }      }
# Line 402  kserver_check_inet_connection (void) Line 515  kserver_check_inet_connection (void)
515          closesocket (fd);          closesocket (fd);
516          return 0;          return 0;
517      }      }
518        log_debug ("kserver_check_inet_connection: no inet connection.\r\n");
519      return -1;      return -1;
520  }  }
521    
# Line 413  kserver_check_inet_connection (void) Line 527  kserver_check_inet_connection (void)
527  const char*  const char*
528  kserver_check_keyid (const char *keyid)  kserver_check_keyid (const char *keyid)
529  {        {      
530      static char id[21];      static char id[22];
531    
532      if (strstr (keyid, "@"))      if (strstr (keyid, "@"))
533          return keyid; /* email address */          return keyid; /* email address */
534      if (strncmp (keyid, "0x", 2)) {      if (strncmp (keyid, "0x", 2)) {
535          memset (&id, 0, sizeof (id));          memset (&id, 0, sizeof (id));
536          _snprintf (id, sizeof (id)-1, "0x%s", keyid);          _snprintf (id, DIM (id)-1, "0x%s", keyid);
537          return id;          return id;
538      }      }
539      return keyid;      return keyid;
# Line 435  update_proxy_user (const char *proxy_use Line 549  update_proxy_user (const char *proxy_use
549    
550      n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;      n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;
551      free_if_alloc (proxy.base64_user);      free_if_alloc (proxy.base64_user);
552      proxy.base64_user = new char[n];      proxy.base64_user = safe_alloc (n+1);
553      if (!proxy.base64_user)      _snprintf (t, DIM (t)-1, "%s:%s", proxy_user, proxy_pass);
         BUG (0);  
     _snprintf (t, sizeof (t)-1, "%s:%s", proxy_user, proxy_pass);  
554      base64_encode (t, proxy.base64_user);      base64_encode (t, proxy.base64_user);
555      free_if_alloc (proxy.user);      free_if_alloc (proxy.user);
556      free_if_alloc (proxy.pass);      free_if_alloc (proxy.pass);
557      proxy.user = m_strdup (proxy_user);      proxy.user = m_strdup (proxy_user);
558      proxy.pass = m_strdup (proxy_pass);      proxy.pass = m_strdup (proxy_pass);
559  }  }
   
   
 /* Check that the given buffer contains a valid keyserver URL. */  
 static int  
 check_URL (const char * buf)  
 {  
     if (strlen (buf) < 7)  
         return -1;  
     if (!strstr (buf, "ldap://")  
         && !strstr (buf, "http://")  
         && !strstr (buf, "finger://")  
         && !strstr (buf, "hkp://"))  
         return -1;  
     return 0;  
 }  
560            
561    
562  /* Get the port number from the given protocol. */  /* Get the port number from the given protocol. */
# Line 467  static int Line 564  static int
564  port_from_proto (int proto)  port_from_proto (int proto)
565  {  {
566      switch (proto) {      switch (proto) {
567      case KSPROTO_LDAP: return 0;      case KSPROTO_LDAP:   return LDAP_PORT;
568      case KSPROTO_FINGER: return FINGER_PORT;      case KSPROTO_FINGER: return FINGER_PORT;
569      case KSPROTO_HTTP: return HKP_PORT;      case KSPROTO_HTTP:   return HKP_PORT;
570      }      }
571      return 0;      return 0;
572  }  }
# Line 479  port_from_proto (int proto) Line 576  port_from_proto (int proto)
576  static int  static int
577  proto_from_URL (const char *buf)  proto_from_URL (const char *buf)
578  {  {
579      if (strstr( buf, "ldap"))      if (strstr (buf, "ldap"))
580          return KSPROTO_LDAP;          return KSPROTO_LDAP;
581      else if (strstr( buf, "finger"))      else if (strstr (buf, "finger"))
582          return KSPROTO_FINGER;          return KSPROTO_FINGER;
583      return KSPROTO_HKP;      return KSPROTO_HKP;
584  }  }
585    
586    
587    /* Set the default keyserver.
588       If @hostname is NULL, use the predefined keyserver. */
589  void  void
590  keyserver_set_default (const char *hostname, WORD port)  keyserver_set_default (const char *hostname, WORD port)
591  {  {
592        if (!port)
593            port = HKP_PORT;
594      if (hostname != NULL) {      if (hostname != NULL) {
595          free_if_alloc (default_keyserver);          free_if_alloc (default_keyserver);
596          default_keyserver = m_strdup (hostname);          default_keyserver = m_strdup (hostname);
         if (!default_keyserver)  
             BUG (0);  
597          default_keyserver_port = port;          default_keyserver_port = port;
598      }      }
599      if (!port)      if (!default_keyserver) {
         port = HKP_PORT;  
     if (!default_keyserver)  
600          default_keyserver = m_strdup (DEF_HKP_KEYSERVER);          default_keyserver = m_strdup (DEF_HKP_KEYSERVER);
601            default_keyserver_port = HKP_PORT;
602        }
603      server[0].name =  m_strdup (default_keyserver);      server[0].name =  m_strdup (default_keyserver);
604      server[0].used = 1;      server[0].used = 1;
605      server[0].port = port;      server[0].port = port;
# Line 552  kserver_save_conf (const char *conf) Line 651  kserver_save_conf (const char *conf)
651  }  }
652    
653    
654    /* Return the specified keyserver config setting @key as an integer. */
655    static int
656    get_conf_kserver_int (const char *key)
657    {
658        char *p;
659        int val = 0;
660    
661        p = get_reg_entry_keyserver (key);
662        if (p && *p)
663            val = atoi (p);
664        free_if_alloc (p);
665        return val;
666    }
667    
668    
669    /* Read the proxy configuration and store it into @prox. */
670    static void
671    read_proxy_config (keyserver_proxy_t prox)
672    {
673        char *proto;
674    
675        if (!prox)
676            return;
677        
678        proto = get_reg_entry_keyserver("Proto");
679        if (proto != NULL && strlen (proto) > 0)
680            prox->proto = atoi (proto);
681        else
682            prox->proto = PROXY_PROTO_NONE;
683        free_if_alloc (proto);
684        free_if_alloc (prox->host);
685        prox->host = get_reg_entry_keyserver ("Host");
686        free_if_alloc (prox->user);
687        prox->user = get_reg_entry_keyserver ("User");
688        free_if_alloc (prox->pass);
689        prox->pass = get_reg_entry_keyserver ("Pass");
690        prox->port = get_conf_kserver_int ("Port");
691    }
692    
693    
694  /* Load the keyserver config file @conf. */  /* Load the keyserver config file @conf. */
695  int  int
696  kserver_load_conf (const char *conf)  kserver_load_conf (const char *conf)
# Line 559  kserver_load_conf (const char *conf) Line 698  kserver_load_conf (const char *conf)
698      FILE *fp;      FILE *fp;
699      char buf[1024], *s, *p;      char buf[1024], *s, *p;
700      char *user = NULL, *pass = NULL;          char *user = NULL, *pass = NULL;    
701      int no_config=0, chk_pos=0;      int no_config=0, chk_pos;
702      int pos;      int pos;
703            
704      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {      for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
705          server[pos].used = 0;          server[pos].used = 0;
706          server[pos].port = HKP_PORT;          server[pos].port = HKP_PORT;
707            server[pos].name = NULL;
708      }      }
709            
710      fp = fopen (conf, "rb");      fp = fopen (conf, "rb");
# Line 574  kserver_load_conf (const char *conf) Line 714  kserver_load_conf (const char *conf)
714              server[pos].name = m_strdup (server_list[pos]);              server[pos].name = m_strdup (server_list[pos]);
715              server[pos].proto = proto_from_URL (server_list[pos]);              server[pos].proto = proto_from_URL (server_list[pos]);
716          }          }
717          no_config=1;          no_config = 1;
718      }      }
719      get_reg_proxy_prefs (&proxy);      read_proxy_config (&proxy);
720      if (user && pass)      if (user && pass)
721          update_proxy_user (user, pass);          update_proxy_user (user, pass);
722      else if (user && !pass || !user && pass) {      else if (user && !pass || !user && pass) {
723          msg_box (NULL, _("Invalid proxy configuration."          msg_box (NULL, _("Invalid proxy configuration. "
724                           "You need to set a user and a password"                           "You need to set a user and a password "
725                           "to use proxy authentication!"),                           "to use proxy authentication!"),
726                           _("Proxy Error"), MB_ERR);                           _("Proxy Error"), MB_ERR);
727      }      }
728      /* check if the host has a http:// prefix and skip it */      /* check if the host has a http:// prefix and skip it */
729      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {      if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
730          char *host = m_strdup (proxy.host+7);          char *host = m_strdup (proxy.host+7);
         if (!host)  
             BUG (0);  
731          free_if_alloc (proxy.host);          free_if_alloc (proxy.host);
732          proxy.host = host;          proxy.host = host;
733      }      }
# Line 598  kserver_load_conf (const char *conf) Line 736  kserver_load_conf (const char *conf)
736            
737      pos = 0;      pos = 0;
738      while (fp && !feof (fp)) {      while (fp && !feof (fp)) {
739          s = fgets (buf, sizeof (buf)-1, fp);          s = fgets (buf, DIM (buf)-1, fp);
740          if (!s)          if (!s)
741              break;              break;
742          if (strstr (buf, "\r\n"))          if (strstr (buf, "\r\n"))
# Line 608  kserver_load_conf (const char *conf) Line 746  kserver_load_conf (const char *conf)
746          s = (char *)skip_whitespace (buf);          s = (char *)skip_whitespace (buf);
747          if (*s == '#' || strlen (s) < 7)          if (*s == '#' || strlen (s) < 7)
748              continue;              continue;
749          if (check_URL (s)) {          chk_pos = check_URL (s);
750            if (!chk_pos) {
751              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"              msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
752                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),                               "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
753                               _("Keyserver Error"), MB_ERR);                               _("Keyserver Error"), MB_ERR);
754              continue;              continue;
755          }          }
         chk_pos = 6;  
         if (strstr (s, "finger"))  
             chk_pos = 10;  
756          p = strchr (s+chk_pos, ':');          p = strchr (s+chk_pos, ':');
757          server[pos].used = 1;          server[pos].used = 1;
758          server[pos].proto = proto_from_URL (s);          server[pos].proto = proto_from_URL (s);
# Line 627  kserver_load_conf (const char *conf) Line 763  kserver_load_conf (const char *conf)
763              server[pos].port = atol (p+1);              server[pos].port = atol (p+1);
764              if (server[pos].port < 0 || server[pos].port > 65536)              if (server[pos].port < 0 || server[pos].port > 65536)
765                  server[pos].port = HKP_PORT;                  server[pos].port = HKP_PORT;
766              server[pos].name = new char [(p-s)+2];              server[pos].name = safe_alloc ((p-s)+2);
             if (!server[pos].name)  
                 BUG (0);  
767              memset (server[pos].name, 0, (p-s)+2);              memset (server[pos].name, 0, (p-s)+2);
768              memcpy (server[pos].name, s, (p-s));              memcpy (server[pos].name, s, (p-s));
769          }          }
# Line 643  kserver_load_conf (const char *conf) Line 777  kserver_load_conf (const char *conf)
777      if (fp)      if (fp)
778          fclose (fp);          fclose (fp);
779      if (!pos) {      if (!pos) {
780          /* only issue an error if the config file exist but          /* Only issue an error if the config file exist but
781             it has no valid entries. */             it has no valid entries. */
782          keyserver_set_default (NULL, HKP_PORT);          keyserver_set_default (NULL, HKP_PORT);
783          if (!no_config)          if (!no_config)
# Line 658  kserver_load_conf (const char *conf) Line 792  kserver_load_conf (const char *conf)
792     Return value: 0 on success */     Return value: 0 on success */
793  int  int
794  kserver_connect (const char *hostname, WORD port, int *conn_fd)  kserver_connect (const char *hostname, WORD port, int *conn_fd)
795  {  {        
     int rc, fd;  
     DWORD iaddr;  
     char host[128] = {0};  
796      struct hostent *hp;      struct hostent *hp;
797      struct sockaddr_in sock;      struct sockaddr_in sock;
798        char host[128] = {0};
799      log_debug ("kserver_connect: %s:%d\r\n", hostname, port);      DWORD iaddr;
800        bool use_proxy = proxy.host != NULL;
801        int rc, fd;
802    
803      if (!port)      if (!port)
804          port = HKP_PORT;          port = HKP_PORT;
805      if (conn_fd)      if (conn_fd)
806          *conn_fd = 0;          *conn_fd = 0;
807      hostname = skip_type_prefix (hostname);      hostname = skip_type_prefix (hostname);
808        log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
809            
810        if (use_proxy && proxy.proto == PROXY_PROTO_HTTP)
811            port = proxy.port;
812      memset (&sock, 0, sizeof (sock));      memset (&sock, 0, sizeof (sock));
813      sock.sin_family = AF_INET;      sock.sin_family = AF_INET;
814      sock.sin_port = proxy.host? htons (proxy.port) : htons (port);      sock.sin_port = htons (port);
815      if (proxy.host)      strncpy (host, use_proxy? proxy.host : hostname, DIM (host)-1);
816          strncpy (host, proxy.host, 127);  
     else  
         strncpy (host, hostname, 127);  
       
817      if ((iaddr = inet_addr (host)) != INADDR_NONE)      if ((iaddr = inet_addr (host)) != INADDR_NONE)
818          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));          memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
819      else if ((hp = gethostbyname (host))) {      else if ((hp = gethostbyname (host))) {
# Line 692  kserver_connect (const char *hostname, W Line 825  kserver_connect (const char *hostname, W
825      }      }
826      else {      else {
827          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);          log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
828          return WPTERR_WINSOCK_RESOLVE;          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_RESOLVE;
829      }      }
830      fd = socket (AF_INET, SOCK_STREAM, 0);      fd = socket (AF_INET, SOCK_STREAM, 0);
831      if (fd == INVALID_SOCKET)        if (fd == INVALID_SOCKET)  
# Line 701  kserver_connect (const char *hostname, W Line 834  kserver_connect (const char *hostname, W
834      if (rc == SOCKET_ERROR) {      if (rc == SOCKET_ERROR) {
835          log_debug ("connect: failed ec=%d.\r\n", net_errno);          log_debug ("connect: failed ec=%d.\r\n", net_errno);
836          closesocket (fd);          closesocket (fd);
837          return WPTERR_WINSOCK_CONNECT;          return use_proxy? WPTERR_WINSOCK_PROXY : WPTERR_WINSOCK_CONNECT;
838      }      }
839    
840      if (proxy.proto == PROXY_PROTO_SOCKS5) {      if (proxy.proto == PROXY_PROTO_SOCKS5) {
841            /* XXX: finish code and provide errors constants. */
842          rc = socks_handshake (&proxy, fd, hostname, port);          rc = socks_handshake (&proxy, fd, hostname, port);
843          if (rc) {          if (rc) {
844              closesocket (fd);              closesocket (fd);
845              return WPTERR_GENERAL; /* XXX: use better code. */              return WPTERR_GENERAL;
846          }          }
847      }      }
848    
# Line 719  kserver_connect (const char *hostname, W Line 853  kserver_connect (const char *hostname, W
853  }  }
854    
855    
856    /* Check if the URL needs to be encoded or not. */
857  static bool  static bool
858  URL_must_encoded (const char *url)  URL_must_encoded (const char *url)
859  {  {
# Line 730  URL_must_encoded (const char *url) Line 865  URL_must_encoded (const char *url)
865    
866  /* Perform URL encoding of the given data. */  /* Perform URL encoding of the given data. */
867  static char*  static char*
868  URL_encode (const char *url, size_t ulen, size_t *ret_nlen)  URL_encode (const char *url, DWORD ulen, DWORD *ret_nlen)
869  {  {
870      gpgme_data_t hd;      gpgme_data_t hd;
871      char numbuf[5], *pp, *p;      char numbuf[5], *p;
872      size_t i, n;      size_t i, nlen;
873    
874      gpgme_data_new (&hd);      if (gpgme_data_new (&hd))
875            BUG (0);
876      for (i=0; i < ulen; i++) {      for (i=0; i < ulen; i++) {
877          if (isalnum (url[i]) || url[i] == '-')          if (isalnum (url[i]) || url[i] == '-')
878              gpg_data_putc (hd, url[i]);              gpg_data_putc (hd, url[i]);
# Line 747  URL_encode (const char *url, size_t ulen Line 883  URL_encode (const char *url, size_t ulen
883              gpgme_data_write (hd, numbuf, strlen (numbuf));              gpgme_data_write (hd, numbuf, strlen (numbuf));
884          }          }
885      }      }
     gpg_data_putc (hd, '\0');  
886    
887      /* Copy memory to avoid that we need to use gpgme_free later. */      p = data_release_and_get_mem (hd, &nlen);
     pp = gpgme_data_release_and_get_mem (hd, &n);  
     p = m_strdup (pp);  
     gpgme_free (pp);  
888      if (ret_nlen)      if (ret_nlen)
889          *ret_nlen = n;          *ret_nlen = nlen;
890      return p;      return p;
891  }  }
892    
# Line 762  URL_encode (const char *url, size_t ulen Line 894  URL_encode (const char *url, size_t ulen
894  /* Format a request for the given keyid (send). */  /* Format a request for the given keyid (send). */
895  static char*  static char*
896  kserver_send_request (const char *hostname, WORD port,  kserver_send_request (const char *hostname, WORD port,
897                        const char *pubkey, int octets)                        const char *pubkey, DWORD octets)
898  {  {
899      char *request = NULL;      const char *fmt;
900      char *enc_pubkey = NULL;      char *request;
901      size_t enc_octets;      char *enc_pubkey;
902        DWORD enc_octets;
903      int reqlen;      int reqlen;
904    
905      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);      log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
906    
907      if (!port)      if (!port)
908          port = HKP_PORT;          port = HKP_PORT;
     reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);  
     request = new char[reqlen];  
     if (!request)  
         BUG (0);  
909      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);      enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
910      if (!enc_pubkey || !enc_octets) {      reqlen = 2*strlen (hostname) + 2*32/*port*/ + enc_octets + 32 /*len*/ + 1;
         free_if_alloc (request);  
         return NULL;  
     }  
911            
912      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {      if (proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
913          _snprintf (request, reqlen-1,          fmt = "POST http://%s:%d/pks/add HTTP/1.0\r\n"
914                     "POST http://%s:%d/pks/add HTTP/1.0\r\n"                "Referer: \r\n"
915                     "Referer: \r\n"                "User-Agent: WinPT/W32\r\n"
916                     "User-Agent: WinPT/W32\r\n"                "Host: %s:%d\r\n"
917                     "Host: %s:%d\r\n"                "Proxy-Authorization: Basic %s\r\n"
918                     "Proxy-Authorization: Basic %s\r\n"                "Content-type: application/x-www-form-urlencoded\r\n"
919                     "Content-type: application/x-www-form-urlencoded\r\n"                "Content-length: %d\r\n"
920                     "Content-length: %d\r\n"                "\r\n"
921                     "\r\n"                "keytext=%s"
922                     "keytext=%s"                "\r\n";
923                     "\n",          reqlen += strlen (fmt) + strlen (proxy.base64_user) + 1;
924                     skip_type_prefix (hostname), port, hostname, port,          request = safe_alloc (reqlen+1);
925            _snprintf (request, reqlen, fmt,
926                       skip_type_prefix (hostname), port, hostname, port,
927                     proxy.base64_user, enc_octets+9, enc_pubkey);                     proxy.base64_user, enc_octets+9, enc_pubkey);
928      }      }
929      else {      else {
930          _snprintf (request, reqlen-1,          fmt = "POST /pks/add HTTP/1.0\r\n"
931                     "POST /pks/add HTTP/1.0\r\n"                "Referer: \r\n"
932                     "Referer: \r\n"                "User-Agent: WinPT/W32\r\n"
933                     "User-Agent: WinPT/W32\r\n"                "Host: %s:%d\r\n"
934                     "Host: %s:%d\r\n"                "Content-type: application/x-www-form-urlencoded\r\n"
935                     "Content-type: application/x-www-form-urlencoded\r\n"                "Content-length: %d\r\n"
936                     "Content-length: %d\r\n"                "\r\n"
937                     "\r\n"                "keytext=%s"
938                     "keytext=%s"                "\r\n";
939                     "\n",          reqlen += strlen (fmt)+1;
940                     skip_type_prefix (hostname), port,          request = safe_alloc (reqlen+1);
941            _snprintf (request, reqlen, fmt,
942                       skip_type_prefix (hostname), port,
943                     enc_octets+9, enc_pubkey);                     enc_octets+9, enc_pubkey);
944      }      }
     free_if_alloc (enc_pubkey);  
945    
946      log_debug ("%s\r\n", request);      free_if_alloc (enc_pubkey);
947        log_debug ("request:\r\n%s\r\n", request);
948      return request;      return request;
949  }  }
950    
951    
952    /* Interface for receiving a public key. */
953  int  int
954  kserver_recvkey_ext (const char *hostname, WORD port, const char *keyid,  kserver_recvkey (const char *hostname, WORD port, const char *keyid,
955                       char **r_key, int *r_keylen)                   char **r_key, size_t *r_keylen)
956  {  {
957      char *request = NULL;      StringBuffer req;
958        const char *reqbuf;
959      int conn_fd;      int conn_fd;
960      int rc, n;      int rc;
961    
962      if (!port)      if (!port)
963          port = HKP_PORT;          port = HKP_PORT;
964      hkp_err = 0; /* reset */          hkp_err = 0; /* reset */
965      rc = kserver_connect (hostname, port, &conn_fd);      rc = kserver_connect (hostname, port, &conn_fd);
966      if (rc)      if (rc)
967          goto leave;          goto leave;
968        
     request = new char[300+1];  
     if (!request)  
         BUG (0);  
       
969      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
970          _snprintf (request, 300,          req = req + "GET http://" + skip_type_prefix (hostname) +
971              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"              ":" + port +
972              "Proxy-Authorization: Basic %s\r\n\r\n",              "/pks/lookup?op=get&search=" + keyid + " HTTP/1.0\r\n" +
973              skip_type_prefix (hostname), port, keyid, proxy.base64_user);              "Proxy-Authorization: Basic " + proxy.base64_user + "\r\n\r\n";
974      }      }
975      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
976          _snprintf (request, 300,          req = req + "GET http://" + skip_type_prefix (hostname) +
977              "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",              ":" + port + "/pks/lookup?op=get&search=" + keyid +
978              skip_type_prefix (hostname), port, keyid);              " HTTP/1.0\r\n\r\n";
     }      
     else {  
         _snprintf (request, 300,  
             "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);  
979      }      }
980        else
981      log_debug ("%s\r\n", request);          req = req + "GET /pks/lookup?op=get&search=" + keyid +
982                " HTTP/1.0\r\n\r\n";
983            
984      rc = sock_write (conn_fd, request, strlen (request));      log_debug ("req:\r\n%s\r\n", req.getBuffer ());
985    
986        reqbuf = req.getBuffer ();
987        rc = sock_write (conn_fd, reqbuf, strlen (reqbuf));
988      if (rc == SOCKET_ERROR) {      if (rc == SOCKET_ERROR) {
989          rc = WPTERR_WINSOCK_RECVKEY;          rc = WPTERR_WINSOCK_RECVKEY;
990          goto leave;          goto leave;
991      }      }
992            
993      rc = sock_read_ext (conn_fd, r_key, &n);      rc = sock_read_ext (conn_fd, r_key, r_keylen);
994      if (rc == SOCKET_ERROR) {      if (rc == SOCKET_ERROR) {
995          rc = WPTERR_WINSOCK_RECVKEY;          rc = WPTERR_WINSOCK_RECVKEY;
996          goto leave;          goto leave;
997      }      }
998    
999      if (r_keylen)      log_debug ("response:\r\n%s\r\n", *r_key);
         *r_keylen = n;  
     log_debug ("%s\r\n", *r_key);  
1000      rc = check_hkp_response (*r_key, 1);      rc = check_hkp_response (*r_key, 1);
1001      if (rc)      if (rc)
1002          goto leave;          goto leave;
# Line 879  kserver_recvkey_ext (const char *hostnam Line 1005  kserver_recvkey_ext (const char *hostnam
1005            
1006  leave:  leave:
1007      closesocket (conn_fd);      closesocket (conn_fd);
     free_if_alloc (request);  
1008      return rc;      return rc;
1009  }  }
1010    
 /* Interface for receiving a public key. */  
 int  
 kserver_recvkey (const char *hostname, WORD port, const char *keyid,  
                  char *key, int maxkeylen)  
 {  
     char *tmpkey;  
     int rc, nread=0;  
   
     /* XXX: just a wrapper around the new method, replace it  
             soon as possible. */  
     rc = kserver_recvkey_ext (hostname, port, keyid, &tmpkey, &nread);  
     if (rc)  
         return rc;  
   
     if (nread > maxkeylen) {  
         free_if_alloc (tmpkey);  
         return WPTERR_GENERAL;  
     }  
     strcpy (key, tmpkey);  
     free_if_alloc (tmpkey);  
     return 0;  
 }  
   
1011    
1012  /* Interface to send a public key. */  /* Interface to send a public key. */
1013  int  int
1014  kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )  kserver_sendkey (const char *hostname, WORD port,
1015                     const char *pubkey, size_t len)
1016  {  {
1017      char *request = NULL;      char *request = NULL;
1018      char log[2048];      char log[2048] = {0};
1019      int conn_fd, n;      int conn_fd, n;
1020      int rc;      int rc;
1021            
# Line 922  kserver_sendkey (const char *hostname, W Line 1025  kserver_sendkey (const char *hostname, W
1025          goto leave;          goto leave;
1026            
1027      request = kserver_send_request (hostname, port, pubkey, len);      request = kserver_send_request (hostname, port, pubkey, len);
     if (request == NULL) {  
         rc = WPTERR_GENERAL;  
         goto leave;      
     }  
       
1028      rc = sock_write (conn_fd, request, strlen (request));      rc = sock_write (conn_fd, request, strlen (request));
1029      if (rc == SOCKET_ERROR) {      if (rc == SOCKET_ERROR) {
1030          rc = WPTERR_WINSOCK_SENDKEY;          rc = WPTERR_WINSOCK_SENDKEY;
1031          goto leave;              goto leave;    
1032      }      }
1033            
1034      rc = sock_read (conn_fd, log, sizeof (log)-1, &n);      rc = sock_read (conn_fd, log, DIM (log)-1, &n);
1035      if (rc == SOCKET_ERROR) {      if (rc == SOCKET_ERROR) {
1036          rc = WPTERR_WINSOCK_SENDKEY;          rc = WPTERR_WINSOCK_SENDKEY;
1037          goto leave;          goto leave;
1038      }      }
1039    
1040      log_debug ("kserver_sendkey:\r\n%s\r\n", log);      log_debug ("kserver_sendkey: read %d bytes\r\n%s\r\n", n, log);
1041      rc = check_hkp_response (log, 0);      rc = check_hkp_response (log, 0);
1042      if (rc)      if (rc)
1043          goto leave;          goto leave;
1044            
1045      WSASetLastError (0);      WSASetLastError (0);
1046        
1047  leave:  leave:
1048      closesocket (conn_fd);      closesocket (conn_fd);
1049      free_if_alloc (request);      free_if_alloc (request);
# Line 961  kserver_search_chkresp (int fd) Line 1059  kserver_search_chkresp (int fd)
1059      int n=0;      int n=0;
1060            
1061      /* parse response 'HTTP/1.0 500 OK' */      /* parse response 'HTTP/1.0 500 OK' */
1062      if (sock_getline (fd, buf, 127, &n))      if (sock_getline (fd, buf, DIM (buf)-1, &n))
1063          return WPTERR_KEYSERVER_NOTFOUND;          return WPTERR_KEYSERVER_NOTFOUND;
1064    
1065      log_debug ("kserver_search_chkpresp: %s\r\n", buf);      log_debug ("kserver_search_chkpresp: %s\r\n", buf);
# Line 982  kserver_search_end (int conn_fd) Line 1080  kserver_search_end (int conn_fd)
1080  }  }
1081    
1082    
1083  /* Begin keyserver search procedure. */  /* Extract the amount of keys from the info record. */
1084    static size_t
1085    count_keys_in_response (char *buf)
1086    {
1087        char *p;
1088        int recno = 0;
1089        size_t n = 0;
1090    
1091        /* info:1:4 */
1092        if (strncmp (buf, "info", 4))
1093            return 0;
1094        p = strtok (buf, ":");
1095        while (p != NULL) {
1096            recno++;
1097            if (recno == 3)
1098                n = atoi (p);
1099            p = strtok (NULL, ":");
1100        }
1101        return n;
1102    }
1103    
1104    
1105    /* Start the keyserver search.
1106       Connect to host @hostname and port @port.
1107       The pattern are given in @pattern.
1108       The socket is returned in @conn_fd and @nkeys contains
1109       the amount of keys which were found. */
1110  int  int
1111  kserver_search_begin (const char *hostname, WORD port,  kserver_search_begin (const char *hostname, WORD port,
1112                        const char *pattern, int *conn_fd)                        const char *pattern, int *conn_fd, size_t *nkeys)
1113  {  {
1114      char *request = NULL;  
1115        StringBuffer req;
1116        const char *reqbuf;
1117      char *enc_patt = NULL;      char *enc_patt = NULL;
1118      int n;      char status[128];
1119      int rc, sock_fd;      int rc, sock_fd;
1120        int nread;
1121            
1122        *conn_fd = 0;
1123    
1124      rc = kserver_connect (hostname, port, &sock_fd);      rc = kserver_connect (hostname, port, &sock_fd);
1125      if (rc) {      if (rc)
         *conn_fd = 0;  
1126          goto leave;          goto leave;
     }  
1127    
1128      enc_patt = URL_encode (pattern, strlen (pattern), NULL);      enc_patt = URL_encode (pattern, strlen (pattern), NULL);
     n = 140 + strlen (enc_patt) + strlen (hostname) + 32 + 2;  
     if (proxy.base64_user)  
         n += strlen (proxy.base64_user) + 1;  
     request = new char[n+1];  
     if (!request)  
         BUG (0);  
       
1129      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {      if (proxy.host && proxy.user && proxy.proto == PROXY_PROTO_HTTP) {
1130          _snprintf (request, n,          req = req + "GET http://" + skip_type_prefix (hostname) + ":" + port +
1131              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"              "/pks/lookup?options=mr&op=index&search=" + enc_patt +
1132              "Proxy-Authorization: Basic %s\r\n\r\n",              " HTTP/1.0\r\n"
1133              skip_type_prefix (hostname), port, enc_patt, proxy.base64_user);              "Proxy-Authorization: Basic " + proxy.base64_user + "\r\n\r\n";
1134      }          }    
1135      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {      else if (proxy.host && proxy.proto == PROXY_PROTO_HTTP) {
1136          _snprintf (request, n,          req = req + "GET http://" + skip_type_prefix (hostname) + ":" + port +
1137              "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",              "/pks/lookup?options=mr&op=index&search=" + enc_patt +
1138              skip_type_prefix (hostname), port, enc_patt);              " HTTP/1.0\r\n\r\n";
1139      }      }
1140      else {      else {
1141          _snprintf (request, n,          req = req + "GET /pks/lookup?options=mr&op=index&search=" +
1142                     "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",              enc_patt + " HTTP/1.0\r\n\r\n";
                    enc_patt);  
1143      }      }
1144            
1145      log_debug ("kserver_search_begin:\r\n%s\r\n", request);      log_debug ("kserver_search_begin:\r\n%s\r\n", req.getBuffer ());
1146            reqbuf = req.getBuffer ();
1147      if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {      if (sock_write (sock_fd, reqbuf, strlen (reqbuf)) == SOCKET_ERROR) {
1148          rc = WPTERR_GENERAL;          rc = WPTERR_GENERAL;
1149          goto leave;          goto leave;
1150      }      }
# Line 1034  kserver_search_begin (const char *hostna Line 1153  kserver_search_begin (const char *hostna
1153      if (rc) {      if (rc) {
1154          closesocket (sock_fd);          closesocket (sock_fd);
1155          sock_fd = 0;          sock_fd = 0;
1156            goto leave;
1157        }
1158    
1159        /* Skip all lines until we reach the "info:" record. */
1160        for (;;) {
1161            if (sock_getline (sock_fd, status, DIM (status)-1, &nread)) {  
1162                log_debug ("kserver_search_begin: retrieving status line failed.\r\n");
1163                closesocket (sock_fd);
1164                sock_fd = 0;
1165                rc = WPTERR_GENERAL;
1166                break;
1167            }
1168            if (!strncmp (status, "info:", 5))
1169                break;
1170      }      }
1171    
1172        if (!rc)
1173            *nkeys = count_keys_in_response (status);
1174      *conn_fd = sock_fd;      *conn_fd = sock_fd;
1175            
1176  leave:  leave:
     free_if_alloc (request);  
1177      free_if_alloc (enc_patt);      free_if_alloc (enc_patt);
1178      return rc;      return rc;
1179  }  }
1180    
1181    
1182    /* Parse a single pub record returned by the keyserver. */
1183    static void
1184    parse_pub_record (keyserver_key_s *key, char *buf)
1185    {
1186        enum pub_rec_t {ID=1, KEYID, ALGO, SIZE, CREATE, EXPIRE};
1187        char *p;
1188        int recno = 0;
1189        int off = 0;
1190    
1191        /* pub:{BF3DF9B4, ED4681C9BF3DF9B4, FPR}:17:1024:925411133:: */
1192        p = strtok (buf, ":");
1193        while (p != NULL) {
1194            recno++;
1195            switch (recno) {
1196            case ID:
1197                break;
1198    
1199            case KEYID:
1200                /* If for any reason the returned record actually contains
1201                   a fingerprint instead of a key ID, we truncate the fpr. */
1202                off = strlen (p) == 40? 32 : 0;
1203                free_if_alloc (key->keyid);
1204                key->keyid = m_strdup (p+off);
1205                break;
1206    
1207  /* Convert an iso date @iso_date (YYYY-MM-DD) into the locale          case ALGO:
1208     representation and store it into @loc_date.              key->algo = atoi (p);
1209     Return value: 0 on success. */              break;
1210  static int              
1211  parse_iso_date (const char *iso_date, char *loc_date, size_t loclen)          case SIZE:
1212                key->bits = atoi (p);
1213                break;
1214    
1215            case CREATE:
1216                key->creation = strtoul (p, NULL, 10);
1217                break;
1218    
1219            case EXPIRE:
1220                key->expires = strtoul (p, NULL, 10);
1221                break;
1222            }
1223            p = strtok (NULL, ":");
1224        }
1225    }
1226    
1227    
1228    /* Parse a single user id returned by the keyserver. */
1229    static void
1230    parse_uid_record (keyserver_key_s *key, char *buf)
1231  {  {
1232      SYSTEMTIME st;      enum uid_rec_t {ID=1, UID, CREATE, EXPIRE};
1233      char buf[16] = {0}, *p;      keyserver_uid_s *u, *n;
1234      int pos=0;      char *p, *raw;
1235        int recno = 0;
1236    
1237        /* uid:Timo Schulz <[email protected]>:1138440360:: */
1238        u = new keyserver_uid_s;
1239        memset (u, 0, sizeof *u);
1240    
1241      strncpy (buf, iso_date, sizeof (buf)-1);      p = strtok (buf, ":");
     p = strtok (buf, "-");  
1242      while (p != NULL) {      while (p != NULL) {
1243          switch (pos) {          recno++;
1244          case 0: st.wYear  = (WORD)atoi (p); pos++; break;  
1245          case 1: st.wMonth = (WORD)atoi (p); pos++; break;          switch (recno) {
1246          case 2: st.wDay   = (WORD)atoi (p); pos++; break;          case ID:
1247          default: break;              break;
1248    
1249            case UID:
1250                unhexify_buffer (p, &raw);
1251                u->uid = utf8_to_native (raw);
1252                free_if_alloc (raw);
1253                break;
1254    
1255            case CREATE:
1256                u->creation = strtoul (p, NULL, 10);
1257                break;
1258    
1259            case EXPIRE:
1260                u->expires = strtoul (p, NULL, 10);
1261                break;
1262          }          }
1263          p = strtok (NULL, "-");  
1264            p = strtok (NULL, ":");
1265      }      }
1266      if (pos != 3)      if (!key->uids)
1267          return -1;          key->uids = u;
1268            else {
1269      if (!GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,          for (n = key->uids; n->next; n=n->next)
1270                          NULL, loc_date, loclen))              ;
1271          return -1;          n->next = u;
1272      return 0;      }
1273    }
1274    
1275    
1276    /* Peek the next 3 bytes to check if the next line
1277       would be a new "pub" record. In this case, return
1278       -1 as an EOF indication, 0 otherwise. */
1279    static int
1280    is_key_eof (int fd)
1281    {
1282        char buf[64];
1283        int n;
1284    
1285        n = recv (fd, buf, 3, MSG_PEEK);
1286        if (n < 3 || strncmp (buf, "pub", 3))
1287            return 0;
1288        return -1;
1289  }  }
1290    
1291    
1292    /* Return the next key from the search response. */
1293  int  int
1294  kserver_search_next (int fd, keyserver_key *key)  kserver_search_next (int fd, keyserver_key_s **r_key)
1295  {  {
1296      char buf[1024], *p;      keyserver_uid_s *uid, *u = NULL;
1297      int uidlen, nbytes, pos = 0;      keyserver_key_s *key;
1298        char buf[512];
1299        int n = 0;
1300        long max = 0;
1301    
1302      log_debug ("keyserver_search_next:\r\n");      log_debug ("keyserver_search_next:\r\n");
1303            *r_key = NULL;
     if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))  
         return WPTERR_GENERAL;  
1304    
1305      /* XXX: use maschine readable option. */      key = new keyserver_key_s;
1306      log_debug ("%s\r\n", buf);      memset (key, 0, sizeof *key);
1307            for (;;) {
1308      if (!strncmp (buf, "pub", 3)) {          if (sock_getline (fd, buf, DIM (buf)-1, &n))
1309          int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;              break;
1310          key->bits = atol (buf+3);          /*log_debug ("record: '%s'\r\n", buf); */
1311          p = strchr (buf, '>');          if (!strncmp (buf, "pub", 3))
1312          if (!p)              parse_pub_record (key, buf);
1313              goto fail;          else
1314          pos = p - buf + 1;              parse_uid_record (key, buf);
1315          memcpy (key->keyid, buf + pos, 8);          if (is_key_eof (fd))
1316          key->keyid[8] = '\0';              break;
1317          p = strstr (buf, "</a>");      }
         if (!p)  
             goto fail;  
         pos = p - buf + 5;  
         memcpy (key->date, buf + pos, 10);  
         key->date[10] = '\0';  
         parse_iso_date (key->date, key->date, sizeof (key->date)-1);  
         if (revoked) {  
             strcpy (key->uid, "KEY REVOKED: not checked");  
             return 0;  
         }  
         pos += 10;  
         p = buf + pos + 1;  
         while (p && *p != '>')  
             p++;  
         p++;  
         uidlen = strlen (p) - 10;  
         if (!strstr (p, "&lt;") && !strstr (p, "&gt;")) {  
             pos=0;  
             while (p && *p && pos < sizeof (key->uid)-1) {  
                 if (*p == '<')  
                     break;  
                 key->uid[pos++] = *p++;  
             }  
             key->uid[pos] ='\0';  
             return 0;  
         }  
1318    
1319          if (uidlen > sizeof (key->uid)-1)      /* the uid with the newest self sig is used as the
1320              uidlen = sizeof (key->uid)-1;         primary user id. */
1321          memcpy (key->uid, p, uidlen);      for (uid = key->uids; uid; uid = uid->next) {
1322          key->uid[uidlen] = '\0';          if (uid->creation > max) {
1323          strcat (key->uid, ">");              max = uid->creation;
1324          p = strchr (key->uid, '&');              u = uid;
         if (p) {  
             key->uid[(p-key->uid)] = '<';  
             memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4,  
                      strlen (key->uid)-3);  
1325          }          }
         return 0;  
1326      }      }
1327    
1328  fail:      key->main_uid = u? u : key->uids;
1329      key->bits = 0;      *r_key = key;
     memset (key, 0, sizeof *key);  
1330      return 0;      return 0;
1331  }  }
1332    
1333    
1334    /* Release the keyserver key @key and all its elements. */
1335    void
1336    kserver_release_key (keyserver_key_s *key)
1337    {
1338        keyserver_uid_s *u;
1339    
1340        while (key->uids) {
1341            u = key->uids->next;
1342            free_if_alloc (key->uids->uid);
1343            free_if_alloc (key->uids);
1344            key->uids = u;
1345        }
1346        free_if_alloc (key->keyid);
1347        free_if_alloc (key);
1348    }
1349    
1350    
1351  /* Release mbmers in the proxy context @ctx. */  /* Release mbmers in the proxy context @ctx. */
1352  void  void
1353  kserver_proxy_release (keyserver_proxy_t ctx)  kserver_proxy_release (keyserver_proxy_t ctx)
# Line 1188  spawn_application (char *cmdl) Line 1386  spawn_application (char *cmdl)
1386  }  }
1387    
1388    
1389  /* Receive an key via LDAP from host @host with the keyid @keyid.  static FILE*
1390     @key contains the key on success. */  do_spawn_ldap_helper (const char *host, const char *keyid)
1391  int  {
1392  ldap_recvkey (const char *host, const char *keyid, char *key, int maxkeylen)      FILE *fp = NULL;
1393  {          StringBuffer cmd;
1394      FILE *fp;      char *sep, *p, *ksprg;
1395      const char *s;      char outf[256], inf[256];
1396      char *ksprg = NULL, *p = NULL, *sep;      size_t n;
     char inf[256], outf[256], buf[512];  
     DWORD n;  
     int start_key = 0, failed = 0;  
     int rc = 0;  
1397    
1398      p = get_gnupg_prog ();      p = get_gnupg_prog ();
1399      n = strlen (p) + 1 + 128;      n = strlen (p) + 1 + 128;
1400      ksprg = new char[n+1];      ksprg = safe_alloc (n+1);
1401      if (!ksprg)      if (!ksprg)
1402          BUG (0);          BUG (0);
1403      sep = strrchr (p, '\\');      sep = strrchr (p, '\\');
# Line 1215  ldap_recvkey (const char *host, const ch Line 1409  ldap_recvkey (const char *host, const ch
1409      if (file_exist_check (ksprg)) {      if (file_exist_check (ksprg)) {
1410          log_box ("LDAP Keyserver Plugin", MB_ERR,          log_box ("LDAP Keyserver Plugin", MB_ERR,
1411                   "%s: could not find LDAP keyserver module!", ksprg);                   "%s: could not find LDAP keyserver module!", ksprg);
1412          rc = -1;          fp = NULL;
1413          goto leave;          goto leave;
1414      }      }
1415      get_temp_name (outf, sizeof (outf)-1, keyid);      get_temp_name (outf, DIM (outf)-1, keyid);
1416      get_temp_name (inf, sizeof (inf)-1, NULL);      get_temp_name (inf, DIM (inf)-1, NULL);
1417      fp = fopen (inf, "w+b");      fp = fopen (inf, "w+b");
1418      if (!fp) {      if (!fp) {
1419          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", inf,          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", inf,
1420                   winpt_strerror (WPTERR_FILE_OPEN));                   winpt_strerror (WPTERR_FILE_OPEN));
         rc = -1;  
1421          goto leave;          goto leave;
1422      }      }
1423      fprintf (fp,      fprintf (fp,
1424          "VERSION 1\n"          "VERSION 1\n"
1425          "PROGRAM 1.4.3-cvs\n"          "PROGRAM %d.%d.%d\n"
1426          "SCHEME ldap\n"          "SCHEME ldap\n"
1427          "HOST %s\n"          "HOST %s\n"
1428          "COMMAND GET\n"          "COMMAND GET\n"
1429          "\n"          "\n"
1430          "%s\n",          "%s\n",
1431            gpgver[0], gpgver[1], gpgver[2],
1432          host? skip_type_prefix (host): "64.94.85.200", keyid);          host? skip_type_prefix (host): "64.94.85.200", keyid);
1433      fclose (fp);      fclose (fp);
1434    
1435      p = new char[strlen (ksprg) + strlen (inf) + strlen (outf) + 32];      cmd = ksprg;
1436      if (!p)      cmd = cmd + " -o " + outf + " " + inf;
1437          BUG (NULL);      if (spawn_application ((char*)cmd.getBuffer ())) {
1438      sprintf (p, "%s -o %s %s", ksprg, outf, inf);          fp = NULL;
     if (spawn_application (p)) {  
         rc = -1;  
1439          goto leave;          goto leave;
1440      }      }
   
1441      fp = fopen (outf, "rb");      fp = fopen (outf, "rb");
1442      if (!fp) {      if (!fp)
1443          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,          log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,
1444                   winpt_strerror (WPTERR_FILE_OPEN));                   winpt_strerror (WPTERR_FILE_OPEN));
1445          rc = -1;  
1446          goto leave;  leave:
1447      }      DeleteFile (inf);
1448      memset (key, 0, maxkeylen);      DeleteFile (outf);
1449        free_if_alloc (ksprg);
1450        return fp;
1451    }
1452    
1453    /* Receive an key via LDAP from host @host with the keyid @keyid.
1454       @key contains the key on success. */
1455    int
1456    ldap_recvkey (const char *host, const char *keyid,
1457                  char **r_key, size_t *r_keylen)
1458    {  
1459        gpgme_data_t raw;
1460        FILE *fp;
1461        const char *s;
1462        char buf[512];
1463        int start_key = 0, failed = 0;
1464        int rc = 0;
1465    
1466        fp = do_spawn_ldap_helper (host, keyid);
1467        if (!fp)
1468            return WPTERR_GENERAL;
1469    
1470        if (gpgme_data_new (&raw))
1471            BUG (0);
1472      while (!feof (fp)) {      while (!feof (fp)) {
1473          s = fgets (buf, sizeof (buf)-1, fp);          s = fgets (buf, DIM (buf)-1, fp);
1474          if (!s)          if (!s)
1475              break;              break;
1476          if (strstr (s, "KEY") && strstr (s, "FAILED")) {          if (strstr (s, "KEY") && strstr (s, "FAILED")) {
# Line 1266  ldap_recvkey (const char *host, const ch Line 1480  ldap_recvkey (const char *host, const ch
1480          if (!start_key && strstr (s, "KEY") && strstr (s, "BEGIN")) {          if (!start_key && strstr (s, "KEY") && strstr (s, "BEGIN")) {
1481              start_key = 1;              start_key = 1;
1482              continue;              continue;
1483          }                }
1484          if (!start_key)          if (!start_key)
1485              continue;              continue;
1486          strcat (key, buf);          gpgme_data_write (raw, buf, strlen (buf));
1487          maxkeylen -= strlen (buf);          if (strstr (s, "KEY") && strstr (s, "END"))
         if (maxkeylen < 0 || (strstr (s, "KEY") && strstr (s, "END")))  
1488              break;              break;
1489      }      }
1490      fclose (fp);      fclose (fp);
1491    
1492  leave:      if (failed)
     if (failed || !strlen (key))  
1493          rc = WPTERR_WINSOCK_RECVKEY;          rc = WPTERR_WINSOCK_RECVKEY;
1494      DeleteFile (inf);      *r_key = data_release_and_get_mem (raw, r_keylen);
     DeleteFile (outf);  
     free_if_alloc (p);  
     free_if_alloc (ksprg);  
1495      return rc;      return rc;
1496  }  }
1497    
# Line 1290  leave: Line 1499  leave:
1499  /* Receive an key via FINGER from host @host with the user @user.  /* Receive an key via FINGER from host @host with the user @user.
1500     On success @key contains the key. */     On success @key contains the key. */
1501  int  int
1502  finger_recvkey (const char *host, const char *user, char *key, int maxkeylen)  finger_recvkey (const char *host, const char *user,
1503                    char **r_key, size_t *r_keylen)
1504  {  {
1505      char buf[128];      gpgme_data_t raw;
1506        char buf[256+1];
1507      int fd, nread;      int fd, nread;
1508      int start_key = 0;      int start_key = 0;
1509      int rc=0;      int rc=0;
# Line 1304  finger_recvkey (const char *host, const Line 1515  finger_recvkey (const char *host, const
1515      sock_write (fd, user, strlen (user));      sock_write (fd, user, strlen (user));
1516      sock_write (fd, "\r\n", 2);      sock_write (fd, "\r\n", 2);
1517    
1518      memset (key, 0, maxkeylen);      if (gpgme_data_new (&raw))
1519      while (maxkeylen > 0) {          return WPTERR_WINSOCK_RECVKEY;
1520          if (sock_getline (fd, buf, sizeof (buf), &nread))  
1521        for (;;) {
1522            if (sock_getline (fd, buf, DIM (buf)-1, &nread))
1523              break;              break;
1524          strcat (buf, "\n");          strcat (buf, "\n");
1525          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {          if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {
1526              strcat (key, buf);              gpgme_data_write (raw, buf, nread);
1527              start_key = 1;              start_key = 1;
             maxkeylen -= nread;  
1528          }          }
1529          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {          else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {
1530              strcat (key, buf);              gpgme_data_write (raw, buf, nread);
1531              start_key--;              start_key--;
             maxkeylen -= nread;  
1532              break;              break;
1533          }          }
1534          else if (start_key) {          else if (start_key)
1535              strcat (key, buf);              gpgme_data_write (raw, buf, nread);
             maxkeylen -= nread;  
         }  
1536      }      }
1537    
1538      closesocket (fd);      closesocket (fd);
1539      if (start_key != 0)      if (start_key != 0)
1540          rc = WPTERR_WINSOCK_RECVKEY;          rc = WPTERR_WINSOCK_RECVKEY;
1541        *r_key = data_release_and_get_mem (raw, r_keylen);
1542      return rc;      return rc;
1543  }  }
1544    
1545    
1546  /* Check if the given name @name is a valid hostname. */  /* Check if the given name @name is a valid inernet address
1547       which means an dotted IP or a valid DNS name.
1548       Return value: 0 on success. */
1549  int  int
1550  check_IP_or_hostname (const char *name)  check_inet_address (const char *addr)
1551  {  {
1552      const char *not_allowed = "=!�$%&@#*~\\/}][{<>|,;:'";      const char *not_allowed = "=!�$%&@#*~\\/}][{<>|,;:'";
1553      size_t i, j;      size_t i;
1554    
1555      for (i=0; i < strlen (name); i++) {      for (i=0; i < strlen (addr); i++) {
1556          for (j =0; j < strlen (not_allowed); j++) {          if (strchr (not_allowed, addr[i]))
1557              if (name[i] == not_allowed[j])              return -1;
1558                  return -1;      }
1559          }      return 0;
1560    }
1561    
1562    
1563    /* Split the URL @r_keyserver into the host and the port
1564       part if possible. */
1565    gpgme_error_t
1566    parse_keyserver_url (char **r_keyserver, unsigned short *r_port)
1567    {
1568        char *p;
1569        char *url = *r_keyserver;
1570        int off = 0;
1571    
1572        /* no port is given so use the default port. */
1573        p = strrchr (url, ':');
1574        if (p == strchr (url, ':')) {
1575            int port = port_from_proto (proto_from_URL (url));
1576            if (!port)
1577                port = HKP_PORT;
1578            *r_port = port;
1579            return 0;
1580      }      }
1581    
1582        if (url[(p-url)-1] == '/') /* remove / in .de/:11371 */
1583            off = 1;
1584    
1585        *r_keyserver = substr (url, 0, (p-url)-off);
1586        *r_port = atoi (url+(p-url)+1);
1587        free_if_alloc (url);
1588      return 0;      return 0;
1589  }  }

Legend:
Removed from v.193  
changed lines
  Added in v.290

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26