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