📄 connect.c
字号:
In other words, accept a client connection on LOCAL_SOCK, and return the new socket used for communication with the client. LOCAL_SOCK should have been bound, e.g. using bind_local(). The caller is blocked until a connection is established. If no connection is established for opt.connect_timeout seconds, the function exits with an error status. */intaccept_connection (int local_sock){ int sock; /* We don't need the values provided by accept, but accept apparently requires them to be present. */ struct sockaddr_storage ss; struct sockaddr *sa = (struct sockaddr *)&ss; socklen_t addrlen = sizeof (ss); if (opt.connect_timeout) { int test = select_fd (local_sock, opt.connect_timeout, WAIT_FOR_READ); if (test == 0) errno = ETIMEDOUT; if (test <= 0) return -1; } sock = accept (local_sock, sa, &addrlen); DEBUGP (("Accepted client at socket %d.\n", sock)); return sock;}/* Get the IP address associated with the connection on FD and store it to IP. Return 1 on success, 0 otherwise. If ENDPOINT is ENDPOINT_LOCAL, it returns the address of the local (client) side of the socket. Else if ENDPOINT is ENDPOINT_PEER, it returns the address of the remote (peer's) side of the socket. */intsocket_ip_address (int sock, ip_address *ip, int endpoint){ struct sockaddr_storage storage; struct sockaddr *sockaddr = (struct sockaddr *)&storage; socklen_t addrlen = sizeof (storage); int ret; if (endpoint == ENDPOINT_LOCAL) ret = getsockname (sock, sockaddr, &addrlen); else if (endpoint == ENDPOINT_PEER) ret = getpeername (sock, sockaddr, &addrlen); else abort (); if (ret < 0) return 0; switch (sockaddr->sa_family) {#ifdef ENABLE_IPV6 case AF_INET6: { struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&storage; ip->type = IPV6_ADDRESS; ADDRESS_IPV6_IN6_ADDR (ip) = sa6->sin6_addr;#ifdef HAVE_SOCKADDR_IN6_SCOPE_ID ADDRESS_IPV6_SCOPE (ip) = sa6->sin6_scope_id;#endif DEBUGP (("conaddr is: %s\n", pretty_print_address (ip))); return 1; }#endif case AF_INET: { struct sockaddr_in *sa = (struct sockaddr_in *)&storage; ip->type = IPV4_ADDRESS; ADDRESS_IPV4_IN_ADDR (ip) = sa->sin_addr; DEBUGP (("conaddr is: %s\n", pretty_print_address (ip))); return 1; } default: abort (); }}/* Return non-zero if the error from the connect code can be considered retryable. Wget normally retries after errors, but the exception are the "unsupported protocol" type errors (possible on IPv4/IPv6 dual family systems) and "connection refused". */intretryable_socket_connect_error (int err){ /* Have to guard against some of these values not being defined. Cannot use a switch statement because some of the values might be equal. */ if (0#ifdef EAFNOSUPPORT || err == EAFNOSUPPORT#endif#ifdef EPFNOSUPPORT || err == EPFNOSUPPORT#endif#ifdef ESOCKTNOSUPPORT /* no, "sockt" is not a typo! */ || err == ESOCKTNOSUPPORT#endif#ifdef EPROTONOSUPPORT || err == EPROTONOSUPPORT#endif#ifdef ENOPROTOOPT || err == ENOPROTOOPT#endif /* Apparently, older versions of Linux and BSD used EINVAL instead of EAFNOSUPPORT and such. */ || err == EINVAL ) return 0; if (!opt.retry_connrefused) if (err == ECONNREFUSED#ifdef ENETUNREACH || err == ENETUNREACH /* network is unreachable */#endif#ifdef EHOSTUNREACH || err == EHOSTUNREACH /* host is unreachable */#endif ) return 0; return 1;}/* Wait for a single descriptor to become available, timing out after MAXTIME seconds. Returns 1 if FD is available, 0 for timeout and -1 for error. The argument WAIT_FOR can be a combination of WAIT_FOR_READ and WAIT_FOR_WRITE. This is a mere convenience wrapper around the select call, and should be taken as such (for example, it doesn't implement Wget's 0-timeout-means-no-timeout semantics.) */intselect_fd (int fd, double maxtime, int wait_for){#ifdef HAVE_SELECT fd_set fdset; fd_set *rd = NULL, *wr = NULL; struct timeval tmout; int result; FD_ZERO (&fdset); FD_SET (fd, &fdset); if (wait_for & WAIT_FOR_READ) rd = &fdset; if (wait_for & WAIT_FOR_WRITE) wr = &fdset; tmout.tv_sec = (long) maxtime; tmout.tv_usec = 1000000 * (maxtime - (long) maxtime); do result = select (fd + 1, rd, wr, NULL, &tmout); while (result < 0 && errno == EINTR); return result;#else /* not HAVE_SELECT */ /* If select() unavailable, just return 1. In most usages in Wget, this is the appropriate response -- "if we can't poll, go ahead with the blocking operation". If a specific part of code needs different behavior, it can use #ifdef HAVE_SELECT to test whether polling really occurs. */ return 1;#endif /* not HAVE_SELECT */}inttest_socket_open (int sock){#ifdef HAVE_SELECT fd_set check_set; struct timeval to; /* Check if we still have a valid (non-EOF) connection. From Andrew * Maholski's code in the Unix Socket FAQ. */ FD_ZERO (&check_set); FD_SET (sock, &check_set); /* Wait one microsecond */ to.tv_sec = 0; to.tv_usec = 1; /* If we get a timeout, then that means still connected */ if (select (sock + 1, &check_set, NULL, NULL, &to) == 0) { /* Connection is valid (not EOF), so continue */ return 1; } else return 0;#else /* Without select, it's hard to know for sure. */ return 1;#endif}/* Basic socket operations, mostly EINTR wrappers. */#ifdef WINDOWS# define read(fd, buf, cnt) recv (fd, buf, cnt, 0)# define write(fd, buf, cnt) send (fd, buf, cnt, 0)# define close(fd) closesocket (fd)#endif#ifdef __BEOS__# define read(fd, buf, cnt) recv (fd, buf, cnt, 0)# define write(fd, buf, cnt) send (fd, buf, cnt, 0)#endifstatic intsock_read (int fd, char *buf, int bufsize){ int res; do res = read (fd, buf, bufsize); while (res == -1 && errno == EINTR); return res;}static intsock_write (int fd, char *buf, int bufsize){ int res; do res = write (fd, buf, bufsize); while (res == -1 && errno == EINTR); return res;}static intsock_poll (int fd, double timeout, int wait_for){ return select_fd (fd, timeout, wait_for);}static intsock_peek (int fd, char *buf, int bufsize){ int res; do res = recv (fd, buf, bufsize, MSG_PEEK); while (res == -1 && errno == EINTR); return res;}static voidsock_close (int fd){ close (fd); DEBUGP (("Closed fd %d\n", fd));}#undef read#undef write#undef close/* Reading and writing from the network. We build around the socket (file descriptor) API, but support "extended" operations for things that are not mere file descriptors under the hood, such as SSL sockets. That way the user code can call fd_read(fd, ...) and we'll run read or SSL_read or whatever is necessary. */static struct hash_table *transport_map;static int transport_map_modified_tick;struct transport_info { fd_reader_t reader; fd_writer_t writer; fd_poller_t poller; fd_peeker_t peeker; fd_closer_t closer; void *ctx;};/* Register the transport layer operations that will be used when reading, writing, and polling FD. This should be used for transport layers like SSL that piggyback on sockets. FD should otherwise be a real socket, on which you can call getpeername, etc. */voidfd_register_transport (int fd, fd_reader_t reader, fd_writer_t writer, fd_poller_t poller, fd_peeker_t peeker, fd_closer_t closer, void *ctx){ struct transport_info *info; /* The file descriptor must be non-negative to be registered. Negative values are ignored by fd_close(), and -1 cannot be used as hash key. */ assert (fd >= 0); info = xnew (struct transport_info); info->reader = reader; info->writer = writer; info->poller = poller; info->peeker = peeker; info->closer = closer; info->ctx = ctx; if (!transport_map) transport_map = hash_table_new (0, NULL, NULL); hash_table_put (transport_map, (void *) fd, info); ++transport_map_modified_tick;}/* Return context of the transport registered with fd_register_transport. This assumes fd_register_transport was previously called on FD. */void *fd_transport_context (int fd){ struct transport_info *info = hash_table_get (transport_map, (void *) fd); return info->ctx;}/* When fd_read/fd_write are called multiple times in a loop, they should remember the INFO pointer instead of fetching it every time. It is not enough to compare FD to LAST_FD because FD might have been closed and reopened. modified_tick ensures that changes to transport_map will not be unnoticed. This is a macro because we want the static storage variables to be per-function. */#define LAZY_RETRIEVE_INFO(info) do { \ static struct transport_info *last_info; \ static int last_fd = -1, last_tick; \ if (!transport_map) \ info = NULL; \ else if (last_fd == fd && last_tick == transport_map_modified_tick) \ info = last_info; \ else \ { \ info = hash_table_get (transport_map, (void *) fd); \ last_fd = fd; \ last_info = info; \ last_tick = transport_map_modified_tick; \ } \} while (0)static intpoll_internal (int fd, struct transport_info *info, int wf, double timeout){ if (timeout == -1) timeout = opt.read_timeout; if (timeout) { int test; if (info && info->poller) test = info->poller (fd, timeout, wf, info->ctx); else test = sock_poll (fd, timeout, wf); if (test == 0) errno = ETIMEDOUT; if (test <= 0) return 0; } return 1;}/* Read no more than BUFSIZE bytes of data from FD, storing them to BUF. If TIMEOUT is non-zero, the operation aborts if no data is received after that many seconds. If TIMEOUT is -1, the value of opt.timeout is used for TIMEOUT. */intfd_read (int fd, char *buf, int bufsize, double timeout){ struct transport_info *info; LAZY_RETRIEVE_INFO (info); if (!poll_internal (fd, info, WAIT_FOR_READ, timeout)) return -1; if (info && info->reader) return info->reader (fd, buf, bufsize, info->ctx); else return sock_read (fd, buf, bufsize);}/* Like fd_read, except it provides a "preview" of the data that will be read by subsequent calls to fd_read. Specifically, it copies no more than BUFSIZE bytes of the currently available data to BUF and returns the number of bytes copied. Return values and timeout semantics are the same as those of fd_read. CAVEAT: Do not assume that the first subsequent call to fd_read will retrieve the same amount of data. Reading can return more or less data, depending on the TCP implementation and other circumstances. However, barring an error, it can be expected that all the peeked data will eventually be read by fd_read. */intfd_peek (int fd, char *buf, int bufsize, double timeout){ struct transport_info *info; LAZY_RETRIEVE_INFO (info); if (!poll_internal (fd, info, WAIT_FOR_READ, timeout)) return -1; if (info && info->peeker) return info->peeker (fd, buf, bufsize, info->ctx); else return sock_peek (fd, buf, bufsize);}/* Write the entire contents of BUF to FD. If TIMEOUT is non-zero, the operation aborts if no data is received after that many seconds. If TIMEOUT is -1, the value of opt.timeout is used for TIMEOUT. */intfd_write (int fd, char *buf, int bufsize, double timeout){ int res; struct transport_info *info; LAZY_RETRIEVE_INFO (info); /* `write' may write less than LEN bytes, thus the loop keeps trying it until all was written, or an error occurred. */ res = 0; while (bufsize > 0) { if (!poll_internal (fd, info, WAIT_FOR_WRITE, timeout)) return -1; if (info && info->writer) res = info->writer (fd, buf, bufsize, info->ctx); else res = sock_write (fd, buf, bufsize); if (res <= 0) break; buf += res; bufsize -= res; } return res;}/* Close the file descriptor FD. */voidfd_close (int fd){ struct transport_info *info; if (fd < 0) return; /* Don't use LAZY_RETRIEVE_INFO because fd_close() is only called once per socket, so that particular optimization wouldn't work. */ info = NULL; if (transport_map) info = hash_table_get (transport_map, (void *) fd); if (info && info->closer) info->closer (fd, info->ctx); else sock_close (fd); if (info) { hash_table_remove (transport_map, (void *) fd); xfree (info); ++transport_map_modified_tick; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -