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

Contents of /trunk/Src/wptKeyserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 185 - (show annotations)
Mon Mar 20 12:48:52 2006 UTC (18 years, 11 months ago) by twoaday
File size: 32642 byte(s)
2006-03-20  Timo Schulz  <ts@g10code.de>

        * wptUTF8.cpp (get_native_charset): Removed.
        (utf8_to_native): Rewritten.
        * wptKeyEditDlgs.cpp (do_add_new_userid): Correct charset
        handling.
        * wptKeygenCBDlg.cpp (keygen_cb): Do proper reset if needed.


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

Properties

Name Value
svn:eol-style native

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26