⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connect.c

📁 一个从网络上自动下载文件的自由工具
💻 C
📖 第 1 页 / 共 2 页
字号:
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 true on success, false 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.  */boolsocket_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 false;  ip->family = sockaddr->sa_family;  switch (sockaddr->sa_family)    {#ifdef ENABLE_IPV6    case AF_INET6:      {        struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&storage;        ip->data.d6 = sa6->sin6_addr;#ifdef HAVE_SOCKADDR_IN6_SCOPE_ID        ip->ipv6_scope = sa6->sin6_scope_id;#endif        DEBUGP (("conaddr is: %s\n", print_address (ip)));        return true;      }#endif    case AF_INET:      {        struct sockaddr_in *sa = (struct sockaddr_in *)&storage;        ip->data.d4 = sa->sin_addr;        DEBUGP (("conaddr is: %s\n", print_address (ip)));        return true;      }    default:      abort ();    }}/* Return true 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".  */boolretryable_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 (false#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 false;  if (!opt.retry_connrefused)    if (err == ECONNREFUSED#ifdef ENETUNREACH        || err == ENETUNREACH   /* network is unreachable */#endif#ifdef EHOSTUNREACH        || err == EHOSTUNREACH  /* host is unreachable */#endif        )      return false;  return true;}/* 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){  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;}/* Return true iff the connection to the remote site established   through SOCK is still open.   Specifically, this function returns true if SOCK is not ready for   reading.  This is because, when the connection closes, the socket   is ready for reading because EOF is about to be delivered.  A side   effect of this method is that sockets that have pending data are   considered non-open.  This is actually a good thing for callers of   this function, where such pending data can only be unwanted   leftover from a previous request.  */booltest_socket_open (int sock){  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 (select (sock + 1, &check_set, NULL, NULL, &to) == 0)    /* We got a timeout, it means we're still connected. */    return true;  else    /* Read now would not wait, it means we have either pending data       or EOF/error. */    return false;}/* Basic socket operations, mostly EINTR wrappers.  */#if defined(WINDOWS) || defined(MSDOS)# 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 unsigned int transport_map_modified_tick;struct transport_info {  struct transport_implementation *imp;  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, struct transport_implementation *imp, 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->imp = imp;  info->ctx = ctx;  if (!transport_map)    transport_map = hash_table_new (0, NULL, NULL);  hash_table_put (transport_map, (void *)(intptr_t) 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 *)(intptr_t) 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;                                              \  static unsigned int 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 *)(intptr_t) fd);     \      last_fd = fd;                                                     \      last_info = info;                                                 \      last_tick = transport_map_modified_tick;                          \    }                                                                   \} while (0)static boolpoll_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->imp->poller)        test = info->imp->poller (fd, timeout, wf, info->ctx);      else        test = sock_poll (fd, timeout, wf);      if (test == 0)        errno = ETIMEDOUT;      if (test <= 0)        return false;    }  return true;}/* 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->imp->reader)    return info->imp->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->imp->peeker)    return info->imp->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->imp->writer)        res = info->imp->writer (fd, buf, bufsize, info->ctx);      else        res = sock_write (fd, buf, bufsize);      if (res <= 0)        break;      buf += res;      bufsize -= res;    }  return res;}/* Report the most recent error(s) on FD.  This should only be called   after fd_* functions, such as fd_read and fd_write, and only if   they return a negative result.  For errors coming from other calls   such as setsockopt or fopen, strerror should continue to be   used.   If the transport doesn't support error messages or doesn't supply   one, strerror(errno) is returned.  The returned error message   should not be used after fd_close has been called.  */const char *fd_errstr (int fd){  /* Don't bother with LAZY_RETRIEVE_INFO, as this will only be called     in case of error, never in a tight loop.  */  struct transport_info *info = NULL;  if (transport_map)    info = hash_table_get (transport_map, (void *)(intptr_t) fd);  if (info && info->imp->errstr)    {      const char *err = info->imp->errstr (fd, info->ctx);      if (err)        return err;      /* else, fall through and print the system error. */    }  return strerror (errno);}/* 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 *)(intptr_t) fd);  if (info && info->imp->closer)    info->imp->closer (fd, info->ctx);  else    sock_close (fd);  if (info)    {      hash_table_remove (transport_map, (void *)(intptr_t) fd);      xfree (info);      ++transport_map_modified_tick;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -