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

Contents of /trunk/Src/wptKeyserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 147 - (show annotations)
Fri Jan 13 14:21:16 2006 UTC (19 years, 1 month ago) by twoaday
File size: 33066 byte(s)
2006-11-13  Timo Schulz  <ts@g10code.com>
 
        * wptPreferencesDlg.cpp (prefs_dlg_proc): Changed translation.
        * wptGPGPrefsDlg.cpp (gpgprefs_dlg_proc): Likewise.
        * wptAboutDlgs.cpp (about_dlg_proc): Make sure GPG about
        dialog isn't shown twice.
        * wptKeyCache.cpp (gpg_keycache_next_updated_key): New.
        (gpg_keycache_update_key): Set update flag.
        * wptKeyManagerDlg.cpp (refresh_keylist): New.
        (keymanager_dlg_proc): Use new refresh system for keyservers.
        * wptKeyserverSearchDlg.cpp (kserver_search_dlg_proc):
        Update keycache.
        * wptKeyserverDlg.cpp (hkp_dlg_proc): Likewise.
        * wptKeyserver.cpp (socket_read_ext): New.
        (kserver_recv_key_ext): New.
        (kserver_read_config, kserver_write_config): Removed.
         


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

Properties

Name Value
svn:eol-style native

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26