File: tcp-connect.c

package info (click to toggle)
ucspi-proxy 0.99-7
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 372 kB
  • sloc: ansic: 1,917; makefile: 46
file content (51 lines) | stat: -rw-r--r-- 1,320 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <errno.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <bglibs/msg.h>
#include <bglibs/resolve.h>
#include <bglibs/socket.h>
#include <bglibs/unix.h>
#include "ucspi-proxy.h"

static ipv4addr addr;
static long port;

int tcp_connect(const char* host, const char* portstr, unsigned timeout)
{
  struct servent* se;
  const char* end;
  int fd;
  iopoll_fd pf;

  if (!resolve_ipv4name(host, &addr))
    die3(111, "Could not resolve '", host, "'");
  if ((se = getservbyname(portstr, "tcp")) != 0)
    port = ntohs(se->s_port);
  else if ((port = strtol(portstr, (char**)&end, 10)) <= 0 ||
	   port >= 0xffff || *end != 0)
    die2(111, "Invalid port number: ", portstr);

  if ((fd = socket_tcp()) == -1)
    warn1sys("Could not create outgoing socket");
  else if (!nonblock_on(fd))
    warn1sys("Could not set flags on new outgoing socket");
  else if (socket_connect4(fd, &addr, port))
    return fd;
  else if (errno == EINPROGRESS || errno == EWOULDBLOCK) {
    pf.fd = fd;
    pf.events = IOPOLL_WRITE;
    switch (iopoll_restart(&pf, 1, timeout * 1000)) {
    case 0:
      warn1("Connection timed out");
      errno = ETIMEDOUT;
      break;
    case 1:
      if (socket_connected(fd))
	return fd;
    }
  }
  warn1sys("Connection to server rejected");
  close(fd);
  return -1;
}