]> sjero.net Git - wget/blob - src/connect.c
[svn] Manually applied Rob Mayoff <mayoff@dqd.com>'s patch (vs. 1.5.3, not 1.5.3...
[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 Wget.
5
6 This program 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 This program 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 this program; 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 /* Bind the local port PORT.  This does all the necessary work, which
111    is creating a socket, setting SO_REUSEADDR option on it, then
112    calling bind() and listen().  If *PORT is 0, a random port is
113    chosen by the system, and its value is stored to *PORT.  The
114    internal variable MPORT is set to the value of the ensuing master
115    socket.  Call acceptport() to block for and accept a connection.  */
116 uerr_t
117 bindport (unsigned short *port)
118 {
119   int optval = 1;
120   static struct sockaddr_in srv;
121
122   msock = -1;
123   addr = (struct sockaddr *) &srv;
124   if ((msock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
125     return CONSOCKERR;
126   if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
127                   (char *)&optval, sizeof (optval)) < 0)
128     return CONSOCKERR;
129
130   if (opt.bind_address == NULL)
131     {
132       srv.sin_family = AF_INET;
133       srv.sin_addr.s_addr = htonl (INADDR_ANY);
134     }
135   else
136     srv = *opt.bind_address;
137
138   srv.sin_port = htons (*port);
139   if (bind (msock, addr, sizeof (struct sockaddr_in)) < 0)
140     {
141       CLOSE (msock);
142       msock = -1;
143       return BINDERR;
144     }
145   DEBUGP (("Master socket fd %d bound.\n", msock));
146   if (!*port)
147     {
148       size_t addrlen = sizeof (struct sockaddr_in);
149       if (getsockname (msock, addr, (int *)&addrlen) < 0)
150         {
151           CLOSE (msock);
152           msock = -1;
153           return CONPORTERR;
154         }
155       *port = ntohs (srv.sin_port);
156     }
157   if (listen (msock, 1) < 0)
158     {
159       CLOSE (msock);
160       msock = -1;
161       return LISTENERR;
162     }
163   return BINDOK;
164 }
165
166 #ifdef HAVE_SELECT
167 /* Wait for file descriptor FD to be readable, MAXTIME being the
168    timeout in seconds.  If WRITEP is non-zero, checks for FD being
169    writable instead.
170
171    Returns 1 if FD is accessible, 0 for timeout and -1 for error in
172    select().  */
173 static int
174 select_fd (int fd, int maxtime, int writep)
175 {
176   fd_set fds, exceptfds;
177   struct timeval timeout;
178
179   FD_ZERO (&fds);
180   FD_SET (fd, &fds);
181   FD_ZERO (&exceptfds);
182   FD_SET (fd, &exceptfds);
183   timeout.tv_sec = maxtime;
184   timeout.tv_usec = 0;
185   /* HPUX reportedly warns here.  What is the correct incantation?  */
186   return select (fd + 1, writep ? NULL : &fds, writep ? &fds : NULL,
187                  &exceptfds, &timeout);
188 }
189 #endif /* HAVE_SELECT */
190
191 /* Call accept() on MSOCK and store the result to *SOCK.  This assumes
192    that bindport() has been used to initialize MSOCK to a correct
193    value.  It blocks the caller until a connection is established.  If
194    no connection is established for OPT.TIMEOUT seconds, the function
195    exits with an error status.  */
196 uerr_t
197 acceptport (int *sock)
198 {
199   int addrlen = sizeof (struct sockaddr_in);
200
201 #ifdef HAVE_SELECT
202   if (select_fd (msock, opt.timeout, 0) <= 0)
203     return ACCEPTERR;
204 #endif
205   if ((*sock = accept (msock, addr, &addrlen)) < 0)
206     return ACCEPTERR;
207   DEBUGP (("Created socket fd %d.\n", *sock));
208   return ACCEPTOK;
209 }
210
211 /* Close SOCK, as well as the most recently remembered MSOCK, created
212    via bindport().  If SOCK is -1, close MSOCK only.  */
213 void
214 closeport (int sock)
215 {
216   /*shutdown (sock, 2);*/
217   if (sock != -1)
218     CLOSE (sock);
219   if (msock != -1)
220     CLOSE (msock);
221   msock = -1;
222 }
223
224 /* Return the local IP address associated with the connection on FD.
225    It is returned in a static buffer.  */
226 unsigned char *
227 conaddr (int fd)
228 {
229   static unsigned char res[4];
230   struct sockaddr_in mysrv;
231   struct sockaddr *myaddr;
232   size_t addrlen = sizeof (mysrv);
233
234   myaddr = (struct sockaddr *) (&mysrv);
235   if (getsockname (fd, myaddr, (int *)&addrlen) < 0)
236     return NULL;
237   memcpy (res, &mysrv.sin_addr, 4);
238   return res;
239 }
240
241 /* Read at most LEN bytes from FD, storing them to BUF.  This is
242    virtually the same as read(), but takes care of EINTR braindamage
243    and uses select() to timeout the stale connections (a connection is
244    stale if more than OPT.TIMEOUT time is spent in select() or
245    read()).  */
246 int
247 iread (int fd, char *buf, int len)
248 {
249   int res;
250
251   do
252     {
253 #ifdef HAVE_SELECT
254       if (opt.timeout)
255         {
256           do
257             {
258               res = select_fd (fd, opt.timeout, 0);
259             }
260           while (res == -1 && errno == EINTR);
261           if (res <= 0)
262             {
263               /* Set errno to ETIMEDOUT on timeout.  */
264               if (res == 0)
265                 /* #### Potentially evil!  */
266                 errno = ETIMEDOUT;
267               return -1;
268             }
269         }
270 #endif
271       res = READ (fd, buf, len);
272     }
273   while (res == -1 && errno == EINTR);
274
275   return res;
276 }
277
278 /* Write LEN bytes from BUF to FD.  This is similar to iread(), but
279    doesn't bother with select().  Unlike iread(), it makes sure that
280    all of BUF is actually written to FD, so callers needn't bother
281    with checking that the return value equals to LEN.  Instead, you
282    should simply check for -1.  */
283 int
284 iwrite (int fd, char *buf, int len)
285 {
286   int res = 0;
287
288   /* `write' may write less than LEN bytes, thus the outward loop
289      keeps trying it until all was written, or an error occurred.  The
290      inner loop is reserved for the usual EINTR f*kage, and the
291      innermost loop deals with the same during select().  */
292   while (len > 0)
293     {
294       do
295         {
296 #ifdef HAVE_SELECT
297           if (opt.timeout)
298             {
299               do
300                 {
301                   res = select_fd (fd, opt.timeout, 1);
302                 }
303               while (res == -1 && errno == EINTR);
304               if (res <= 0)
305                 {
306                   /* Set errno to ETIMEDOUT on timeout.  */
307                   if (res == 0)
308                     /* #### Potentially evil!  */
309                     errno = ETIMEDOUT;
310                   return -1;
311                 }
312             }
313 #endif
314           res = WRITE (fd, buf, len);
315         }
316       while (res == -1 && errno == EINTR);
317       if (res <= 0)
318         break;
319       buf += res;
320       len -= res;
321     }
322   return res;
323 }