Deleted Added
full compact
common.c (214256) common.c (221830)
1/*-
2 * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/lib/libfetch/common.c 214256 2010-10-24 01:05:10Z emaste $");
30__FBSDID("$FreeBSD: head/lib/libfetch/common.c 221830 2011-05-13 07:21:41Z des $");
31
32#include <sys/param.h>
33#include <sys/socket.h>
34#include <sys/time.h>
35#include <sys/uio.h>
36
37#include <netinet/in.h>
38
39#include <ctype.h>
40#include <errno.h>
41#include <fcntl.h>
42#include <netdb.h>
43#include <pwd.h>
44#include <stdarg.h>
45#include <stdlib.h>
46#include <stdio.h>
47#include <string.h>
48#include <unistd.h>
49
50#include "fetch.h"
51#include "common.h"
52
53
54/*** Local data **************************************************************/
55
56/*
57 * Error messages for resolver errors
58 */
59static struct fetcherr netdb_errlist[] = {
60#ifdef EAI_NODATA
61 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
62#endif
63 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
64 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
65 { EAI_NONAME, FETCH_RESOLV, "No address record" },
66 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
67};
68
69/* End-of-Line */
70static const char ENDL[2] = "\r\n";
71
72
73/*** Error-reporting functions ***********************************************/
74
75/*
76 * Map error code to string
77 */
78static struct fetcherr *
79fetch_finderr(struct fetcherr *p, int e)
80{
81 while (p->num != -1 && p->num != e)
82 p++;
83 return (p);
84}
85
86/*
87 * Set error code
88 */
89void
90fetch_seterr(struct fetcherr *p, int e)
91{
92 p = fetch_finderr(p, e);
93 fetchLastErrCode = p->cat;
94 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
95}
96
97/*
98 * Set error code according to errno
99 */
100void
101fetch_syserr(void)
102{
103 switch (errno) {
104 case 0:
105 fetchLastErrCode = FETCH_OK;
106 break;
107 case EPERM:
108 case EACCES:
109 case EROFS:
110 case EAUTH:
111 case ENEEDAUTH:
112 fetchLastErrCode = FETCH_AUTH;
113 break;
114 case ENOENT:
115 case EISDIR: /* XXX */
116 fetchLastErrCode = FETCH_UNAVAIL;
117 break;
118 case ENOMEM:
119 fetchLastErrCode = FETCH_MEMORY;
120 break;
121 case EBUSY:
122 case EAGAIN:
123 fetchLastErrCode = FETCH_TEMP;
124 break;
125 case EEXIST:
126 fetchLastErrCode = FETCH_EXISTS;
127 break;
128 case ENOSPC:
129 fetchLastErrCode = FETCH_FULL;
130 break;
131 case EADDRINUSE:
132 case EADDRNOTAVAIL:
133 case ENETDOWN:
134 case ENETUNREACH:
135 case ENETRESET:
136 case EHOSTUNREACH:
137 fetchLastErrCode = FETCH_NETWORK;
138 break;
139 case ECONNABORTED:
140 case ECONNRESET:
141 fetchLastErrCode = FETCH_ABORT;
142 break;
143 case ETIMEDOUT:
144 fetchLastErrCode = FETCH_TIMEOUT;
145 break;
146 case ECONNREFUSED:
147 case EHOSTDOWN:
148 fetchLastErrCode = FETCH_DOWN;
149 break;
150default:
151 fetchLastErrCode = FETCH_UNKNOWN;
152 }
153 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
154}
155
156
157/*
158 * Emit status message
159 */
160void
161fetch_info(const char *fmt, ...)
162{
163 va_list ap;
164
165 va_start(ap, fmt);
166 vfprintf(stderr, fmt, ap);
167 va_end(ap);
168 fputc('\n', stderr);
169}
170
171
172/*** Network-related utility functions ***************************************/
173
174/*
175 * Return the default port for a scheme
176 */
177int
178fetch_default_port(const char *scheme)
179{
180 struct servent *se;
181
182 if ((se = getservbyname(scheme, "tcp")) != NULL)
183 return (ntohs(se->s_port));
184 if (strcasecmp(scheme, SCHEME_FTP) == 0)
185 return (FTP_DEFAULT_PORT);
186 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
187 return (HTTP_DEFAULT_PORT);
188 return (0);
189}
190
191/*
192 * Return the default proxy port for a scheme
193 */
194int
195fetch_default_proxy_port(const char *scheme)
196{
197 if (strcasecmp(scheme, SCHEME_FTP) == 0)
198 return (FTP_DEFAULT_PROXY_PORT);
199 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
200 return (HTTP_DEFAULT_PROXY_PORT);
201 return (0);
202}
203
204
205/*
206 * Create a connection for an existing descriptor.
207 */
208conn_t *
209fetch_reopen(int sd)
210{
211 conn_t *conn;
212
213 /* allocate and fill connection structure */
214 if ((conn = calloc(1, sizeof(*conn))) == NULL)
215 return (NULL);
31
32#include <sys/param.h>
33#include <sys/socket.h>
34#include <sys/time.h>
35#include <sys/uio.h>
36
37#include <netinet/in.h>
38
39#include <ctype.h>
40#include <errno.h>
41#include <fcntl.h>
42#include <netdb.h>
43#include <pwd.h>
44#include <stdarg.h>
45#include <stdlib.h>
46#include <stdio.h>
47#include <string.h>
48#include <unistd.h>
49
50#include "fetch.h"
51#include "common.h"
52
53
54/*** Local data **************************************************************/
55
56/*
57 * Error messages for resolver errors
58 */
59static struct fetcherr netdb_errlist[] = {
60#ifdef EAI_NODATA
61 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
62#endif
63 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
64 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
65 { EAI_NONAME, FETCH_RESOLV, "No address record" },
66 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
67};
68
69/* End-of-Line */
70static const char ENDL[2] = "\r\n";
71
72
73/*** Error-reporting functions ***********************************************/
74
75/*
76 * Map error code to string
77 */
78static struct fetcherr *
79fetch_finderr(struct fetcherr *p, int e)
80{
81 while (p->num != -1 && p->num != e)
82 p++;
83 return (p);
84}
85
86/*
87 * Set error code
88 */
89void
90fetch_seterr(struct fetcherr *p, int e)
91{
92 p = fetch_finderr(p, e);
93 fetchLastErrCode = p->cat;
94 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
95}
96
97/*
98 * Set error code according to errno
99 */
100void
101fetch_syserr(void)
102{
103 switch (errno) {
104 case 0:
105 fetchLastErrCode = FETCH_OK;
106 break;
107 case EPERM:
108 case EACCES:
109 case EROFS:
110 case EAUTH:
111 case ENEEDAUTH:
112 fetchLastErrCode = FETCH_AUTH;
113 break;
114 case ENOENT:
115 case EISDIR: /* XXX */
116 fetchLastErrCode = FETCH_UNAVAIL;
117 break;
118 case ENOMEM:
119 fetchLastErrCode = FETCH_MEMORY;
120 break;
121 case EBUSY:
122 case EAGAIN:
123 fetchLastErrCode = FETCH_TEMP;
124 break;
125 case EEXIST:
126 fetchLastErrCode = FETCH_EXISTS;
127 break;
128 case ENOSPC:
129 fetchLastErrCode = FETCH_FULL;
130 break;
131 case EADDRINUSE:
132 case EADDRNOTAVAIL:
133 case ENETDOWN:
134 case ENETUNREACH:
135 case ENETRESET:
136 case EHOSTUNREACH:
137 fetchLastErrCode = FETCH_NETWORK;
138 break;
139 case ECONNABORTED:
140 case ECONNRESET:
141 fetchLastErrCode = FETCH_ABORT;
142 break;
143 case ETIMEDOUT:
144 fetchLastErrCode = FETCH_TIMEOUT;
145 break;
146 case ECONNREFUSED:
147 case EHOSTDOWN:
148 fetchLastErrCode = FETCH_DOWN;
149 break;
150default:
151 fetchLastErrCode = FETCH_UNKNOWN;
152 }
153 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
154}
155
156
157/*
158 * Emit status message
159 */
160void
161fetch_info(const char *fmt, ...)
162{
163 va_list ap;
164
165 va_start(ap, fmt);
166 vfprintf(stderr, fmt, ap);
167 va_end(ap);
168 fputc('\n', stderr);
169}
170
171
172/*** Network-related utility functions ***************************************/
173
174/*
175 * Return the default port for a scheme
176 */
177int
178fetch_default_port(const char *scheme)
179{
180 struct servent *se;
181
182 if ((se = getservbyname(scheme, "tcp")) != NULL)
183 return (ntohs(se->s_port));
184 if (strcasecmp(scheme, SCHEME_FTP) == 0)
185 return (FTP_DEFAULT_PORT);
186 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
187 return (HTTP_DEFAULT_PORT);
188 return (0);
189}
190
191/*
192 * Return the default proxy port for a scheme
193 */
194int
195fetch_default_proxy_port(const char *scheme)
196{
197 if (strcasecmp(scheme, SCHEME_FTP) == 0)
198 return (FTP_DEFAULT_PROXY_PORT);
199 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
200 return (HTTP_DEFAULT_PROXY_PORT);
201 return (0);
202}
203
204
205/*
206 * Create a connection for an existing descriptor.
207 */
208conn_t *
209fetch_reopen(int sd)
210{
211 conn_t *conn;
212
213 /* allocate and fill connection structure */
214 if ((conn = calloc(1, sizeof(*conn))) == NULL)
215 return (NULL);
216 fcntl(sd, F_SETFD, FD_CLOEXEC);
216 conn->sd = sd;
217 ++conn->ref;
218 return (conn);
219}
220
221
222/*
223 * Bump a connection's reference count.
224 */
225conn_t *
226fetch_ref(conn_t *conn)
227{
228
229 ++conn->ref;
230 return (conn);
231}
232
233
234/*
235 * Bind a socket to a specific local address
236 */
237int
238fetch_bind(int sd, int af, const char *addr)
239{
240 struct addrinfo hints, *res, *res0;
241 int err;
242
243 memset(&hints, 0, sizeof(hints));
244 hints.ai_family = af;
245 hints.ai_socktype = SOCK_STREAM;
246 hints.ai_protocol = 0;
247 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
248 return (-1);
249 for (res = res0; res; res = res->ai_next)
250 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
251 return (0);
252 return (-1);
253}
254
255
256/*
257 * Establish a TCP connection to the specified port on the specified host.
258 */
259conn_t *
260fetch_connect(const char *host, int port, int af, int verbose)
261{
262 conn_t *conn;
263 char pbuf[10];
264 const char *bindaddr;
265 struct addrinfo hints, *res, *res0;
266 int sd, err;
267
268 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
269
270 if (verbose)
271 fetch_info("looking up %s", host);
272
273 /* look up host name and set up socket address structure */
274 snprintf(pbuf, sizeof(pbuf), "%d", port);
275 memset(&hints, 0, sizeof(hints));
276 hints.ai_family = af;
277 hints.ai_socktype = SOCK_STREAM;
278 hints.ai_protocol = 0;
279 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
280 netdb_seterr(err);
281 return (NULL);
282 }
283 bindaddr = getenv("FETCH_BIND_ADDRESS");
284
285 if (verbose)
286 fetch_info("connecting to %s:%d", host, port);
287
288 /* try to connect */
289 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
290 if ((sd = socket(res->ai_family, res->ai_socktype,
291 res->ai_protocol)) == -1)
292 continue;
293 if (bindaddr != NULL && *bindaddr != '\0' &&
294 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
295 fetch_info("failed to bind to '%s'", bindaddr);
296 close(sd);
297 continue;
298 }
299 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
300 fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
301 break;
302 close(sd);
303 }
304 freeaddrinfo(res0);
305 if (sd == -1) {
306 fetch_syserr();
307 return (NULL);
308 }
309
310 if ((conn = fetch_reopen(sd)) == NULL) {
311 fetch_syserr();
312 close(sd);
313 }
314 return (conn);
315}
316
317
318/*
319 * Enable SSL on a connection.
320 */
321int
322fetch_ssl(conn_t *conn, int verbose)
323{
324#ifdef WITH_SSL
325 int ret, ssl_err;
326
327 /* Init the SSL library and context */
328 if (!SSL_library_init()){
329 fprintf(stderr, "SSL library init failed\n");
330 return (-1);
331 }
332
333 SSL_load_error_strings();
334
335 conn->ssl_meth = SSLv23_client_method();
336 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
337 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
338
339 conn->ssl = SSL_new(conn->ssl_ctx);
340 if (conn->ssl == NULL){
341 fprintf(stderr, "SSL context creation failed\n");
342 return (-1);
343 }
344 SSL_set_fd(conn->ssl, conn->sd);
345 while ((ret = SSL_connect(conn->ssl)) == -1) {
346 ssl_err = SSL_get_error(conn->ssl, ret);
347 if (ssl_err != SSL_ERROR_WANT_READ &&
348 ssl_err != SSL_ERROR_WANT_WRITE) {
349 ERR_print_errors_fp(stderr);
350 return (-1);
351 }
352 }
353
354 if (verbose) {
355 X509_NAME *name;
356 char *str;
357
358 fprintf(stderr, "SSL connection established using %s\n",
359 SSL_get_cipher(conn->ssl));
360 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
361 name = X509_get_subject_name(conn->ssl_cert);
362 str = X509_NAME_oneline(name, 0, 0);
363 printf("Certificate subject: %s\n", str);
364 free(str);
365 name = X509_get_issuer_name(conn->ssl_cert);
366 str = X509_NAME_oneline(name, 0, 0);
367 printf("Certificate issuer: %s\n", str);
368 free(str);
369 }
370
371 return (0);
372#else
373 (void)conn;
374 (void)verbose;
375 fprintf(stderr, "SSL support disabled\n");
376 return (-1);
377#endif
378}
379
380#define FETCH_READ_WAIT -2
381#define FETCH_READ_ERROR -1
382#define FETCH_READ_DONE 0
383
384#ifdef WITH_SSL
385static ssize_t
386fetch_ssl_read(SSL *ssl, char *buf, size_t len)
387{
388 ssize_t rlen;
389 int ssl_err;
390
391 rlen = SSL_read(ssl, buf, len);
392 if (rlen < 0) {
393 ssl_err = SSL_get_error(ssl, rlen);
394 if (ssl_err == SSL_ERROR_WANT_READ ||
395 ssl_err == SSL_ERROR_WANT_WRITE) {
396 return (FETCH_READ_WAIT);
397 } else {
398 ERR_print_errors_fp(stderr);
399 return (FETCH_READ_ERROR);
400 }
401 }
402 return (rlen);
403}
404#endif
405
406static ssize_t
407fetch_socket_read(int sd, char *buf, size_t len)
408{
409 ssize_t rlen;
410
411 rlen = read(sd, buf, len);
412 if (rlen < 0) {
413 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
414 return (FETCH_READ_WAIT);
415 else
416 return (FETCH_READ_ERROR);
417 }
418 return (rlen);
419}
420
421/*
422 * Read a character from a connection w/ timeout
423 */
424ssize_t
425fetch_read(conn_t *conn, char *buf, size_t len)
426{
427 struct timeval now, timeout, delta;
428 fd_set readfds;
429 ssize_t rlen, total;
430 int r;
431
432 if (fetchTimeout) {
433 FD_ZERO(&readfds);
434 gettimeofday(&timeout, NULL);
435 timeout.tv_sec += fetchTimeout;
436 }
437
438 total = 0;
439 while (len > 0) {
440 /*
441 * The socket is non-blocking. Instead of the canonical
442 * select() -> read(), we do the following:
443 *
444 * 1) call read() or SSL_read().
445 * 2) if an error occurred, return -1.
446 * 3) if we received data but we still expect more,
447 * update our counters and loop.
448 * 4) if read() or SSL_read() signaled EOF, return.
449 * 5) if we did not receive any data but we're not at EOF,
450 * call select().
451 *
452 * In the SSL case, this is necessary because if we
453 * receive a close notification, we have to call
454 * SSL_read() one additional time after we've read
455 * everything we received.
456 *
457 * In the non-SSL case, it may improve performance (very
458 * slightly) when reading small amounts of data.
459 */
460#ifdef WITH_SSL
461 if (conn->ssl != NULL)
462 rlen = fetch_ssl_read(conn->ssl, buf, len);
463 else
464#endif
465 rlen = fetch_socket_read(conn->sd, buf, len);
466 if (rlen == 0) {
467 break;
468 } else if (rlen > 0) {
469 len -= rlen;
470 buf += rlen;
471 total += rlen;
472 continue;
473 } else if (rlen == FETCH_READ_ERROR) {
474 return (-1);
475 }
476 // assert(rlen == FETCH_READ_WAIT);
477 while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
478 FD_SET(conn->sd, &readfds);
479 gettimeofday(&now, NULL);
480 delta.tv_sec = timeout.tv_sec - now.tv_sec;
481 delta.tv_usec = timeout.tv_usec - now.tv_usec;
482 if (delta.tv_usec < 0) {
483 delta.tv_usec += 1000000;
484 delta.tv_sec--;
485 }
486 if (delta.tv_sec < 0) {
487 errno = ETIMEDOUT;
488 fetch_syserr();
489 return (-1);
490 }
491 errno = 0;
492 r = select(conn->sd + 1, &readfds, NULL, NULL, &delta);
493 if (r == -1) {
494 if (errno == EINTR && fetchRestartCalls)
495 continue;
496 fetch_syserr();
497 return (-1);
498 }
499 }
500 }
501 return (total);
502}
503
504
505/*
506 * Read a line of text from a connection w/ timeout
507 */
508#define MIN_BUF_SIZE 1024
509
510int
511fetch_getln(conn_t *conn)
512{
513 char *tmp;
514 size_t tmpsize;
515 ssize_t len;
516 char c;
517
518 if (conn->buf == NULL) {
519 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
520 errno = ENOMEM;
521 return (-1);
522 }
523 conn->bufsize = MIN_BUF_SIZE;
524 }
525
526 conn->buf[0] = '\0';
527 conn->buflen = 0;
528
529 do {
530 len = fetch_read(conn, &c, 1);
531 if (len == -1)
532 return (-1);
533 if (len == 0)
534 break;
535 conn->buf[conn->buflen++] = c;
536 if (conn->buflen == conn->bufsize) {
537 tmp = conn->buf;
538 tmpsize = conn->bufsize * 2 + 1;
539 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
540 errno = ENOMEM;
541 return (-1);
542 }
543 conn->buf = tmp;
544 conn->bufsize = tmpsize;
545 }
546 } while (c != '\n');
547
548 conn->buf[conn->buflen] = '\0';
549 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
550 return (0);
551}
552
553
554/*
555 * Write to a connection w/ timeout
556 */
557ssize_t
558fetch_write(conn_t *conn, const char *buf, size_t len)
559{
560 struct iovec iov;
561
562 iov.iov_base = __DECONST(char *, buf);
563 iov.iov_len = len;
564 return fetch_writev(conn, &iov, 1);
565}
566
567/*
568 * Write a vector to a connection w/ timeout
569 * Note: can modify the iovec.
570 */
571ssize_t
572fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
573{
574 struct timeval now, timeout, delta;
575 fd_set writefds;
576 ssize_t wlen, total;
577 int r;
578
579 if (fetchTimeout) {
580 FD_ZERO(&writefds);
581 gettimeofday(&timeout, NULL);
582 timeout.tv_sec += fetchTimeout;
583 }
584
585 total = 0;
586 while (iovcnt > 0) {
587 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
588 FD_SET(conn->sd, &writefds);
589 gettimeofday(&now, NULL);
590 delta.tv_sec = timeout.tv_sec - now.tv_sec;
591 delta.tv_usec = timeout.tv_usec - now.tv_usec;
592 if (delta.tv_usec < 0) {
593 delta.tv_usec += 1000000;
594 delta.tv_sec--;
595 }
596 if (delta.tv_sec < 0) {
597 errno = ETIMEDOUT;
598 fetch_syserr();
599 return (-1);
600 }
601 errno = 0;
602 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
603 if (r == -1) {
604 if (errno == EINTR && fetchRestartCalls)
605 continue;
606 return (-1);
607 }
608 }
609 errno = 0;
610#ifdef WITH_SSL
611 if (conn->ssl != NULL)
612 wlen = SSL_write(conn->ssl,
613 iov->iov_base, iov->iov_len);
614 else
615#endif
616 wlen = writev(conn->sd, iov, iovcnt);
617 if (wlen == 0) {
618 /* we consider a short write a failure */
619 /* XXX perhaps we shouldn't in the SSL case */
620 errno = EPIPE;
621 fetch_syserr();
622 return (-1);
623 }
624 if (wlen < 0) {
625 if (errno == EINTR && fetchRestartCalls)
626 continue;
627 return (-1);
628 }
629 total += wlen;
630 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
631 wlen -= iov->iov_len;
632 iov++;
633 iovcnt--;
634 }
635 if (iovcnt > 0) {
636 iov->iov_len -= wlen;
637 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
638 }
639 }
640 return (total);
641}
642
643
644/*
645 * Write a line of text to a connection w/ timeout
646 */
647int
648fetch_putln(conn_t *conn, const char *str, size_t len)
649{
650 struct iovec iov[2];
651 int ret;
652
653 DEBUG(fprintf(stderr, ">>> %s\n", str));
654 iov[0].iov_base = __DECONST(char *, str);
655 iov[0].iov_len = len;
656 iov[1].iov_base = __DECONST(char *, ENDL);
657 iov[1].iov_len = sizeof(ENDL);
658 if (len == 0)
659 ret = fetch_writev(conn, &iov[1], 1);
660 else
661 ret = fetch_writev(conn, iov, 2);
662 if (ret == -1)
663 return (-1);
664 return (0);
665}
666
667
668/*
669 * Close connection
670 */
671int
672fetch_close(conn_t *conn)
673{
674 int ret;
675
676 if (--conn->ref > 0)
677 return (0);
678 ret = close(conn->sd);
679 free(conn->buf);
680 free(conn);
681 return (ret);
682}
683
684
685/*** Directory-related utility functions *************************************/
686
687int
688fetch_add_entry(struct url_ent **p, int *size, int *len,
689 const char *name, struct url_stat *us)
690{
691 struct url_ent *tmp;
692
693 if (*p == NULL) {
694 *size = 0;
695 *len = 0;
696 }
697
698 if (*len >= *size - 1) {
699 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
700 if (tmp == NULL) {
701 errno = ENOMEM;
702 fetch_syserr();
703 return (-1);
704 }
705 *size = (*size * 2 + 1);
706 *p = tmp;
707 }
708
709 tmp = *p + *len;
710 snprintf(tmp->name, PATH_MAX, "%s", name);
711 memcpy(&tmp->stat, us, sizeof(*us));
712
713 (*len)++;
714 (++tmp)->name[0] = 0;
715
716 return (0);
717}
718
719
720/*** Authentication-related utility functions ********************************/
721
722static const char *
723fetch_read_word(FILE *f)
724{
725 static char word[1024];
726
727 if (fscanf(f, " %1023s ", word) != 1)
728 return (NULL);
729 return (word);
730}
731
732/*
733 * Get authentication data for a URL from .netrc
734 */
735int
736fetch_netrc_auth(struct url *url)
737{
738 char fn[PATH_MAX];
739 const char *word;
740 char *p;
741 FILE *f;
742
743 if ((p = getenv("NETRC")) != NULL) {
744 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
745 fetch_info("$NETRC specifies a file name "
746 "longer than PATH_MAX");
747 return (-1);
748 }
749 } else {
750 if ((p = getenv("HOME")) != NULL) {
751 struct passwd *pwd;
752
753 if ((pwd = getpwuid(getuid())) == NULL ||
754 (p = pwd->pw_dir) == NULL)
755 return (-1);
756 }
757 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
758 return (-1);
759 }
760
761 if ((f = fopen(fn, "r")) == NULL)
762 return (-1);
763 while ((word = fetch_read_word(f)) != NULL) {
764 if (strcmp(word, "default") == 0) {
765 DEBUG(fetch_info("Using default .netrc settings"));
766 break;
767 }
768 if (strcmp(word, "machine") == 0 &&
769 (word = fetch_read_word(f)) != NULL &&
770 strcasecmp(word, url->host) == 0) {
771 DEBUG(fetch_info("Using .netrc settings for %s", word));
772 break;
773 }
774 }
775 if (word == NULL)
776 goto ferr;
777 while ((word = fetch_read_word(f)) != NULL) {
778 if (strcmp(word, "login") == 0) {
779 if ((word = fetch_read_word(f)) == NULL)
780 goto ferr;
781 if (snprintf(url->user, sizeof(url->user),
782 "%s", word) > (int)sizeof(url->user)) {
783 fetch_info("login name in .netrc is too long");
784 url->user[0] = '\0';
785 }
786 } else if (strcmp(word, "password") == 0) {
787 if ((word = fetch_read_word(f)) == NULL)
788 goto ferr;
789 if (snprintf(url->pwd, sizeof(url->pwd),
790 "%s", word) > (int)sizeof(url->pwd)) {
791 fetch_info("password in .netrc is too long");
792 url->pwd[0] = '\0';
793 }
794 } else if (strcmp(word, "account") == 0) {
795 if ((word = fetch_read_word(f)) == NULL)
796 goto ferr;
797 /* XXX not supported! */
798 } else {
799 break;
800 }
801 }
802 fclose(f);
803 return (0);
804 ferr:
805 fclose(f);
806 return (-1);
807}
808
809/*
810 * The no_proxy environment variable specifies a set of domains for
811 * which the proxy should not be consulted; the contents is a comma-,
812 * or space-separated list of domain names. A single asterisk will
813 * override all proxy variables and no transactions will be proxied
814 * (for compatability with lynx and curl, see the discussion at
815 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
816 */
817int
818fetch_no_proxy_match(const char *host)
819{
820 const char *no_proxy, *p, *q;
821 size_t h_len, d_len;
822
823 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
824 (no_proxy = getenv("no_proxy")) == NULL)
825 return (0);
826
827 /* asterisk matches any hostname */
828 if (strcmp(no_proxy, "*") == 0)
829 return (1);
830
831 h_len = strlen(host);
832 p = no_proxy;
833 do {
834 /* position p at the beginning of a domain suffix */
835 while (*p == ',' || isspace((unsigned char)*p))
836 p++;
837
838 /* position q at the first separator character */
839 for (q = p; *q; ++q)
840 if (*q == ',' || isspace((unsigned char)*q))
841 break;
842
843 d_len = q - p;
844 if (d_len > 0 && h_len >= d_len &&
845 strncasecmp(host + h_len - d_len,
846 p, d_len) == 0) {
847 /* domain name matches */
848 return (1);
849 }
850
851 p = q + 1;
852 } while (*q);
853
854 return (0);
855}
217 conn->sd = sd;
218 ++conn->ref;
219 return (conn);
220}
221
222
223/*
224 * Bump a connection's reference count.
225 */
226conn_t *
227fetch_ref(conn_t *conn)
228{
229
230 ++conn->ref;
231 return (conn);
232}
233
234
235/*
236 * Bind a socket to a specific local address
237 */
238int
239fetch_bind(int sd, int af, const char *addr)
240{
241 struct addrinfo hints, *res, *res0;
242 int err;
243
244 memset(&hints, 0, sizeof(hints));
245 hints.ai_family = af;
246 hints.ai_socktype = SOCK_STREAM;
247 hints.ai_protocol = 0;
248 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
249 return (-1);
250 for (res = res0; res; res = res->ai_next)
251 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
252 return (0);
253 return (-1);
254}
255
256
257/*
258 * Establish a TCP connection to the specified port on the specified host.
259 */
260conn_t *
261fetch_connect(const char *host, int port, int af, int verbose)
262{
263 conn_t *conn;
264 char pbuf[10];
265 const char *bindaddr;
266 struct addrinfo hints, *res, *res0;
267 int sd, err;
268
269 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
270
271 if (verbose)
272 fetch_info("looking up %s", host);
273
274 /* look up host name and set up socket address structure */
275 snprintf(pbuf, sizeof(pbuf), "%d", port);
276 memset(&hints, 0, sizeof(hints));
277 hints.ai_family = af;
278 hints.ai_socktype = SOCK_STREAM;
279 hints.ai_protocol = 0;
280 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
281 netdb_seterr(err);
282 return (NULL);
283 }
284 bindaddr = getenv("FETCH_BIND_ADDRESS");
285
286 if (verbose)
287 fetch_info("connecting to %s:%d", host, port);
288
289 /* try to connect */
290 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
291 if ((sd = socket(res->ai_family, res->ai_socktype,
292 res->ai_protocol)) == -1)
293 continue;
294 if (bindaddr != NULL && *bindaddr != '\0' &&
295 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
296 fetch_info("failed to bind to '%s'", bindaddr);
297 close(sd);
298 continue;
299 }
300 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
301 fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
302 break;
303 close(sd);
304 }
305 freeaddrinfo(res0);
306 if (sd == -1) {
307 fetch_syserr();
308 return (NULL);
309 }
310
311 if ((conn = fetch_reopen(sd)) == NULL) {
312 fetch_syserr();
313 close(sd);
314 }
315 return (conn);
316}
317
318
319/*
320 * Enable SSL on a connection.
321 */
322int
323fetch_ssl(conn_t *conn, int verbose)
324{
325#ifdef WITH_SSL
326 int ret, ssl_err;
327
328 /* Init the SSL library and context */
329 if (!SSL_library_init()){
330 fprintf(stderr, "SSL library init failed\n");
331 return (-1);
332 }
333
334 SSL_load_error_strings();
335
336 conn->ssl_meth = SSLv23_client_method();
337 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
338 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
339
340 conn->ssl = SSL_new(conn->ssl_ctx);
341 if (conn->ssl == NULL){
342 fprintf(stderr, "SSL context creation failed\n");
343 return (-1);
344 }
345 SSL_set_fd(conn->ssl, conn->sd);
346 while ((ret = SSL_connect(conn->ssl)) == -1) {
347 ssl_err = SSL_get_error(conn->ssl, ret);
348 if (ssl_err != SSL_ERROR_WANT_READ &&
349 ssl_err != SSL_ERROR_WANT_WRITE) {
350 ERR_print_errors_fp(stderr);
351 return (-1);
352 }
353 }
354
355 if (verbose) {
356 X509_NAME *name;
357 char *str;
358
359 fprintf(stderr, "SSL connection established using %s\n",
360 SSL_get_cipher(conn->ssl));
361 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
362 name = X509_get_subject_name(conn->ssl_cert);
363 str = X509_NAME_oneline(name, 0, 0);
364 printf("Certificate subject: %s\n", str);
365 free(str);
366 name = X509_get_issuer_name(conn->ssl_cert);
367 str = X509_NAME_oneline(name, 0, 0);
368 printf("Certificate issuer: %s\n", str);
369 free(str);
370 }
371
372 return (0);
373#else
374 (void)conn;
375 (void)verbose;
376 fprintf(stderr, "SSL support disabled\n");
377 return (-1);
378#endif
379}
380
381#define FETCH_READ_WAIT -2
382#define FETCH_READ_ERROR -1
383#define FETCH_READ_DONE 0
384
385#ifdef WITH_SSL
386static ssize_t
387fetch_ssl_read(SSL *ssl, char *buf, size_t len)
388{
389 ssize_t rlen;
390 int ssl_err;
391
392 rlen = SSL_read(ssl, buf, len);
393 if (rlen < 0) {
394 ssl_err = SSL_get_error(ssl, rlen);
395 if (ssl_err == SSL_ERROR_WANT_READ ||
396 ssl_err == SSL_ERROR_WANT_WRITE) {
397 return (FETCH_READ_WAIT);
398 } else {
399 ERR_print_errors_fp(stderr);
400 return (FETCH_READ_ERROR);
401 }
402 }
403 return (rlen);
404}
405#endif
406
407static ssize_t
408fetch_socket_read(int sd, char *buf, size_t len)
409{
410 ssize_t rlen;
411
412 rlen = read(sd, buf, len);
413 if (rlen < 0) {
414 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
415 return (FETCH_READ_WAIT);
416 else
417 return (FETCH_READ_ERROR);
418 }
419 return (rlen);
420}
421
422/*
423 * Read a character from a connection w/ timeout
424 */
425ssize_t
426fetch_read(conn_t *conn, char *buf, size_t len)
427{
428 struct timeval now, timeout, delta;
429 fd_set readfds;
430 ssize_t rlen, total;
431 int r;
432
433 if (fetchTimeout) {
434 FD_ZERO(&readfds);
435 gettimeofday(&timeout, NULL);
436 timeout.tv_sec += fetchTimeout;
437 }
438
439 total = 0;
440 while (len > 0) {
441 /*
442 * The socket is non-blocking. Instead of the canonical
443 * select() -> read(), we do the following:
444 *
445 * 1) call read() or SSL_read().
446 * 2) if an error occurred, return -1.
447 * 3) if we received data but we still expect more,
448 * update our counters and loop.
449 * 4) if read() or SSL_read() signaled EOF, return.
450 * 5) if we did not receive any data but we're not at EOF,
451 * call select().
452 *
453 * In the SSL case, this is necessary because if we
454 * receive a close notification, we have to call
455 * SSL_read() one additional time after we've read
456 * everything we received.
457 *
458 * In the non-SSL case, it may improve performance (very
459 * slightly) when reading small amounts of data.
460 */
461#ifdef WITH_SSL
462 if (conn->ssl != NULL)
463 rlen = fetch_ssl_read(conn->ssl, buf, len);
464 else
465#endif
466 rlen = fetch_socket_read(conn->sd, buf, len);
467 if (rlen == 0) {
468 break;
469 } else if (rlen > 0) {
470 len -= rlen;
471 buf += rlen;
472 total += rlen;
473 continue;
474 } else if (rlen == FETCH_READ_ERROR) {
475 return (-1);
476 }
477 // assert(rlen == FETCH_READ_WAIT);
478 while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
479 FD_SET(conn->sd, &readfds);
480 gettimeofday(&now, NULL);
481 delta.tv_sec = timeout.tv_sec - now.tv_sec;
482 delta.tv_usec = timeout.tv_usec - now.tv_usec;
483 if (delta.tv_usec < 0) {
484 delta.tv_usec += 1000000;
485 delta.tv_sec--;
486 }
487 if (delta.tv_sec < 0) {
488 errno = ETIMEDOUT;
489 fetch_syserr();
490 return (-1);
491 }
492 errno = 0;
493 r = select(conn->sd + 1, &readfds, NULL, NULL, &delta);
494 if (r == -1) {
495 if (errno == EINTR && fetchRestartCalls)
496 continue;
497 fetch_syserr();
498 return (-1);
499 }
500 }
501 }
502 return (total);
503}
504
505
506/*
507 * Read a line of text from a connection w/ timeout
508 */
509#define MIN_BUF_SIZE 1024
510
511int
512fetch_getln(conn_t *conn)
513{
514 char *tmp;
515 size_t tmpsize;
516 ssize_t len;
517 char c;
518
519 if (conn->buf == NULL) {
520 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
521 errno = ENOMEM;
522 return (-1);
523 }
524 conn->bufsize = MIN_BUF_SIZE;
525 }
526
527 conn->buf[0] = '\0';
528 conn->buflen = 0;
529
530 do {
531 len = fetch_read(conn, &c, 1);
532 if (len == -1)
533 return (-1);
534 if (len == 0)
535 break;
536 conn->buf[conn->buflen++] = c;
537 if (conn->buflen == conn->bufsize) {
538 tmp = conn->buf;
539 tmpsize = conn->bufsize * 2 + 1;
540 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
541 errno = ENOMEM;
542 return (-1);
543 }
544 conn->buf = tmp;
545 conn->bufsize = tmpsize;
546 }
547 } while (c != '\n');
548
549 conn->buf[conn->buflen] = '\0';
550 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
551 return (0);
552}
553
554
555/*
556 * Write to a connection w/ timeout
557 */
558ssize_t
559fetch_write(conn_t *conn, const char *buf, size_t len)
560{
561 struct iovec iov;
562
563 iov.iov_base = __DECONST(char *, buf);
564 iov.iov_len = len;
565 return fetch_writev(conn, &iov, 1);
566}
567
568/*
569 * Write a vector to a connection w/ timeout
570 * Note: can modify the iovec.
571 */
572ssize_t
573fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
574{
575 struct timeval now, timeout, delta;
576 fd_set writefds;
577 ssize_t wlen, total;
578 int r;
579
580 if (fetchTimeout) {
581 FD_ZERO(&writefds);
582 gettimeofday(&timeout, NULL);
583 timeout.tv_sec += fetchTimeout;
584 }
585
586 total = 0;
587 while (iovcnt > 0) {
588 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
589 FD_SET(conn->sd, &writefds);
590 gettimeofday(&now, NULL);
591 delta.tv_sec = timeout.tv_sec - now.tv_sec;
592 delta.tv_usec = timeout.tv_usec - now.tv_usec;
593 if (delta.tv_usec < 0) {
594 delta.tv_usec += 1000000;
595 delta.tv_sec--;
596 }
597 if (delta.tv_sec < 0) {
598 errno = ETIMEDOUT;
599 fetch_syserr();
600 return (-1);
601 }
602 errno = 0;
603 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
604 if (r == -1) {
605 if (errno == EINTR && fetchRestartCalls)
606 continue;
607 return (-1);
608 }
609 }
610 errno = 0;
611#ifdef WITH_SSL
612 if (conn->ssl != NULL)
613 wlen = SSL_write(conn->ssl,
614 iov->iov_base, iov->iov_len);
615 else
616#endif
617 wlen = writev(conn->sd, iov, iovcnt);
618 if (wlen == 0) {
619 /* we consider a short write a failure */
620 /* XXX perhaps we shouldn't in the SSL case */
621 errno = EPIPE;
622 fetch_syserr();
623 return (-1);
624 }
625 if (wlen < 0) {
626 if (errno == EINTR && fetchRestartCalls)
627 continue;
628 return (-1);
629 }
630 total += wlen;
631 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
632 wlen -= iov->iov_len;
633 iov++;
634 iovcnt--;
635 }
636 if (iovcnt > 0) {
637 iov->iov_len -= wlen;
638 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
639 }
640 }
641 return (total);
642}
643
644
645/*
646 * Write a line of text to a connection w/ timeout
647 */
648int
649fetch_putln(conn_t *conn, const char *str, size_t len)
650{
651 struct iovec iov[2];
652 int ret;
653
654 DEBUG(fprintf(stderr, ">>> %s\n", str));
655 iov[0].iov_base = __DECONST(char *, str);
656 iov[0].iov_len = len;
657 iov[1].iov_base = __DECONST(char *, ENDL);
658 iov[1].iov_len = sizeof(ENDL);
659 if (len == 0)
660 ret = fetch_writev(conn, &iov[1], 1);
661 else
662 ret = fetch_writev(conn, iov, 2);
663 if (ret == -1)
664 return (-1);
665 return (0);
666}
667
668
669/*
670 * Close connection
671 */
672int
673fetch_close(conn_t *conn)
674{
675 int ret;
676
677 if (--conn->ref > 0)
678 return (0);
679 ret = close(conn->sd);
680 free(conn->buf);
681 free(conn);
682 return (ret);
683}
684
685
686/*** Directory-related utility functions *************************************/
687
688int
689fetch_add_entry(struct url_ent **p, int *size, int *len,
690 const char *name, struct url_stat *us)
691{
692 struct url_ent *tmp;
693
694 if (*p == NULL) {
695 *size = 0;
696 *len = 0;
697 }
698
699 if (*len >= *size - 1) {
700 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
701 if (tmp == NULL) {
702 errno = ENOMEM;
703 fetch_syserr();
704 return (-1);
705 }
706 *size = (*size * 2 + 1);
707 *p = tmp;
708 }
709
710 tmp = *p + *len;
711 snprintf(tmp->name, PATH_MAX, "%s", name);
712 memcpy(&tmp->stat, us, sizeof(*us));
713
714 (*len)++;
715 (++tmp)->name[0] = 0;
716
717 return (0);
718}
719
720
721/*** Authentication-related utility functions ********************************/
722
723static const char *
724fetch_read_word(FILE *f)
725{
726 static char word[1024];
727
728 if (fscanf(f, " %1023s ", word) != 1)
729 return (NULL);
730 return (word);
731}
732
733/*
734 * Get authentication data for a URL from .netrc
735 */
736int
737fetch_netrc_auth(struct url *url)
738{
739 char fn[PATH_MAX];
740 const char *word;
741 char *p;
742 FILE *f;
743
744 if ((p = getenv("NETRC")) != NULL) {
745 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
746 fetch_info("$NETRC specifies a file name "
747 "longer than PATH_MAX");
748 return (-1);
749 }
750 } else {
751 if ((p = getenv("HOME")) != NULL) {
752 struct passwd *pwd;
753
754 if ((pwd = getpwuid(getuid())) == NULL ||
755 (p = pwd->pw_dir) == NULL)
756 return (-1);
757 }
758 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
759 return (-1);
760 }
761
762 if ((f = fopen(fn, "r")) == NULL)
763 return (-1);
764 while ((word = fetch_read_word(f)) != NULL) {
765 if (strcmp(word, "default") == 0) {
766 DEBUG(fetch_info("Using default .netrc settings"));
767 break;
768 }
769 if (strcmp(word, "machine") == 0 &&
770 (word = fetch_read_word(f)) != NULL &&
771 strcasecmp(word, url->host) == 0) {
772 DEBUG(fetch_info("Using .netrc settings for %s", word));
773 break;
774 }
775 }
776 if (word == NULL)
777 goto ferr;
778 while ((word = fetch_read_word(f)) != NULL) {
779 if (strcmp(word, "login") == 0) {
780 if ((word = fetch_read_word(f)) == NULL)
781 goto ferr;
782 if (snprintf(url->user, sizeof(url->user),
783 "%s", word) > (int)sizeof(url->user)) {
784 fetch_info("login name in .netrc is too long");
785 url->user[0] = '\0';
786 }
787 } else if (strcmp(word, "password") == 0) {
788 if ((word = fetch_read_word(f)) == NULL)
789 goto ferr;
790 if (snprintf(url->pwd, sizeof(url->pwd),
791 "%s", word) > (int)sizeof(url->pwd)) {
792 fetch_info("password in .netrc is too long");
793 url->pwd[0] = '\0';
794 }
795 } else if (strcmp(word, "account") == 0) {
796 if ((word = fetch_read_word(f)) == NULL)
797 goto ferr;
798 /* XXX not supported! */
799 } else {
800 break;
801 }
802 }
803 fclose(f);
804 return (0);
805 ferr:
806 fclose(f);
807 return (-1);
808}
809
810/*
811 * The no_proxy environment variable specifies a set of domains for
812 * which the proxy should not be consulted; the contents is a comma-,
813 * or space-separated list of domain names. A single asterisk will
814 * override all proxy variables and no transactions will be proxied
815 * (for compatability with lynx and curl, see the discussion at
816 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
817 */
818int
819fetch_no_proxy_match(const char *host)
820{
821 const char *no_proxy, *p, *q;
822 size_t h_len, d_len;
823
824 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
825 (no_proxy = getenv("no_proxy")) == NULL)
826 return (0);
827
828 /* asterisk matches any hostname */
829 if (strcmp(no_proxy, "*") == 0)
830 return (1);
831
832 h_len = strlen(host);
833 p = no_proxy;
834 do {
835 /* position p at the beginning of a domain suffix */
836 while (*p == ',' || isspace((unsigned char)*p))
837 p++;
838
839 /* position q at the first separator character */
840 for (q = p; *q; ++q)
841 if (*q == ',' || isspace((unsigned char)*q))
842 break;
843
844 d_len = q - p;
845 if (d_len > 0 && h_len >= d_len &&
846 strncasecmp(host + h_len - d_len,
847 p, d_len) == 0) {
848 /* domain name matches */
849 return (1);
850 }
851
852 p = q + 1;
853 } while (*q);
854
855 return (0);
856}