common.c revision 62911
1/*-
2 * Copyright (c) 1998 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: head/lib/libfetch/common.c 62911 2000-07-10 16:28:28Z ume $
29 */
30
31#include <sys/param.h>
32#include <sys/socket.h>
33#include <sys/time.h>
34#include <netinet/in.h>
35
36#include <errno.h>
37#include <netdb.h>
38#include <stdarg.h>
39#include <stdlib.h>
40#include <stdio.h>
41#include <string.h>
42#include <unistd.h>
43
44#include "fetch.h"
45#include "common.h"
46
47
48/*** Local data **************************************************************/
49
50/*
51 * Error messages for resolver errors
52 */
53static struct fetcherr _netdb_errlist[] = {
54    { EAI_NODATA,	FETCH_RESOLV,	"Host not found" },
55    { EAI_AGAIN,	FETCH_TEMP,	"Transient resolver failure" },
56    { EAI_FAIL,		FETCH_RESOLV,	"Non-recoverable resolver failure" },
57    { EAI_NONAME,	FETCH_RESOLV,	"No address record" },
58    { -1,		FETCH_UNKNOWN,	"Unknown resolver error" }
59};
60
61
62/*** Error-reporting functions ***********************************************/
63
64/*
65 * Map error code to string
66 */
67static struct fetcherr *
68_fetch_finderr(struct fetcherr *p, int e)
69{
70    while (p->num != -1 && p->num != e)
71	p++;
72    return p;
73}
74
75/*
76 * Set error code
77 */
78void
79_fetch_seterr(struct fetcherr *p, int e)
80{
81    p = _fetch_finderr(p, e);
82    fetchLastErrCode = p->cat;
83    snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
84}
85
86/*
87 * Set error code according to errno
88 */
89void
90_fetch_syserr(void)
91{
92    int e;
93    e = errno;
94
95    switch (errno) {
96    case 0:
97	fetchLastErrCode = FETCH_OK;
98	break;
99    case EPERM:
100    case EACCES:
101    case EROFS:
102    case EAUTH:
103    case ENEEDAUTH:
104	fetchLastErrCode = FETCH_AUTH;
105	break;
106    case ENOENT:
107    case EISDIR: /* XXX */
108	fetchLastErrCode = FETCH_UNAVAIL;
109	break;
110    case ENOMEM:
111	fetchLastErrCode = FETCH_MEMORY;
112	break;
113    case EBUSY:
114    case EAGAIN:
115	fetchLastErrCode = FETCH_TEMP;
116	break;
117    case EEXIST:
118	fetchLastErrCode = FETCH_EXISTS;
119	break;
120    case ENOSPC:
121	fetchLastErrCode = FETCH_FULL;
122	break;
123    case EADDRINUSE:
124    case EADDRNOTAVAIL:
125    case ENETDOWN:
126    case ENETUNREACH:
127    case ENETRESET:
128    case EHOSTUNREACH:
129	fetchLastErrCode = FETCH_NETWORK;
130	break;
131    case ECONNABORTED:
132    case ECONNRESET:
133	fetchLastErrCode = FETCH_ABORT;
134	break;
135    case ETIMEDOUT:
136	fetchLastErrCode = FETCH_TIMEOUT;
137	break;
138    case ECONNREFUSED:
139    case EHOSTDOWN:
140	fetchLastErrCode = FETCH_DOWN;
141	break;
142    default:
143	fetchLastErrCode = FETCH_UNKNOWN;
144    }
145    snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(e));
146}
147
148
149/*
150 * Emit status message
151 */
152void
153_fetch_info(char *fmt, ...)
154{
155    va_list ap;
156
157    va_start(ap, fmt);
158    vfprintf(stderr, fmt, ap);
159    va_end(ap);
160    fputc('\n', stderr);
161}
162
163
164/*** Network-related utility functions ***************************************/
165
166/*
167 * Establish a TCP connection to the specified port on the specified host.
168 */
169int
170_fetch_connect(char *host, int port, int af, int verbose)
171{
172    char pbuf[10];
173    struct addrinfo hints, *res, *res0;
174    int sd, err;
175
176#ifndef NDEBUG
177    fprintf(stderr, "\033[1m---> %s:%d\033[m\n", host, port);
178#endif
179
180    if (verbose)
181	_fetch_info("looking up %s", host);
182
183    /* look up host name and set up socket address structure */
184    snprintf(pbuf, sizeof(pbuf), "%d", port);
185    memset(&hints, 0, sizeof(hints));
186    hints.ai_family = af;
187    hints.ai_socktype = SOCK_STREAM;
188    hints.ai_protocol = 0;
189    if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
190	_netdb_seterr(err);
191	return -1;
192    }
193
194    if (verbose)
195	_fetch_info("connecting to %s:%d", host, port);
196
197    /* try to connect */
198    sd = -1;
199    for (res = res0; res; res = res->ai_next) {
200	if ((sd = socket(res->ai_family, res->ai_socktype,
201			 res->ai_protocol)) < 0)
202	    continue;
203	if (connect(sd, res->ai_addr, res->ai_addrlen) >= 0)
204	    break;
205	close(sd);
206	sd = -1;
207    }
208    freeaddrinfo(res0);
209    if (sd < 0) {
210	_fetch_syserr();
211	return -1;
212    }
213
214    return sd;
215}
216
217
218/*
219 * Read a line of text from a socket w/ timeout
220 */
221#define MIN_BUF_SIZE 1024
222
223int
224_fetch_getln(int fd, char **buf, size_t *size, size_t *len)
225{
226    struct timeval now, timeout, wait;
227    fd_set readfds;
228    int r;
229    char c;
230
231    if (*buf == NULL) {
232	if ((*buf = malloc(MIN_BUF_SIZE)) == NULL) {
233	    errno = ENOMEM;
234	    return -1;
235	}
236	*size = MIN_BUF_SIZE;
237    }
238
239    **buf = '\0';
240    *len = 0;
241
242    if (fetchTimeout) {
243	gettimeofday(&timeout, NULL);
244	timeout.tv_sec += fetchTimeout;
245	FD_ZERO(&readfds);
246    }
247
248    do {
249	if (fetchTimeout) {
250	    FD_SET(fd, &readfds);
251	    gettimeofday(&now, NULL);
252	    wait.tv_sec = timeout.tv_sec - now.tv_sec;
253	    wait.tv_usec = timeout.tv_usec - now.tv_usec;
254	    if (wait.tv_usec < 0) {
255		wait.tv_usec += 1000000;
256		wait.tv_sec--;
257	    }
258	    if (wait.tv_sec < 0) {
259		errno = ETIMEDOUT;
260		return -1;
261	    }
262	    r = select(fd+1, &readfds, NULL, NULL, &wait);
263	    if (r == -1) {
264		if (errno == EINTR)
265		    continue;
266		/* EBADF or EINVAL: shouldn't happen */
267		return -1;
268	    }
269	    if (!FD_ISSET(fd, &readfds))
270		continue;
271	}
272	r = read(fd, &c, 1);
273	if (r == 0)
274	    break;
275	if (r == -1) {
276	    if (errno == EINTR)
277		continue;
278	    /* any other error is bad news */
279	    return -1;
280	}
281	(*buf)[*len] = c;
282	*len += 1;
283	if (*len == *size) {
284	    char *tmp;
285
286	    if ((tmp = realloc(*buf, *size * 2 + 1)) == NULL) {
287		errno = ENOMEM;
288		return -1;
289	    }
290	    *buf = tmp;
291	    *size = *size * 2 + 1;
292	}
293    } while (c != '\n');
294
295    return 0;
296}
297
298
299/*** Directory-related utility functions *************************************/
300
301int
302_fetch_add_entry(struct url_ent **p, int *size, int *len,
303		 char *name, struct url_stat *stat)
304{
305    struct url_ent *tmp;
306
307    if (*p == NULL) {
308#define INITIAL_SIZE 8
309	if ((*p = malloc(INITIAL_SIZE * sizeof **p)) == NULL) {
310	    errno = ENOMEM;
311	    _fetch_syserr();
312	    return -1;
313	}
314	*size = INITIAL_SIZE;
315	*len = 0;
316#undef INITIAL_SIZE
317    }
318
319    if (*len >= *size - 1) {
320	tmp = realloc(*p, *size * 2 * sizeof **p);
321	if (tmp == NULL) {
322	    errno = ENOMEM;
323	    _fetch_syserr();
324	    return -1;
325	}
326	*size *= 2;
327	*p = tmp;
328    }
329
330    tmp = *p + *len;
331    snprintf(tmp->name, MAXPATHLEN, "%s", name);
332    bcopy(stat, &tmp->stat, sizeof *stat);
333
334    (*len)++;
335    (++tmp)->name[0] = 0;
336
337    return 0;
338}
339