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