lock around accesses to uidinfo and varsymset
[dragonfly.git] / lib / libfetch / common.c
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  * $FreeBSD: src/lib/libfetch/common.c,v 1.50 2005/02/16 12:46:46 des Exp $
29  * $DragonFly: src/lib/libfetch/common.c,v 1.5 2008/04/02 14:46:37 joerg Exp $
30  */
31
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/time.h>
35 #include <sys/uio.h>
36 #include <netinet/in.h>
37
38 #include <errno.h>
39 #include <netdb.h>
40 #include <pwd.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #include "fetch.h"
48 #include "common.h"
49
50
51 /*** Local data **************************************************************/
52
53 /*
54  * Error messages for resolver errors
55  */
56 static struct fetcherr _netdb_errlist[] = {
57 #ifdef EAI_NODATA
58         { EAI_NODATA,   FETCH_RESOLV,   "Host not found" },
59 #endif
60         { EAI_AGAIN,    FETCH_TEMP,     "Transient resolver failure" },
61         { EAI_FAIL,     FETCH_RESOLV,   "Non-recoverable resolver failure" },
62         { EAI_NONAME,   FETCH_RESOLV,   "No address record" },
63         { -1,           FETCH_UNKNOWN,  "Unknown resolver error" }
64 };
65
66 /* End-of-Line */
67 static const char ENDL[2] = "\r\n";
68
69
70 /*** Error-reporting functions ***********************************************/
71
72 /*
73  * Map error code to string
74  */
75 static struct fetcherr *
76 _fetch_finderr(struct fetcherr *p, int e)
77 {
78         while (p->num != -1 && p->num != e)
79                 p++;
80         return (p);
81 }
82
83 /*
84  * Set error code
85  */
86 void
87 _fetch_seterr(struct fetcherr *p, int e)
88 {
89         p = _fetch_finderr(p, e);
90         fetchLastErrCode = p->cat;
91         snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
92 }
93
94 /*
95  * Set error code according to errno
96  */
97 void
98 _fetch_syserr(void)
99 {
100         switch (errno) {
101         case 0:
102                 fetchLastErrCode = FETCH_OK;
103                 break;
104         case EPERM:
105         case EACCES:
106         case EROFS:
107         case EAUTH:
108         case ENEEDAUTH:
109                 fetchLastErrCode = FETCH_AUTH;
110                 break;
111         case ENOENT:
112         case EISDIR: /* XXX */
113                 fetchLastErrCode = FETCH_UNAVAIL;
114                 break;
115         case ENOMEM:
116                 fetchLastErrCode = FETCH_MEMORY;
117                 break;
118         case EBUSY:
119         case EAGAIN:
120                 fetchLastErrCode = FETCH_TEMP;
121                 break;
122         case EEXIST:
123                 fetchLastErrCode = FETCH_EXISTS;
124                 break;
125         case ENOSPC:
126                 fetchLastErrCode = FETCH_FULL;
127                 break;
128         case EADDRINUSE:
129         case EADDRNOTAVAIL:
130         case ENETDOWN:
131         case ENETUNREACH:
132         case ENETRESET:
133         case EHOSTUNREACH:
134                 fetchLastErrCode = FETCH_NETWORK;
135                 break;
136         case ECONNABORTED:
137         case ECONNRESET:
138                 fetchLastErrCode = FETCH_ABORT;
139                 break;
140         case ETIMEDOUT:
141                 fetchLastErrCode = FETCH_TIMEOUT;
142                 break;
143         case ECONNREFUSED:
144         case EHOSTDOWN:
145                 fetchLastErrCode = FETCH_DOWN;
146                 break;
147 default:
148                 fetchLastErrCode = FETCH_UNKNOWN;
149         }
150         snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
151 }
152
153
154 /*
155  * Emit status message
156  */
157 void
158 _fetch_info(const char *fmt, ...)
159 {
160         va_list ap;
161
162         va_start(ap, fmt);
163         vfprintf(stderr, fmt, ap);
164         va_end(ap);
165         fputc('\n', stderr);
166 }
167
168
169 /*** Network-related utility functions ***************************************/
170
171 /*
172  * Return the default port for a scheme
173  */
174 int
175 _fetch_default_port(const char *scheme)
176 {
177         struct servent *se;
178
179         if ((se = getservbyname(scheme, "tcp")) != NULL)
180                 return (ntohs(se->s_port));
181         if (strcasecmp(scheme, SCHEME_FTP) == 0)
182                 return (FTP_DEFAULT_PORT);
183         if (strcasecmp(scheme, SCHEME_HTTP) == 0)
184                 return (HTTP_DEFAULT_PORT);
185         return (0);
186 }
187
188 /*
189  * Return the default proxy port for a scheme
190  */
191 int
192 _fetch_default_proxy_port(const char *scheme)
193 {
194         if (strcasecmp(scheme, SCHEME_FTP) == 0)
195                 return (FTP_DEFAULT_PROXY_PORT);
196         if (strcasecmp(scheme, SCHEME_HTTP) == 0)
197                 return (HTTP_DEFAULT_PROXY_PORT);
198         return (0);
199 }
200
201
202 /*
203  * Create a connection for an existing descriptor.
204  */
205 conn_t *
206 _fetch_reopen(int sd)
207 {
208         conn_t *conn;
209
210         /* allocate and fill connection structure */
211         if ((conn = calloc(1, sizeof(*conn))) == NULL)
212                 return (NULL);
213         conn->sd = sd;
214         ++conn->ref;
215         return (conn);
216 }
217
218
219 /*
220  * Bump a connection's reference count.
221  */
222 conn_t *
223 _fetch_ref(conn_t *conn)
224 {
225
226         ++conn->ref;
227         return (conn);
228 }
229
230
231 /*
232  * Bind a socket to a specific local address
233  */
234 int
235 _fetch_bind(int sd, int af, const char *addr)
236 {
237         struct addrinfo hints, *res, *res0;
238         int err;
239
240         memset(&hints, 0, sizeof(hints));
241         hints.ai_family = af;
242         hints.ai_socktype = SOCK_STREAM;
243         hints.ai_protocol = 0;
244         if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
245                 return (-1);
246         for (res = res0; res; res = res->ai_next)
247                 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
248                         return (0);
249         return (-1);
250 }
251
252
253 /*
254  * Establish a TCP connection to the specified port on the specified host.
255  */
256 conn_t *
257 _fetch_connect(const char *host, int port, int af, int verbose)
258 {
259         conn_t *conn;
260         char pbuf[10];
261         const char *bindaddr;
262         struct addrinfo hints, *res, *res0;
263         int sd, err;
264
265         DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
266
267         if (verbose)
268                 _fetch_info("looking up %s", host);
269
270         /* look up host name and set up socket address structure */
271         snprintf(pbuf, sizeof(pbuf), "%d", port);
272         memset(&hints, 0, sizeof(hints));
273         hints.ai_family = af;
274         hints.ai_socktype = SOCK_STREAM;
275         hints.ai_protocol = 0;
276         if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
277                 _netdb_seterr(err);
278                 return (NULL);
279         }
280         bindaddr = getenv("FETCH_BIND_ADDRESS");
281
282         if (verbose)
283                 _fetch_info("connecting to %s:%d", host, port);
284
285         /* try to connect */
286         for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
287                 if ((sd = socket(res->ai_family, res->ai_socktype,
288                          res->ai_protocol)) == -1)
289                         continue;
290                 if (bindaddr != NULL && *bindaddr != '\0' &&
291                     _fetch_bind(sd, res->ai_family, bindaddr) != 0) {
292                         _fetch_info("failed to bind to '%s'", bindaddr);
293                         close(sd);
294                         continue;
295                 }
296                 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0)
297                         break;
298                 close(sd);
299         }
300         freeaddrinfo(res0);
301         if (sd == -1) {
302                 _fetch_syserr();
303                 return (NULL);
304         }
305
306         if ((conn = _fetch_reopen(sd)) == NULL) {
307                 _fetch_syserr();
308                 close(sd);
309         }
310         return (conn);
311 }
312
313
314 /*
315  * Enable SSL on a connection.
316  */
317 int
318 _fetch_ssl(conn_t *conn, int verbose)
319 {
320
321 #ifdef WITH_SSL
322         /* Init the SSL library and context */
323         if (!SSL_library_init()){
324                 fprintf(stderr, "SSL library init failed\n");
325                 return (-1);
326         }
327
328         SSL_load_error_strings();
329
330         conn->ssl_meth = SSLv23_client_method();
331         conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
332         SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
333
334         conn->ssl = SSL_new(conn->ssl_ctx);
335         if (conn->ssl == NULL){
336                 fprintf(stderr, "SSL context creation failed\n");
337                 return (-1);
338         }
339         SSL_set_fd(conn->ssl, conn->sd);
340         if (SSL_connect(conn->ssl) == -1){
341                 ERR_print_errors_fp(stderr);
342                 return (-1);
343         }
344
345         if (verbose) {
346                 X509_NAME *name;
347                 char *str;
348
349                 fprintf(stderr, "SSL connection established using %s\n",
350                     SSL_get_cipher(conn->ssl));
351                 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
352                 name = X509_get_subject_name(conn->ssl_cert);
353                 str = X509_NAME_oneline(name, 0, 0);
354                 printf("Certificate subject: %s\n", str);
355                 free(str);
356                 name = X509_get_issuer_name(conn->ssl_cert);
357                 str = X509_NAME_oneline(name, 0, 0);
358                 printf("Certificate issuer: %s\n", str);
359                 free(str);
360         }
361
362         return (0);
363 #else
364         (void)conn;
365         (void)verbose;
366         fprintf(stderr, "SSL support disabled\n");
367         return (-1);
368 #endif
369 }
370
371
372 /*
373  * Read a character from a connection w/ timeout
374  */
375 ssize_t
376 _fetch_read(conn_t *conn, char *buf, size_t len)
377 {
378         struct timeval now, timeout, wait;
379         fd_set readfds;
380         ssize_t rlen, total;
381         int r;
382
383         if (fetchTimeout) {
384                 FD_ZERO(&readfds);
385                 gettimeofday(&timeout, NULL);
386                 timeout.tv_sec += fetchTimeout;
387         }
388
389         total = 0;
390         while (len > 0) {
391                 while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
392                         FD_SET(conn->sd, &readfds);
393                         gettimeofday(&now, NULL);
394                         wait.tv_sec = timeout.tv_sec - now.tv_sec;
395                         wait.tv_usec = timeout.tv_usec - now.tv_usec;
396                         if (wait.tv_usec < 0) {
397                                 wait.tv_usec += 1000000;
398                                 wait.tv_sec--;
399                         }
400                         if (wait.tv_sec < 0) {
401                                 errno = ETIMEDOUT;
402                                 _fetch_syserr();
403                                 return (-1);
404                         }
405                         errno = 0;
406                         r = select(conn->sd + 1, &readfds, NULL, NULL, &wait);
407                         if (r == -1) {
408                                 if (errno == EINTR && fetchRestartCalls)
409                                         continue;
410                                 _fetch_syserr();
411                                 return (-1);
412                         }
413                 }
414 #ifdef WITH_SSL
415                 if (conn->ssl != NULL)
416                         rlen = SSL_read(conn->ssl, buf, len);
417                 else
418 #endif
419                         rlen = read(conn->sd, buf, len);
420                 if (rlen == 0)
421                         break;
422                 if (rlen < 0) {
423                         if (errno == EINTR && fetchRestartCalls)
424                                 continue;
425                         return (-1);
426                 }
427                 len -= rlen;
428                 buf += rlen;
429                 total += rlen;
430         }
431         return (total);
432 }
433
434
435 /*
436  * Read a line of text from a connection w/ timeout
437  */
438 #define MIN_BUF_SIZE 1024
439
440 int
441 _fetch_getln(conn_t *conn)
442 {
443         char *tmp;
444         size_t tmpsize;
445         ssize_t len;
446         char c;
447
448         if (conn->buf == NULL) {
449                 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
450                         errno = ENOMEM;
451                         return (-1);
452                 }
453                 conn->bufsize = MIN_BUF_SIZE;
454         }
455
456         conn->buf[0] = '\0';
457         conn->buflen = 0;
458
459         do {
460                 len = _fetch_read(conn, &c, 1);
461                 if (len == -1)
462                         return (-1);
463                 if (len == 0)
464                         break;
465                 conn->buf[conn->buflen++] = c;
466                 if (conn->buflen == conn->bufsize) {
467                         tmp = conn->buf;
468                         tmpsize = conn->bufsize * 2 + 1;
469                         if ((tmp = realloc(tmp, tmpsize)) == NULL) {
470                                 errno = ENOMEM;
471                                 return (-1);
472                         }
473                         conn->buf = tmp;
474                         conn->bufsize = tmpsize;
475                 }
476         } while (c != '\n');
477
478         conn->buf[conn->buflen] = '\0';
479         DEBUG(fprintf(stderr, "<<< %s", conn->buf));
480         return (0);
481 }
482
483
484 /*
485  * Write to a connection w/ timeout
486  */
487 ssize_t
488 _fetch_write(conn_t *conn, const char *buf, size_t len)
489 {
490         struct iovec iov;
491
492         iov.iov_base = __DECONST(char *, buf);
493         iov.iov_len = len;
494         return _fetch_writev(conn, &iov, 1);
495 }
496
497 /*
498  * Write a vector to a connection w/ timeout
499  * Note: can modify the iovec.
500  */
501 ssize_t
502 _fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
503 {
504         struct timeval now, timeout, wait;
505         fd_set writefds;
506         ssize_t wlen, total;
507         int r;
508
509         if (fetchTimeout) {
510                 FD_ZERO(&writefds);
511                 gettimeofday(&timeout, NULL);
512                 timeout.tv_sec += fetchTimeout;
513         }
514
515         total = 0;
516         while (iovcnt > 0) {
517                 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
518                         FD_SET(conn->sd, &writefds);
519                         gettimeofday(&now, NULL);
520                         wait.tv_sec = timeout.tv_sec - now.tv_sec;
521                         wait.tv_usec = timeout.tv_usec - now.tv_usec;
522                         if (wait.tv_usec < 0) {
523                                 wait.tv_usec += 1000000;
524                                 wait.tv_sec--;
525                         }
526                         if (wait.tv_sec < 0) {
527                                 errno = ETIMEDOUT;
528                                 _fetch_syserr();
529                                 return (-1);
530                         }
531                         errno = 0;
532                         r = select(conn->sd + 1, NULL, &writefds, NULL, &wait);
533                         if (r == -1) {
534                                 if (errno == EINTR && fetchRestartCalls)
535                                         continue;
536                                 return (-1);
537                         }
538                 }
539                 errno = 0;
540 #ifdef WITH_SSL
541                 if (conn->ssl != NULL)
542                         wlen = SSL_write(conn->ssl,
543                             iov->iov_base, iov->iov_len);
544                 else
545 #endif
546                         wlen = writev(conn->sd, iov, iovcnt);
547                 if (wlen == 0) {
548                         /* we consider a short write a failure */
549                         errno = EPIPE;
550                         _fetch_syserr();
551                         return (-1);
552                 }
553                 if (wlen < 0) {
554                         if (errno == EINTR && fetchRestartCalls)
555                                 continue;
556                         return (-1);
557                 }
558                 total += wlen;
559                 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
560                         wlen -= iov->iov_len;
561                         iov++;
562                         iovcnt--;
563                 }
564                 if (iovcnt > 0) {
565                         iov->iov_len -= wlen;
566                         iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
567                 }
568         }
569         return (total);
570 }
571
572
573 /*
574  * Write a line of text to a connection w/ timeout
575  */
576 int
577 _fetch_putln(conn_t *conn, const char *str, size_t len)
578 {
579         struct iovec iov[2];
580         int ret;
581
582         DEBUG(fprintf(stderr, ">>> %s\n", str));
583         iov[0].iov_base = __DECONST(char *, str);
584         iov[0].iov_len = len;
585         iov[1].iov_base = __DECONST(char *, ENDL);
586         iov[1].iov_len = sizeof(ENDL);
587         if (len == 0)
588                 ret = _fetch_writev(conn, &iov[1], 1);
589         else
590                 ret = _fetch_writev(conn, iov, 2);
591         if (ret == -1)
592                 return (-1);
593         return (0);
594 }
595
596
597 /*
598  * Close connection
599  */
600 int
601 _fetch_close(conn_t *conn)
602 {
603         int ret;
604
605         if (--conn->ref > 0)
606                 return (0);
607         ret = close(conn->sd);
608         free(conn->buf);
609         free(conn);
610         return (ret);
611 }
612
613
614 /*** Directory-related utility functions *************************************/
615
616 int
617 _fetch_add_entry(struct url_ent **p, int *size, int *len,
618     const char *name, struct url_stat *us)
619 {
620         struct url_ent *tmp;
621
622         if (*p == NULL) {
623                 *size = 0;
624                 *len = 0;
625         }
626
627         if (*len >= *size - 1) {
628                 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
629                 if (tmp == NULL) {
630                         errno = ENOMEM;
631                         _fetch_syserr();
632                         return (-1);
633                 }
634                 *size = (*size * 2 + 1);
635                 *p = tmp;
636         }
637
638         tmp = *p + *len;
639         snprintf(tmp->name, PATH_MAX, "%s", name);
640         bcopy(us, &tmp->stat, sizeof(*us));
641
642         (*len)++;
643         (++tmp)->name[0] = 0;
644
645         return (0);
646 }
647
648
649 /*** Authentication-related utility functions ********************************/
650
651 static const char *
652 _fetch_read_word(FILE *f)
653 {
654         static char word[1024];
655
656         if (fscanf(f, " %1023s ", word) != 1)
657                 return (NULL);
658         return (word);
659 }
660
661 /*
662  * Get authentication data for a URL from .netrc
663  */
664 int
665 _fetch_netrc_auth(struct url *url)
666 {
667         char fn[PATH_MAX];
668         const char *word;
669         char *p;
670         FILE *f;
671
672         if ((p = getenv("NETRC")) != NULL) {
673                 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
674                         _fetch_info("$NETRC specifies a file name "
675                             "longer than PATH_MAX");
676                         return (-1);
677                 }
678         } else {
679                 if ((p = getenv("HOME")) != NULL) {
680                         struct passwd *pwd;
681
682                         if ((pwd = getpwuid(getuid())) == NULL ||
683                             (p = pwd->pw_dir) == NULL)
684                                 return (-1);
685                 }
686                 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
687                         return (-1);
688         }
689
690         if ((f = fopen(fn, "r")) == NULL)
691                 return (-1);
692         while ((word = _fetch_read_word(f)) != NULL) {
693                 if (strcmp(word, "default") == 0) {
694                         DEBUG(_fetch_info("Using default .netrc settings"));
695                         break;
696                 }
697                 if (strcmp(word, "machine") == 0 &&
698                     (word = _fetch_read_word(f)) != NULL &&
699                     strcasecmp(word, url->host) == 0) {
700                         DEBUG(_fetch_info("Using .netrc settings for %s", word));
701                         break;
702                 }
703         }
704         if (word == NULL)
705                 goto ferr;
706         while ((word = _fetch_read_word(f)) != NULL) {
707                 if (strcmp(word, "login") == 0) {
708                         if ((word = _fetch_read_word(f)) == NULL)
709                                 goto ferr;
710                         if (snprintf(url->user, sizeof(url->user),
711                                 "%s", word) > (int)sizeof(url->user)) {
712                                 _fetch_info("login name in .netrc is too long");
713                                 url->user[0] = '\0';
714                         }
715                 } else if (strcmp(word, "password") == 0) {
716                         if ((word = _fetch_read_word(f)) == NULL)
717                                 goto ferr;
718                         if (snprintf(url->pwd, sizeof(url->pwd),
719                                 "%s", word) > (int)sizeof(url->pwd)) {
720                                 _fetch_info("password in .netrc is too long");
721                                 url->pwd[0] = '\0';
722                         }
723                 } else if (strcmp(word, "account") == 0) {
724                         if ((word = _fetch_read_word(f)) == NULL)
725                                 goto ferr;
726                         /* XXX not supported! */
727                 } else {
728                         break;
729                 }
730         }
731         fclose(f);
732         return (0);
733  ferr:
734         fclose(f);
735         return (-1);
736 }