Example #1
0
// I *could* use templates, but I don't understand C++.
static int connect_common(char* hostport,
                          int (*try_socket)(int fd, const struct addrinfo* res),
                          int flags) {
  struct addrinfo *result;
  struct addrinfo *res;
  struct addrinfo hints;
  int error;
  int sfd;
  char* host;
  char* port;

  parse_hostport(hostport, &host, &port);
  if (port == NULL) {
    // They didn't give us a port.
    return -1;
  }

  memset(&hints, 0, sizeof(hints));
  hints.ai_family= PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_flags = AI_NUMERICSERV | flags;

  error = getaddrinfo(host, port, &hints, &result);
  if (error != 0) {
    return -1;
  }

  for (res = result; res != NULL; res = res->ai_next) {
    sfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (sfd == -1) continue;

    if (try_socket(sfd, res) == 0) {
      break;
    }

    close(sfd);
  }

  if (res == NULL) {
    sfd = -1;
  }

  freeaddrinfo(result);
  // TODO(awreece) This is bad and I feel bad, but I'm lazy.
  port[-1] = ':';
  return sfd;
}
Example #2
0
int
get_xsockets (int *number, struct x_socket **sockets, int tcp_socket)
{
     int dpy;
     struct x_socket *s;
     int n;
     int i;

     s = malloc (sizeof(*s) * 5);
     if (s == NULL)
	 errx (1, "malloc: out of memory");

     try_mkdir (X_UNIX_PATH);
     try_mkdir (X_PIPE_PATH);

     for(dpy = 4; dpy < 256; ++dpy) {
	 char **path;
	 int tmp = 0;

	 n = 0;
	 for (path = x_sockets; *path; ++path) {
	     tmp = try_socket (&s[n], dpy, *path);
	     if (tmp == -1) {
		 if (errno != ENOTDIR && errno != ENOENT)
		     err(1, "failed to open '%s'", *path);
	     } else if (tmp == 1) {
		 while(--n >= 0) {
		     close (s[n].fd);
		     free (s[n].pathname);
		 }
		 break;
	     } else if (tmp == 0)
		 ++n;
	 }
	 if (tmp == 1)
	     continue;

#ifdef MAY_HAVE_X11_PIPES
	 for (path = x_pipes; *path; ++path) {
	     tmp = try_pipe (&s[n], dpy, *path);
	     if (tmp == -1) {
		 if (errno != ENOTDIR && errno != ENOENT && errno != ENOSYS)
		     err(1, "failed to open '%s'", *path);
	     } else if (tmp == 1) {
		 while (--n >= 0) {
		     close (s[n].fd);
		     free (s[n].pathname);
		 }
		 break;
	     } else if (tmp == 0)
		 ++n;
	 }

	 if (tmp == 1)
	     continue;
#endif

	 if (tcp_socket) {
	     tmp = try_tcp (&s[n], dpy);
	     if (tmp == -1)
		 err(1, "failed to open tcp stocket");
	     else if (tmp == 1) {
		 while (--n >= 0) {
		     close (s[n].fd);
		     free (s[n].pathname);
		 }
		 break;
	     } else if (tmp == 0)
		 ++n;
	 }
	 break;
     }
     if (dpy == 256)
	 errx (1, "no free x-servers");
     for (i = 0; i < n; ++i)
	 if (s[i].flags & LISTENP
	     && listen (s[i].fd, SOMAXCONN) < 0)
	     err (1, "listen %s", s[i].pathname ? s[i].pathname : "tcp");
     *number = n;
     *sockets = s;
     return dpy;
}