common.c revision 97856
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 97856 2002-06-05 10:05:03Z 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 */
201conn_t *
202_fetch_connect(const char *host, int port, int af, int verbose)
203{
204	conn_t *conn;
205	char pbuf[10];
206	struct addrinfo hints, *res, *res0;
207	int sd, err;
208
209	DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
210
211	if (verbose)
212		_fetch_info("looking up %s", host);
213
214	/* look up host name and set up socket address structure */
215	snprintf(pbuf, sizeof(pbuf), "%d", port);
216	memset(&hints, 0, sizeof(hints));
217	hints.ai_family = af;
218	hints.ai_socktype = SOCK_STREAM;
219	hints.ai_protocol = 0;
220	if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
221		_netdb_seterr(err);
222		return (NULL);
223	}
224
225	if (verbose)
226		_fetch_info("connecting to %s:%d", host, port);
227
228	/* try to connect */
229	for (sd = -1, res = res0; res; res = res->ai_next) {
230		if ((sd = socket(res->ai_family, res->ai_socktype,
231			 res->ai_protocol)) == -1)
232			continue;
233		if (connect(sd, res->ai_addr, res->ai_addrlen) != -1)
234			break;
235		close(sd);
236		sd = -1;
237	}
238	freeaddrinfo(res0);
239	if (sd == -1) {
240		_fetch_syserr();
241		return (NULL);
242	}
243
244	/* allocate and fill connection structure */
245	if ((conn = calloc(1, sizeof *conn)) == NULL) {
246		close(sd);
247		return (NULL);
248	}
249	if ((conn->host = strdup(host)) == NULL) {
250		free(conn);
251		close(sd);
252		return (NULL);
253	}
254	conn->port = port;
255	conn->af = af;
256	conn->sd = sd;
257	return (conn);
258}
259
260
261/*
262 * Read a line of text from a socket w/ timeout
263 */
264#define MIN_BUF_SIZE 1024
265
266int
267_fetch_getln(conn_t *conn)
268{
269	struct timeval now, timeout, wait;
270	fd_set readfds;
271	int r;
272	char c;
273
274	if (conn->buf == NULL) {
275		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
276			errno = ENOMEM;
277			return (-1);
278		}
279		conn->bufsize = MIN_BUF_SIZE;
280	}
281
282	conn->buf[0] = '\0';
283	conn->buflen = 0;
284
285	if (fetchTimeout) {
286		gettimeofday(&timeout, NULL);
287		timeout.tv_sec += fetchTimeout;
288		FD_ZERO(&readfds);
289	}
290
291	do {
292		if (fetchTimeout) {
293			FD_SET(conn->sd, &readfds);
294			gettimeofday(&now, NULL);
295			wait.tv_sec = timeout.tv_sec - now.tv_sec;
296			wait.tv_usec = timeout.tv_usec - now.tv_usec;
297			if (wait.tv_usec < 0) {
298				wait.tv_usec += 1000000;
299				wait.tv_sec--;
300			}
301			if (wait.tv_sec < 0) {
302				errno = ETIMEDOUT;
303				return (-1);
304			}
305			r = select(conn->sd + 1, &readfds, NULL, NULL, &wait);
306			if (r == -1) {
307				if (errno == EINTR && fetchRestartCalls)
308					continue;
309				/* EBADF or EINVAL: shouldn't happen */
310				return (-1);
311			}
312			if (!FD_ISSET(conn->sd, &readfds))
313				continue;
314		}
315		r = read(conn->sd, &c, 1);
316		if (r == 0)
317			break;
318		if (r == -1) {
319			if (errno == EINTR && fetchRestartCalls)
320				continue;
321			/* any other error is bad news */
322			return (-1);
323		}
324		conn->buf[conn->buflen++] = c;
325		if (conn->buflen == conn->bufsize) {
326			char *tmp;
327			size_t tmpsize;
328
329			tmp = conn->buf;
330			tmpsize = conn->bufsize * 2 + 1;
331			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
332				errno = ENOMEM;
333				return (-1);
334			}
335			conn->buf = tmp;
336			conn->bufsize = tmpsize;
337		}
338	} while (c != '\n');
339
340	conn->buf[conn->buflen] = '\0';
341	DEBUG(fprintf(stderr, "<<< %s", conn->buf));
342	return (0);
343}
344
345
346/*
347 * Write a line of text to a socket w/ timeout
348 * XXX currently does not enforce timeout
349 */
350int
351_fetch_putln(conn_t *conn, const char *str, size_t len)
352{
353	struct iovec iov[2];
354	ssize_t wlen;
355
356	/* XXX should enforce timeout */
357	iov[0].iov_base = (char *)str;
358	iov[0].iov_len = len;
359	iov[1].iov_base = (char *)ENDL;
360	iov[1].iov_len = sizeof ENDL;
361	len += sizeof ENDL;
362	wlen = writev(conn->sd, iov, 2);
363	if (wlen < 0 || (size_t)wlen != len)
364		return (-1);
365	DEBUG(fprintf(stderr, ">>> %.*s\n", (int)len, str));
366	return (0);
367}
368
369
370/*
371 * Close connection
372 */
373int
374_fetch_close(conn_t *conn)
375{
376	int ret;
377
378	ret = close(conn->sd);
379	free(conn->host);
380	free(conn);
381	return (ret);
382}
383
384
385/*** Directory-related utility functions *************************************/
386
387int
388_fetch_add_entry(struct url_ent **p, int *size, int *len,
389    const char *name, struct url_stat *us)
390{
391	struct url_ent *tmp;
392
393	if (*p == NULL) {
394		*size = 0;
395		*len = 0;
396	}
397
398	if (*len >= *size - 1) {
399		tmp = realloc(*p, (*size * 2 + 1) * sizeof **p);
400		if (tmp == NULL) {
401			errno = ENOMEM;
402			_fetch_syserr();
403			return (-1);
404		}
405		*size = (*size * 2 + 1);
406		*p = tmp;
407	}
408
409	tmp = *p + *len;
410	snprintf(tmp->name, PATH_MAX, "%s", name);
411	bcopy(us, &tmp->stat, sizeof *us);
412
413	(*len)++;
414	(++tmp)->name[0] = 0;
415
416	return (0);
417}
418