]> sjero.net Git - wget/blob - src/connect.c
[svn] Update copyright notices.
[wget] / src / connect.c
1 /* Establishing and handling network connections.
2    Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <sys/types.h>
24 #ifdef HAVE_UNISTD_H
25 # include <unistd.h>
26 #endif
27
28 #ifdef WINDOWS
29 # include <winsock.h>
30 #else
31 # include <sys/socket.h>
32 # include <netdb.h>
33 # include <netinet/in.h>
34 # include <arpa/inet.h>
35 #endif /* WINDOWS */
36
37 #include <errno.h>
38 #ifdef HAVE_STRING_H
39 # include <string.h>
40 #else
41 # include <strings.h>
42 #endif /* HAVE_STRING_H */
43 #ifdef HAVE_SYS_SELECT_H
44 # include <sys/select.h>
45 #endif /* HAVE_SYS_SELECT_H */
46
47 #include "wget.h"
48 #include "connect.h"
49 #include "host.h"
50
51 #ifndef errno
52 extern int errno;
53 #endif
54
55 /* Variables shared by bindport and acceptport: */
56 static int msock = -1;
57 static struct sockaddr *addr;
58
59
60 /* Create an internet connection to HOSTNAME on PORT.  The created
61    socket will be stored to *SOCK.  */
62 uerr_t
63 make_connection (int *sock, char *hostname, unsigned short port)
64 {
65   struct sockaddr_in sock_name;
66   /* struct hostent *hptr; */
67
68   /* Get internet address of the host.  We can do it either by calling
69      ngethostbyname, or by calling store_hostaddress, from host.c.
70      storehostaddress is better since it caches calls to
71      gethostbyname.  */
72 #if 1
73   if (!store_hostaddress ((unsigned char *)&sock_name.sin_addr, hostname))
74     return HOSTERR;
75 #else  /* never */
76   if (!(hptr = ngethostbyname (hostname)))
77     return HOSTERR;
78   /* Copy the address of the host to socket description.  */
79   memcpy (&sock_name.sin_addr, hptr->h_addr, hptr->h_length);
80 #endif /* never */
81
82   /* Set port and protocol */
83   sock_name.sin_family = AF_INET;
84   sock_name.sin_port = htons (port);
85
86   /* Make an internet socket, stream type.  */
87   if ((*sock = socket (AF_INET, SOCK_STREAM, 0)) == -1)
88     return CONSOCKERR;
89
90   if (opt.bind_address != NULL)
91     {
92       /* Bind the client side to the requested address. */
93       if (bind (*sock, (struct sockaddr *) opt.bind_address,
94                 sizeof (*opt.bind_address)))
95         return CONSOCKERR;
96     }
97
98   /* Connect the socket to the remote host.  */
99   if (connect (*sock, (struct sockaddr *) &sock_name, sizeof (sock_name)))
100     {
101       if (errno == ECONNREFUSED)
102         return CONREFUSED;
103       else
104         return CONERROR;
105     }
106   DEBUGP (("Created fd %d.\n", *sock));
107   return NOCONERROR;
108 }
109
110 int
111 test_socket_open (int sock)
112 {
113 #ifdef HAVE_SELECT
114   fd_set check_set;
115   struct timeval to;
116
117   /* Check if we still have a valid (non-EOF) connection.  From Andrew
118    * Maholski's code in the Unix Socket FAQ.  */
119
120   FD_ZERO (&check_set);
121   FD_SET (sock, &check_set);
122
123   /* Wait one microsecond */
124   to.tv_sec = 0;
125   to.tv_usec = 1;
126
127   /* If we get a timeout, then that means still connected */
128   if (select (sock + 1, &check_set, NULL, NULL, &to) == 0)
129     {
130       /* Connection is valid (not EOF), so continue */
131       return 1;
132     }
133   else
134     return 0;
135 #else
136   /* Without select, it's hard to know for sure. */
137   return 1;
138 #endif
139 }
140
141 /* Bind the local port PORT.  This does all the necessary work, which
142    is creating a socket, setting SO_REUSEADDR option on it, then
143    calling bind() and listen().  If *PORT is 0, a random port is
144    chosen by the system, and its value is stored to *PORT.  The
145    internal variable MPORT is set to the value of the ensuing master
146    socket.  Call acceptport() to block for and accept a connection.  */
147 uerr_t
148 bindport (unsigned short *port)
149 {
150   int optval = 1;
151   static struct sockaddr_in srv;
152
153   msock = -1;
154   addr = (struct sockaddr *) &srv;
155   if ((msock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
156     return CONSOCKERR;
157   if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
158                   (char *)&optval, sizeof (optval)) < 0)
159     return CONSOCKERR;
160
161   if (opt.bind_address == NULL)
162     {
163       srv.sin_family = AF_INET;
164       srv.sin_addr.s_addr = htonl (INADDR_ANY);
165     }
166   else
167     srv = *opt.bind_address;
168
169   srv.sin_port = htons (*port);
170   if (bind (msock, addr, sizeof (struct sockaddr_in)) < 0)
171     {
172       CLOSE (msock);
173       msock = -1;
174       return BINDERR;
175     }
176   DEBUGP (("Master socket fd %d bound.\n", msock));
177   if (!*port)
178     {
179       /* #### addrlen should be a 32-bit type, which int is not
180          guaranteed to be.  Oh, and don't try to make it a size_t,
181          because that can be 64-bit.  */
182       int addrlen = sizeof (struct sockaddr_in);
183       if (getsockname (msock, addr, &addrlen) < 0)
184         {
185           CLOSE (msock);
186           msock = -1;
187           return CONPORTERR;
188         }
189       *port = ntohs (srv.sin_port);
190     }
191   if (listen (msock, 1) < 0)
192     {
193       CLOSE (msock);
194       msock = -1;
195       return LISTENERR;
196     }
197   return BINDOK;
198 }
199
200 #ifdef HAVE_SELECT
201 /* Wait for file descriptor FD to be readable, MAXTIME being the
202    timeout in seconds.  If WRITEP is non-zero, checks for FD being
203    writable instead.
204
205    Returns 1 if FD is accessible, 0 for timeout and -1 for error in
206    select().  */
207 int
208 select_fd (int fd, int maxtime, int writep)
209 {
210   fd_set fds, exceptfds;
211   struct timeval timeout;
212
213   FD_ZERO (&fds);
214   FD_SET (fd, &fds);
215   FD_ZERO (&exceptfds);
216   FD_SET (fd, &exceptfds);
217   timeout.tv_sec = maxtime;
218   timeout.tv_usec = 0;
219   /* HPUX reportedly warns here.  What is the correct incantation?  */
220   return select (fd + 1, writep ? NULL : &fds, writep ? &fds : NULL,
221                  &exceptfds, &timeout);
222 }
223 #endif /* HAVE_SELECT */
224
225 /* Call accept() on MSOCK and store the result to *SOCK.  This assumes
226    that bindport() has been used to initialize MSOCK to a correct
227    value.  It blocks the caller until a connection is established.  If
228    no connection is established for OPT.TIMEOUT seconds, the function
229    exits with an error status.  */
230 uerr_t
231 acceptport (int *sock)
232 {
233   int addrlen = sizeof (struct sockaddr_in);
234
235 #ifdef HAVE_SELECT
236   if (select_fd (msock, opt.timeout, 0) <= 0)
237     return ACCEPTERR;
238 #endif
239   if ((*sock = accept (msock, addr, &addrlen)) < 0)
240     return ACCEPTERR;
241   DEBUGP (("Created socket fd %d.\n", *sock));
242   return ACCEPTOK;
243 }
244
245 /* Close SOCK, as well as the most recently remembered MSOCK, created
246    via bindport().  If SOCK is -1, close MSOCK only.  */
247 void
248 closeport (int sock)
249 {
250   /*shutdown (sock, 2);*/
251   if (sock != -1)
252     CLOSE (sock);
253   if (msock != -1)
254     CLOSE (msock);
255   msock = -1;
256 }
257
258 /* Return the local IP address associated with the connection on FD.
259    It is returned in a static buffer.  */
260 unsigned char *
261 conaddr (int fd)
262 {
263   static unsigned char res[4];
264   struct sockaddr_in mysrv;
265   struct sockaddr *myaddr;
266   int addrlen = sizeof (mysrv); /* see bindport() for discussion of
267                                    using `int' here. */
268
269   myaddr = (struct sockaddr *) (&mysrv);
270   if (getsockname (fd, myaddr, (int *)&addrlen) < 0)
271     return NULL;
272   memcpy (res, &mysrv.sin_addr, 4);
273   return res;
274 }
275
276 /* Read at most LEN bytes from FD, storing them to BUF.  This is
277    virtually the same as read(), but takes care of EINTR braindamage
278    and uses select() to timeout the stale connections (a connection is
279    stale if more than OPT.TIMEOUT time is spent in select() or
280    read()).  */
281 int
282 iread (int fd, char *buf, int len)
283 {
284   int res;
285
286   do
287     {
288 #ifdef HAVE_SELECT
289       if (opt.timeout)
290         {
291           do
292             {
293               res = select_fd (fd, opt.timeout, 0);
294             }
295           while (res == -1 && errno == EINTR);
296           if (res <= 0)
297             {
298               /* Set errno to ETIMEDOUT on timeout.  */
299               if (res == 0)
300                 /* #### Potentially evil!  */
301                 errno = ETIMEDOUT;
302               return -1;
303             }
304         }
305 #endif
306       res = READ (fd, buf, len);
307     }
308   while (res == -1 && errno == EINTR);
309
310   return res;
311 }
312
313 /* Write LEN bytes from BUF to FD.  This is similar to iread(), but
314    doesn't bother with select().  Unlike iread(), it makes sure that
315    all of BUF is actually written to FD, so callers needn't bother
316    with checking that the return value equals to LEN.  Instead, you
317    should simply check for -1.  */
318 int
319 iwrite (int fd, char *buf, int len)
320 {
321   int res = 0;
322
323   /* `write' may write less than LEN bytes, thus the outward loop
324      keeps trying it until all was written, or an error occurred.  The
325      inner loop is reserved for the usual EINTR f*kage, and the
326      innermost loop deals with the same during select().  */
327   while (len > 0)
328     {
329       do
330         {
331 #ifdef HAVE_SELECT
332           if (opt.timeout)
333             {
334               do
335                 {
336                   res = select_fd (fd, opt.timeout, 1);
337                 }
338               while (res == -1 && errno == EINTR);
339               if (res <= 0)
340                 {
341                   /* Set errno to ETIMEDOUT on timeout.  */
342                   if (res == 0)
343                     /* #### Potentially evil!  */
344                     errno = ETIMEDOUT;
345                   return -1;
346                 }
347             }
348 #endif
349           res = WRITE (fd, buf, len);
350         }
351       while (res == -1 && errno == EINTR);
352       if (res <= 0)
353         break;
354       buf += res;
355       len -= res;
356     }
357   return res;
358 }