]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - lib/libfetch/common.c
MFH r225813, r233648: man page fixes
[FreeBSD/stable/8.git] / lib / libfetch / common.c
1 /*-
2  * Copyright (c) 1998-2011 Dag-Erling 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$");
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  */
59 static 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 */
70 static const char ENDL[2] = "\r\n";
71
72
73 /*** Error-reporting functions ***********************************************/
74
75 /*
76  * Map error code to string
77  */
78 static struct fetcherr *
79 fetch_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  */
89 void
90 fetch_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  */
100 void
101 fetch_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;
150 default:
151                 fetchLastErrCode = FETCH_UNKNOWN;
152         }
153         snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
154 }
155
156
157 /*
158  * Emit status message
159  */
160 void
161 fetch_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  */
177 int
178 fetch_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  */
194 int
195 fetch_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  */
208 conn_t *
209 fetch_reopen(int sd)
210 {
211         conn_t *conn;
212         int opt = 1;
213
214         /* allocate and fill connection structure */
215         if ((conn = calloc(1, sizeof(*conn))) == NULL)
216                 return (NULL);
217         fcntl(sd, F_SETFD, FD_CLOEXEC);
218         setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
219         conn->sd = sd;
220         ++conn->ref;
221         return (conn);
222 }
223
224
225 /*
226  * Bump a connection's reference count.
227  */
228 conn_t *
229 fetch_ref(conn_t *conn)
230 {
231
232         ++conn->ref;
233         return (conn);
234 }
235
236
237 /*
238  * Bind a socket to a specific local address
239  */
240 int
241 fetch_bind(int sd, int af, const char *addr)
242 {
243         struct addrinfo hints, *res, *res0;
244         int err;
245
246         memset(&hints, 0, sizeof(hints));
247         hints.ai_family = af;
248         hints.ai_socktype = SOCK_STREAM;
249         hints.ai_protocol = 0;
250         if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
251                 return (-1);
252         for (res = res0; res; res = res->ai_next)
253                 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
254                         return (0);
255         return (-1);
256 }
257
258
259 /*
260  * Establish a TCP connection to the specified port on the specified host.
261  */
262 conn_t *
263 fetch_connect(const char *host, int port, int af, int verbose)
264 {
265         conn_t *conn;
266         char pbuf[10];
267         const char *bindaddr;
268         struct addrinfo hints, *res, *res0;
269         int sd, err;
270
271         DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
272
273         if (verbose)
274                 fetch_info("looking up %s", host);
275
276         /* look up host name and set up socket address structure */
277         snprintf(pbuf, sizeof(pbuf), "%d", port);
278         memset(&hints, 0, sizeof(hints));
279         hints.ai_family = af;
280         hints.ai_socktype = SOCK_STREAM;
281         hints.ai_protocol = 0;
282         if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
283                 netdb_seterr(err);
284                 return (NULL);
285         }
286         bindaddr = getenv("FETCH_BIND_ADDRESS");
287
288         if (verbose)
289                 fetch_info("connecting to %s:%d", host, port);
290
291         /* try to connect */
292         for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
293                 if ((sd = socket(res->ai_family, res->ai_socktype,
294                          res->ai_protocol)) == -1)
295                         continue;
296                 if (bindaddr != NULL && *bindaddr != '\0' &&
297                     fetch_bind(sd, res->ai_family, bindaddr) != 0) {
298                         fetch_info("failed to bind to '%s'", bindaddr);
299                         close(sd);
300                         continue;
301                 }
302                 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
303                     fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
304                         break;
305                 close(sd);
306         }
307         freeaddrinfo(res0);
308         if (sd == -1) {
309                 fetch_syserr();
310                 return (NULL);
311         }
312
313         if ((conn = fetch_reopen(sd)) == NULL) {
314                 fetch_syserr();
315                 close(sd);
316         }
317         return (conn);
318 }
319
320
321 /*
322  * Enable SSL on a connection.
323  */
324 int
325 fetch_ssl(conn_t *conn, int verbose)
326 {
327 #ifdef WITH_SSL
328         int ret, ssl_err;
329
330         /* Init the SSL library and context */
331         if (!SSL_library_init()){
332                 fprintf(stderr, "SSL library init failed\n");
333                 return (-1);
334         }
335
336         SSL_load_error_strings();
337
338         conn->ssl_meth = SSLv23_client_method();
339         conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
340         SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
341
342         conn->ssl = SSL_new(conn->ssl_ctx);
343         if (conn->ssl == NULL){
344                 fprintf(stderr, "SSL context creation failed\n");
345                 return (-1);
346         }
347         SSL_set_fd(conn->ssl, conn->sd);
348         while ((ret = SSL_connect(conn->ssl)) == -1) {
349                 ssl_err = SSL_get_error(conn->ssl, ret);
350                 if (ssl_err != SSL_ERROR_WANT_READ &&
351                     ssl_err != SSL_ERROR_WANT_WRITE) {
352                         ERR_print_errors_fp(stderr);
353                         return (-1);
354                 }
355         }
356
357         if (verbose) {
358                 X509_NAME *name;
359                 char *str;
360
361                 fprintf(stderr, "SSL connection established using %s\n",
362                     SSL_get_cipher(conn->ssl));
363                 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
364                 name = X509_get_subject_name(conn->ssl_cert);
365                 str = X509_NAME_oneline(name, 0, 0);
366                 printf("Certificate subject: %s\n", str);
367                 free(str);
368                 name = X509_get_issuer_name(conn->ssl_cert);
369                 str = X509_NAME_oneline(name, 0, 0);
370                 printf("Certificate issuer: %s\n", str);
371                 free(str);
372         }
373
374         return (0);
375 #else
376         (void)conn;
377         (void)verbose;
378         fprintf(stderr, "SSL support disabled\n");
379         return (-1);
380 #endif
381 }
382
383 #define FETCH_READ_WAIT         -2
384 #define FETCH_READ_ERROR        -1
385 #define FETCH_READ_DONE          0
386
387 #ifdef WITH_SSL
388 static ssize_t
389 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
390 {
391         ssize_t rlen;
392         int ssl_err;
393
394         rlen = SSL_read(ssl, buf, len);
395         if (rlen < 0) {
396                 ssl_err = SSL_get_error(ssl, rlen);
397                 if (ssl_err == SSL_ERROR_WANT_READ ||
398                     ssl_err == SSL_ERROR_WANT_WRITE) {
399                         return (FETCH_READ_WAIT);
400                 } else {
401                         ERR_print_errors_fp(stderr);
402                         return (FETCH_READ_ERROR);
403                 }
404         }
405         return (rlen);
406 }
407 #endif
408
409 /*
410  * Cache some data that was read from a socket but cannot be immediately
411  * returned because of an interrupted system call.
412  */
413 static int
414 fetch_cache_data(conn_t *conn, char *src, size_t nbytes)
415 {
416         char *tmp;
417
418         if (conn->cache.size < nbytes) {
419                 tmp = realloc(conn->cache.buf, nbytes);
420                 if (tmp == NULL) {
421                         errno = ENOMEM;
422                         fetch_syserr();
423                         return (-1);
424                 }
425                 conn->cache.buf = tmp;
426                 conn->cache.size = nbytes;
427         }
428
429         memcpy(conn->cache.buf, src, nbytes);
430         conn->cache.len = nbytes;
431         conn->cache.pos = 0;
432
433         return (0);
434 }
435
436
437 static ssize_t
438 fetch_socket_read(int sd, char *buf, size_t len)
439 {
440         ssize_t rlen;
441
442         rlen = read(sd, buf, len);
443         if (rlen < 0) {
444                 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
445                         return (FETCH_READ_WAIT);
446                 else
447                         return (FETCH_READ_ERROR);
448         }
449         return (rlen);
450 }
451
452 /*
453  * Read a character from a connection w/ timeout
454  */
455 ssize_t
456 fetch_read(conn_t *conn, char *buf, size_t len)
457 {
458         struct timeval now, timeout, delta;
459         fd_set readfds;
460         ssize_t rlen, total;
461         char *start;
462
463         if (fetchTimeout > 0) {
464                 gettimeofday(&timeout, NULL);
465                 timeout.tv_sec += fetchTimeout;
466         }
467
468         total = 0;
469         start = buf;
470
471         if (conn->cache.len > 0) {
472                 /*
473                  * The last invocation of fetch_read was interrupted by a
474                  * signal after some data had been read from the socket. Copy
475                  * the cached data into the supplied buffer before trying to
476                  * read from the socket again.
477                  */
478                 total = (conn->cache.len < len) ? conn->cache.len : len;
479                 memcpy(buf, conn->cache.buf, total);
480
481                 conn->cache.len -= total;
482                 conn->cache.pos += total;
483                 len -= total;
484                 buf+= total;
485         }
486
487         while (len > 0) {
488                 /*
489                  * The socket is non-blocking.  Instead of the canonical
490                  * select() -> read(), we do the following:
491                  *
492                  * 1) call read() or SSL_read().
493                  * 2) if an error occurred, return -1.
494                  * 3) if we received data but we still expect more,
495                  *    update our counters and loop.
496                  * 4) if read() or SSL_read() signaled EOF, return.
497                  * 5) if we did not receive any data but we're not at EOF,
498                  *    call select().
499                  *
500                  * In the SSL case, this is necessary because if we
501                  * receive a close notification, we have to call
502                  * SSL_read() one additional time after we've read
503                  * everything we received.
504                  *
505                  * In the non-SSL case, it may improve performance (very
506                  * slightly) when reading small amounts of data.
507                  */
508 #ifdef WITH_SSL
509                 if (conn->ssl != NULL)
510                         rlen = fetch_ssl_read(conn->ssl, buf, len);
511                 else
512 #endif
513                         rlen = fetch_socket_read(conn->sd, buf, len);
514                 if (rlen == 0) {
515                         break;
516                 } else if (rlen > 0) {
517                         len -= rlen;
518                         buf += rlen;
519                         total += rlen;
520                         continue;
521                 } else if (rlen == FETCH_READ_ERROR) {
522                         if (errno == EINTR)
523                                 fetch_cache_data(conn, start, total);
524                         return (-1);
525                 }
526                 // assert(rlen == FETCH_READ_WAIT);
527                 FD_ZERO(&readfds);
528                 while (!FD_ISSET(conn->sd, &readfds)) {
529                         FD_SET(conn->sd, &readfds);
530                         if (fetchTimeout > 0) {
531                                 gettimeofday(&now, NULL);
532                                 if (!timercmp(&timeout, &now, >)) {
533                                         errno = ETIMEDOUT;
534                                         fetch_syserr();
535                                         return (-1);
536                                 }
537                                 timersub(&timeout, &now, &delta);
538                         }
539                         errno = 0;
540                         if (select(conn->sd + 1, &readfds, NULL, NULL,
541                                 fetchTimeout > 0 ? &delta : NULL) < 0) {
542                                 if (errno == EINTR) {
543                                         if (fetchRestartCalls)
544                                                 continue;
545                                         /* Save anything that was read. */
546                                         fetch_cache_data(conn, start, total);
547                                 }
548                                 fetch_syserr();
549                                 return (-1);
550                         }
551                 }
552         }
553         return (total);
554 }
555
556
557 /*
558  * Read a line of text from a connection w/ timeout
559  */
560 #define MIN_BUF_SIZE 1024
561
562 int
563 fetch_getln(conn_t *conn)
564 {
565         char *tmp;
566         size_t tmpsize;
567         ssize_t len;
568         char c;
569
570         if (conn->buf == NULL) {
571                 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
572                         errno = ENOMEM;
573                         return (-1);
574                 }
575                 conn->bufsize = MIN_BUF_SIZE;
576         }
577
578         conn->buf[0] = '\0';
579         conn->buflen = 0;
580
581         do {
582                 len = fetch_read(conn, &c, 1);
583                 if (len == -1)
584                         return (-1);
585                 if (len == 0)
586                         break;
587                 conn->buf[conn->buflen++] = c;
588                 if (conn->buflen == conn->bufsize) {
589                         tmp = conn->buf;
590                         tmpsize = conn->bufsize * 2 + 1;
591                         if ((tmp = realloc(tmp, tmpsize)) == NULL) {
592                                 errno = ENOMEM;
593                                 return (-1);
594                         }
595                         conn->buf = tmp;
596                         conn->bufsize = tmpsize;
597                 }
598         } while (c != '\n');
599
600         conn->buf[conn->buflen] = '\0';
601         DEBUG(fprintf(stderr, "<<< %s", conn->buf));
602         return (0);
603 }
604
605
606 /*
607  * Write to a connection w/ timeout
608  */
609 ssize_t
610 fetch_write(conn_t *conn, const char *buf, size_t len)
611 {
612         struct iovec iov;
613
614         iov.iov_base = __DECONST(char *, buf);
615         iov.iov_len = len;
616         return fetch_writev(conn, &iov, 1);
617 }
618
619 /*
620  * Write a vector to a connection w/ timeout
621  * Note: can modify the iovec.
622  */
623 ssize_t
624 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
625 {
626         struct timeval now, timeout, delta;
627         fd_set writefds;
628         ssize_t wlen, total;
629         int r;
630
631         if (fetchTimeout) {
632                 FD_ZERO(&writefds);
633                 gettimeofday(&timeout, NULL);
634                 timeout.tv_sec += fetchTimeout;
635         }
636
637         total = 0;
638         while (iovcnt > 0) {
639                 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
640                         FD_SET(conn->sd, &writefds);
641                         gettimeofday(&now, NULL);
642                         delta.tv_sec = timeout.tv_sec - now.tv_sec;
643                         delta.tv_usec = timeout.tv_usec - now.tv_usec;
644                         if (delta.tv_usec < 0) {
645                                 delta.tv_usec += 1000000;
646                                 delta.tv_sec--;
647                         }
648                         if (delta.tv_sec < 0) {
649                                 errno = ETIMEDOUT;
650                                 fetch_syserr();
651                                 return (-1);
652                         }
653                         errno = 0;
654                         r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
655                         if (r == -1) {
656                                 if (errno == EINTR && fetchRestartCalls)
657                                         continue;
658                                 return (-1);
659                         }
660                 }
661                 errno = 0;
662 #ifdef WITH_SSL
663                 if (conn->ssl != NULL)
664                         wlen = SSL_write(conn->ssl,
665                             iov->iov_base, iov->iov_len);
666                 else
667 #endif
668                         wlen = writev(conn->sd, iov, iovcnt);
669                 if (wlen == 0) {
670                         /* we consider a short write a failure */
671                         /* XXX perhaps we shouldn't in the SSL case */
672                         errno = EPIPE;
673                         fetch_syserr();
674                         return (-1);
675                 }
676                 if (wlen < 0) {
677                         if (errno == EINTR && fetchRestartCalls)
678                                 continue;
679                         return (-1);
680                 }
681                 total += wlen;
682                 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
683                         wlen -= iov->iov_len;
684                         iov++;
685                         iovcnt--;
686                 }
687                 if (iovcnt > 0) {
688                         iov->iov_len -= wlen;
689                         iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
690                 }
691         }
692         return (total);
693 }
694
695
696 /*
697  * Write a line of text to a connection w/ timeout
698  */
699 int
700 fetch_putln(conn_t *conn, const char *str, size_t len)
701 {
702         struct iovec iov[2];
703         int ret;
704
705         DEBUG(fprintf(stderr, ">>> %s\n", str));
706         iov[0].iov_base = __DECONST(char *, str);
707         iov[0].iov_len = len;
708         iov[1].iov_base = __DECONST(char *, ENDL);
709         iov[1].iov_len = sizeof(ENDL);
710         if (len == 0)
711                 ret = fetch_writev(conn, &iov[1], 1);
712         else
713                 ret = fetch_writev(conn, iov, 2);
714         if (ret == -1)
715                 return (-1);
716         return (0);
717 }
718
719
720 /*
721  * Close connection
722  */
723 int
724 fetch_close(conn_t *conn)
725 {
726         int ret;
727
728         if (--conn->ref > 0)
729                 return (0);
730         ret = close(conn->sd);
731         free(conn->cache.buf);
732         free(conn->buf);
733         free(conn);
734         return (ret);
735 }
736
737
738 /*** Directory-related utility functions *************************************/
739
740 int
741 fetch_add_entry(struct url_ent **p, int *size, int *len,
742     const char *name, struct url_stat *us)
743 {
744         struct url_ent *tmp;
745
746         if (*p == NULL) {
747                 *size = 0;
748                 *len = 0;
749         }
750
751         if (*len >= *size - 1) {
752                 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
753                 if (tmp == NULL) {
754                         errno = ENOMEM;
755                         fetch_syserr();
756                         return (-1);
757                 }
758                 *size = (*size * 2 + 1);
759                 *p = tmp;
760         }
761
762         tmp = *p + *len;
763         snprintf(tmp->name, PATH_MAX, "%s", name);
764         memcpy(&tmp->stat, us, sizeof(*us));
765
766         (*len)++;
767         (++tmp)->name[0] = 0;
768
769         return (0);
770 }
771
772
773 /*** Authentication-related utility functions ********************************/
774
775 static const char *
776 fetch_read_word(FILE *f)
777 {
778         static char word[1024];
779
780         if (fscanf(f, " %1023s ", word) != 1)
781                 return (NULL);
782         return (word);
783 }
784
785 /*
786  * Get authentication data for a URL from .netrc
787  */
788 int
789 fetch_netrc_auth(struct url *url)
790 {
791         char fn[PATH_MAX];
792         const char *word;
793         char *p;
794         FILE *f;
795
796         if ((p = getenv("NETRC")) != NULL) {
797                 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
798                         fetch_info("$NETRC specifies a file name "
799                             "longer than PATH_MAX");
800                         return (-1);
801                 }
802         } else {
803                 if ((p = getenv("HOME")) != NULL) {
804                         struct passwd *pwd;
805
806                         if ((pwd = getpwuid(getuid())) == NULL ||
807                             (p = pwd->pw_dir) == NULL)
808                                 return (-1);
809                 }
810                 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
811                         return (-1);
812         }
813
814         if ((f = fopen(fn, "r")) == NULL)
815                 return (-1);
816         while ((word = fetch_read_word(f)) != NULL) {
817                 if (strcmp(word, "default") == 0) {
818                         DEBUG(fetch_info("Using default .netrc settings"));
819                         break;
820                 }
821                 if (strcmp(word, "machine") == 0 &&
822                     (word = fetch_read_word(f)) != NULL &&
823                     strcasecmp(word, url->host) == 0) {
824                         DEBUG(fetch_info("Using .netrc settings for %s", word));
825                         break;
826                 }
827         }
828         if (word == NULL)
829                 goto ferr;
830         while ((word = fetch_read_word(f)) != NULL) {
831                 if (strcmp(word, "login") == 0) {
832                         if ((word = fetch_read_word(f)) == NULL)
833                                 goto ferr;
834                         if (snprintf(url->user, sizeof(url->user),
835                                 "%s", word) > (int)sizeof(url->user)) {
836                                 fetch_info("login name in .netrc is too long");
837                                 url->user[0] = '\0';
838                         }
839                 } else if (strcmp(word, "password") == 0) {
840                         if ((word = fetch_read_word(f)) == NULL)
841                                 goto ferr;
842                         if (snprintf(url->pwd, sizeof(url->pwd),
843                                 "%s", word) > (int)sizeof(url->pwd)) {
844                                 fetch_info("password in .netrc is too long");
845                                 url->pwd[0] = '\0';
846                         }
847                 } else if (strcmp(word, "account") == 0) {
848                         if ((word = fetch_read_word(f)) == NULL)
849                                 goto ferr;
850                         /* XXX not supported! */
851                 } else {
852                         break;
853                 }
854         }
855         fclose(f);
856         return (0);
857  ferr:
858         fclose(f);
859         return (-1);
860 }
861
862 /*
863  * The no_proxy environment variable specifies a set of domains for
864  * which the proxy should not be consulted; the contents is a comma-,
865  * or space-separated list of domain names.  A single asterisk will
866  * override all proxy variables and no transactions will be proxied
867  * (for compatability with lynx and curl, see the discussion at
868  * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
869  */
870 int
871 fetch_no_proxy_match(const char *host)
872 {
873         const char *no_proxy, *p, *q;
874         size_t h_len, d_len;
875
876         if ((no_proxy = getenv("NO_PROXY")) == NULL &&
877             (no_proxy = getenv("no_proxy")) == NULL)
878                 return (0);
879
880         /* asterisk matches any hostname */
881         if (strcmp(no_proxy, "*") == 0)
882                 return (1);
883
884         h_len = strlen(host);
885         p = no_proxy;
886         do {
887                 /* position p at the beginning of a domain suffix */
888                 while (*p == ',' || isspace((unsigned char)*p))
889                         p++;
890
891                 /* position q at the first separator character */
892                 for (q = p; *q; ++q)
893                         if (*q == ',' || isspace((unsigned char)*q))
894                                 break;
895
896                 d_len = q - p;
897                 if (d_len > 0 && h_len >= d_len &&
898                     strncasecmp(host + h_len - d_len,
899                         p, d_len) == 0) {
900                         /* domain name matches */
901                         return (1);
902                 }
903
904                 p = q + 1;
905         } while (*q);
906
907         return (0);
908 }