Ejemplo n.º 1
0
int netloader_activate(void) {
    struct sockaddr_in serv_addr;
    // create udp socket for broadcast ping
    netloader_udpfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (netloader_udpfd < 0)
    {
        netloader_socket_error("udp socket", errno );
        return -1;
    }

    memset(&serv_addr, '0', sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(NETLOADER_PORT);

    if(bind(netloader_udpfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) {
        netloader_socket_error("bind udp socket", errno );
        return -1;
    }

    if (set_socket_nonblocking(netloader_udpfd) == -1)
    {
        netloader_socket_error("listen fcntl", errno);
        return -1;
    }

    // create listening socket on all addresses on NETLOADER_PORT

    netloader_listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(netloader_listenfd < 0)
    {
        netloader_socket_error("socket", errno );
        return -1;
    }

    int rc = bind(netloader_listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    if(rc != 0)
    {
        netloader_socket_error("bind", errno);
        return -1;
    }

    if (set_socket_nonblocking(netloader_listenfd) == -1)
    {
        netloader_socket_error("listen fcntl", errno);
        return -1;
    }

    rc = listen(netloader_listenfd, 10);
    if(rc != 0)
    {
        netloader_socket_error("listen", errno);
        return -1;
    }

    return 0;
}
Ejemplo n.º 2
0
	int32 EventLoop::startCtl()
	{
		mutex_init(&m_ops_mtx);
		int32 sockets[2];
		if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0)
		{
			return -1;
		}
		m_ctlfdr = sockets[0];
		m_ctlfdw = sockets[1];
		set_socket_nonblocking(m_ctlfdr);
		set_socket_nonblocking(m_ctlfdw);
		return 0;
	}
Ejemplo n.º 3
0
int input_accept_connection(input_t* input)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t len;
        
        int new_fd = accept(input->listen_fd, &addr, &len);
        if (new_fd == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                break;
            }
            else {
                fprintf(stderr, "accept: %s\n", strerror(errno));
                break;
            }
        }
        
        if (set_socket_nonblocking(new_fd) == -1) {
            close(new_fd);
            continue;
        }
        
        struct epoll_event event;
        event.data.fd = new_fd;
        event.events = EPOLLIN;
        
        if (epoll_ctl(input->epoll_fd, EPOLL_CTL_ADD, new_fd, &event) == -1) {
            fprintf(stderr, "epoll_ctl: %s\n", strerror(errno));
            continue;
        }
    }
    return 0;
}
Ejemplo n.º 4
0
/* set all options for a transfer connection */
void ir_setsockopt(int clientsocket)
{
#if !defined(CANT_SET_TOS)
  int tempc;
#endif
  int nodelay = 1;
  int rc;

  updatecontext();

  if (gdata.tcp_buffer_size > 0) {
    ir_setsockopt2(clientsocket, SO_SNDBUF, "SO_SNDBUF", gdata.tcp_buffer_size); /* NOTRANSLATE */
    ir_setsockopt2(clientsocket, SO_RCVBUF, "SO_RCVBUF", gdata.tcp_buffer_size); /* NOTRANSLATE */
  }

#if !defined(CANT_SET_TOS)
  /* Set TOS socket option to max throughput */
  tempc = 0x8; /* IPTOS_THROUGHPUT */
  setsockopt(clientsocket, IPPROTO_IP, IP_TOS, &tempc, sizeof(int));
#endif

  if (gdata.tcp_nodelay != 0) {
    rc = setsockopt(clientsocket, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
    if (rc < 0)
      outerror(OUTERROR_TYPE_WARN, "Couldn't Set TCP_NODELAY");
  }

  if (set_socket_nonblocking(clientsocket, 1) < 0 )
    outerror(OUTERROR_TYPE_WARN, "Couldn't Set Non-Blocking");
}
Ejemplo n.º 5
0
/** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
 */
static int
spawn_cpuworker(void)
{
  tor_socket_t *fdarray;
  tor_socket_t fd;
  connection_t *conn;
  int err;

  fdarray = tor_malloc(sizeof(tor_socket_t)*2);
  if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
    log_warn(LD_NET, "Couldn't construct socketpair for cpuworker: %s",
             tor_socket_strerror(-err));
    tor_free(fdarray);
    return -1;
  }

  tor_assert(SOCKET_OK(fdarray[0]));
  tor_assert(SOCKET_OK(fdarray[1]));

  fd = fdarray[0];
  if (spawn_func(cpuworker_main, (void*)fdarray) < 0) {
    tor_close_socket(fdarray[0]);
    tor_close_socket(fdarray[1]);
    tor_free(fdarray);
    return -1;
  }
  log_debug(LD_OR,"just spawned a cpu worker.");
#ifndef TOR_IS_MULTITHREADED
  tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  tor_free(fdarray);
#endif

  conn = connection_new(CONN_TYPE_CPUWORKER, AF_UNIX);

  /* set up conn so it's got all the data we need to remember */
  conn->s = fd;
  conn->address = tor_strdup("localhost");
  tor_addr_make_unspec(&conn->addr);

  if (set_socket_nonblocking(fd) == -1) {
    connection_free(conn); /* this closes fd */
    return -1;
  }

  if (connection_add(conn) < 0) { /* no space, forget it */
    log_warn(LD_NET,"connection_add for cpuworker failed. Giving up.");
    connection_free(conn); /* this closes fd */
    return -1;
  }

  conn->state = CPUWORKER_STATE_IDLE;
  connection_start_reading(conn);

  return 0; /* success */
}
Ejemplo n.º 6
0
/* complete the connection to the IRC server */
static unsigned int connectirc2(res_addrinfo_t *remote)
{
  int retval;
  int family;

  if (remote->ai_reset)
    gnetwork->serv_resolv.next = 0;

  family = remote->ai_addr.sa_family;
  gnetwork->ircserver = socket(family, remote->ai_socktype, remote->ai_protocol);
  if (gnetwork->ircserver < 0) {
    outerror(OUTERROR_TYPE_WARN_LOUD, "Socket Error: %s", strerror(errno));
    return 1;
  }

  if (gdata.debug > 0) {
    char *msg;
    msg = mymalloc(maxtextlength);
    my_getnameinfo(msg, maxtextlength -1, &(remote->ai_addr));
    ioutput(OUT_S, COLOR_YELLOW, "Connecting to %s", msg);
    mydelete(msg);
  }

  if (bind_irc_vhost(family, gnetwork->ircserver) != 0) {
    outerror(OUTERROR_TYPE_WARN_LOUD, "Couldn't Bind To Virtual Host");
    event_close(gnetwork->ircserver);
    return 1;
  }

  if (set_socket_nonblocking(gnetwork->ircserver, 1) < 0 )
    outerror(OUTERROR_TYPE_WARN, "Couldn't Set Non-Blocking");

  alarm(CTIMEOUT);
  retval = connect(gnetwork->ircserver, &(remote->ai_addr), remote->ai_addrlen);
  if ( (retval < 0) && !((errno == EINPROGRESS) || (errno == EAGAIN)) ) {
    outerror(OUTERROR_TYPE_WARN_LOUD, "Connection to Server Failed: %s", strerror(errno));
    alarm(0);
    event_close(gnetwork->ircserver);
    return 1;
  }
  alarm(0);

  if (gdata.debug > 0) {
    ioutput(OUT_S, COLOR_YELLOW, "ircserver socket = %d", gnetwork->ircserver);
  }

  gnetwork->lastservercontact=gdata.curtime;

  /* good */
  gnetwork->serverstatus = SERVERSTATUS_TRYING;

  return 0;
}
Ejemplo n.º 7
0
/*
 * This is the new connection handler. This function is called by the
 * event handler when data is pending on the listening socket (conn_fd).
 * If space is available, an interactive data structure is initialized and
 * the connected is established.
 */
void new_conn_handler()
{

#ifdef IPV6
	struct sockaddr_in6 client;
#else
    struct sockaddr_in client;
#endif
    socklen_t client_len;
    struct hostent *c_hostent;
    int new_fd;
    int conn_index;

    client_len = sizeof(client);
    new_fd = accept(conn_fd, (struct sockaddr *) & client, &client_len);
    if (new_fd == -1) {
	socket_perror("new_conn_handler: accept", 0);
	return;
    }
    if (set_socket_nonblocking(new_fd, 1) == -1) {
	socket_perror("new_conn_handler: set_socket_nonblocking 1", 0);
	OS_socket_close(new_fd);
	return;
    }
    if (total_conns >= MAX_CONNS) {
	char *message = "no available slots -- closing connection.\n";

	fprintf(stderr, "new_conn_handler: no available connection slots.\n");
	OS_socket_write(new_fd, message, strlen(message));
	if (OS_socket_close(new_fd) == -1)
	    socket_perror("new_conn_handler: close", 0);
	return;
    }
    /* get some information about new connection */
    for (conn_index = 0; conn_index < MAX_CONNS; conn_index++) {
	if (all_conns[conn_index].state == CONN_CLOSED) {
	    DBG(("new_conn_handler: opening conn index %d", conn_index));
	    /* update global data for new fd */
	    all_conns[conn_index].fd = new_fd;
	    all_conns[conn_index].state = CONN_OPEN;
	    all_conns[conn_index].addr = client;

	    char portname[256];
	    if(getnameinfo(&client, sizeof(client), all_conns[conn_index].sname, SNAME_LEN, portname, 255, NI_NAMEREQD|NI_NUMERICHOST))
	    	strcpy(all_conns[conn_index].sname, "<unknown>");
	    total_conns++;
	    return;
	}
    }
    fprintf(stderr, "new_conn_handler: sanity check failed!\n");
}
Ejemplo n.º 8
0
/*
 * This is the new connection handler. This function is called by the
 * event handler when data is pending on the listening socket (conn_fd).
 * If space is available, an interactive data structure is initialized and
 * the connected is established.
 */
void new_conn_handler()
{
    struct sockaddr_in client;
    int client_len;
    struct hostent *c_hostent;
    int new_fd;
    int conn_index;

    client_len = sizeof(client);
    new_fd = accept(conn_fd, (struct sockaddr *) & client, (int *) &client_len);
    if (new_fd == -1) {
	socket_perror("new_conn_handler: accept", 0);
	return;
    }
    if (set_socket_nonblocking(new_fd, 1) == -1) {
	socket_perror("new_conn_handler: set_socket_nonblocking 1", 0);
	OS_socket_close(new_fd);
	return;
    }
    if (total_conns >= MAX_CONNS) {
	char *message = "no available slots -- closing connection.\n";

	fprintf(stderr, "new_conn_handler: no available connection slots.\n");
	OS_socket_write(new_fd, message, strlen(message));
	if (OS_socket_close(new_fd) == -1)
	    socket_perror("new_conn_handler: close", 0);
	return;
    }
    /* get some information about new connection */
    c_hostent = gethostbyaddr((char *) &client.sin_addr.s_addr,
			      sizeof(client.sin_addr.s_addr), AF_INET);
    for (conn_index = 0; conn_index < MAX_CONNS; conn_index++) {
	if (all_conns[conn_index].state == CONN_CLOSED) {
	    DBG(("new_conn_handler: opening conn index %d", conn_index));
	    /* update global data for new fd */
	    all_conns[conn_index].fd = new_fd;
	    all_conns[conn_index].state = CONN_OPEN;
	    all_conns[conn_index].addr = client;
	    if (c_hostent)
		strcpy(all_conns[conn_index].sname, c_hostent->h_name);
	    else
		strcpy(all_conns[conn_index].sname, "<unknown>");
	    total_conns++;
	    return;
	}
    }
    fprintf(stderr, "new_conn_handler: sanity check failed!\n");
}
Ejemplo n.º 9
0
void tostdout_disable_buffering(void)
{
  if (!gdata.stdout_buffer_init)
    {
      return;
    }
  
  set_socket_nonblocking(fileno(stdout),0);
  
  tostdout_write();
  
  ir_boutput_delete(&gdata.stdout_buffer);
  gdata.stdout_buffer_init = 0;
  
  return;
}
Ejemplo n.º 10
0
void setupdccchataccept(dccchat_t *chat)
{
  SIGNEDSOCK int addrlen;
  char *msg;
  
  updatecontext();
  
  addrlen = sizeof(struct sockaddr_in);
  if ((chat->con.clientsocket = accept(chat->con.listensocket, &(chat->con.remote.sa), &addrlen)) < 0)
    {
      outerror(OUTERROR_TYPE_WARN,"Accept Error, Aborting: %s",strerror(errno));
      event_close(chat->con.listensocket);
      chat->con.clientsocket = FD_UNUSED;
      chat->con.listensocket = FD_UNUSED;
      return;
    }

  ir_listen_port_connected(chat->con.localport);

  event_close(chat->con.listensocket);
  chat->con.listensocket = FD_UNUSED;
  
  ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
          "DCC CHAT connection received, authenticating");
  
  if (set_socket_nonblocking(chat->con.clientsocket, 1) < 0 )
    {
      outerror(OUTERROR_TYPE_WARN,"Couldn't Set Non-Blocking");
    }
  
  if (is_in_badip(&(chat->con.remote))) {
    shutdowndccchat(chat, 0);
    return;
  }
  
  chat->status     = DCCCHAT_AUTHENTICATING;
  chat->con.connecttime = gdata.curtime;
  chat->con.lastcontact = gdata.curtime;
  ir_boutput_init(&chat->boutput, chat->con.clientsocket, 0);
  
  msg = mymalloc(maxtextlength);
  my_getnameinfo(msg, maxtextlength -1, &(chat->con.remote.sa));
  chat->con.remoteaddr = mystrdup(msg);
  mydelete(msg);

  setup_chat_banner(chat);
}
Ejemplo n.º 11
0
/* Special case for epoll, where we need to create the fd ahead of time. */
static int epoll_setup(thread_args *args) {
  int epoll_fd;
  struct epoll_event ev;
  set_socket_nonblocking(args);
  epoll_fd = epoll_create(1);
  if (epoll_fd < 0) {
    gpr_log(GPR_ERROR, "epoll_create: %s", strerror(errno));
    return -1;
  }

  args->epoll_fd = epoll_fd;

  ev.events = EPOLLIN | EPOLLET;
  ev.data.fd = args->fds.read_fd;
  if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, args->fds.read_fd, &ev) < 0) {
    gpr_log(GPR_ERROR, "epoll_ctl: %s", strerror(errno));
  }
  return 0;
}
Ejemplo n.º 12
0
int make_bind_socket()
{
    struct addrinfo hints;
    struct addrinfo *result;
    
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    
    if (getaddrinfo(NULL, PORT, &hints, &result) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(errno));
        return -1;
    }
    
    int fd;
    struct addrinfo *r;
    for(r = result; r != NULL; r = r->ai_next) {
        if ((fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1) {
            continue;
        }
        
        int yes = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); 
        
        if (bind(fd, r->ai_addr, r->ai_addrlen) == 0) {
            break;
        }
        close(fd);
    }
    if (r == NULL) {
        fprintf(stderr, "could not bind\n");
        return -1;
    }
    
    freeaddrinfo(result);
    if (set_socket_nonblocking(fd) == -1) {
        close(fd);
        return -1;
    }
    return fd;
}
Ejemplo n.º 13
0
/* Accepts an incoming connection on 'socket' and adds it to the connections vector 'list'.*/
static int acceptConnection(std::vector<ConnectionData> *list, int socket){
    sockaddr_in clientAddr;
    socklen_t addrSize = sizeof(clientAddr);

    // accept a single incoming connection
    int clientfd = accept( socket, (sockaddr*)&clientAddr, &addrSize );

    if( -1 == clientfd )
	{
	    perror( "accept() failed" );
	    return -1;
	}

#			if VERBOSE
    // print some information about the new client
    char buff[128];
    printf( "Connection from %s:%d -> socket %d\n",
	    inet_ntop( AF_INET, &clientAddr.sin_addr, buff, sizeof(buff) ),
	    ntohs(clientAddr.sin_port),
	    clientfd
	    );
    fflush( stdout );
#			endif

#			if NONBLOCKING
    // enable non-blocking sends and receives on this socket
    if( !set_socket_nonblocking( clientfd ) )
	return -1;
#			endif

    // initialize connection data
    ConnectionData connData;
    memset( &connData, 0, sizeof(connData) );

    connData.sock = clientfd;
    connData.state = eConnStateReceiving;

    list->push_back(connData); // Add connection to the list

    return 0;
}
Ejemplo n.º 14
0
/*
 * Create an LPC efun socket
 */
int socket_create (enum socket_mode mode, svalue_t * read_callback, svalue_t * close_callback)
{
    int type, i, fd, optval;
#ifndef NO_BUFFER_TYPE
    int binary = 0;

    if (mode == STREAM_BINARY) {
        binary = 1;
        mode = STREAM;
    } else if (mode == DATAGRAM_BINARY) {
        binary = 1;
        mode = DATAGRAM;
    }
#endif
    switch (mode) {

        case MUD:
        case STREAM:
            type = SOCK_STREAM;
            break;
        case DATAGRAM:
            type = SOCK_DGRAM;
            break;

        default:
            return EEMODENOTSUPP;
    }

    i = find_new_socket();
    if (i >= 0) {
#ifdef IPV6
        fd = socket(PF_INET6, type, 0);
#else
        fd = socket(PF_INET, type, 0);
#endif
        if (fd == INVALID_SOCKET) {
            socket_perror("socket_create: socket", 0);
            return EESOCKET;
        }
        optval = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &optval,
                    sizeof(optval)) == -1) {
            socket_perror("socket_create: setsockopt", 0);
            OS_socket_close(fd);
            return EESETSOCKOPT;
        }
        if (set_socket_nonblocking(fd, 1) == -1) {
            socket_perror("socket_create: set_socket_nonblocking", 0);
            OS_socket_close(fd);
            return EENONBLOCK;
        }
        lpc_socks[i].fd = fd;
        lpc_socks[i].flags = S_HEADER;

        if (type == SOCK_DGRAM) close_callback = 0;
        set_read_callback(i, read_callback);
        set_write_callback(i, 0);
        set_close_callback(i, close_callback);

#ifndef NO_BUFFER_TYPE
        if (binary) {
            lpc_socks[i].flags |= S_BINARY;
        }
#endif
        lpc_socks[i].mode = mode;
        lpc_socks[i].state = STATE_UNBOUND;
        memset((char *) &lpc_socks[i].l_addr, 0, sizeof(lpc_socks[i].l_addr));
        memset((char *) &lpc_socks[i].r_addr, 0, sizeof(lpc_socks[i].r_addr));
        lpc_socks[i].owner_ob = current_object;
        lpc_socks[i].release_ob = NULL;
        lpc_socks[i].r_buf = NULL;
        lpc_socks[i].r_off = 0;
        lpc_socks[i].r_len = 0;
        lpc_socks[i].w_buf = NULL;
        lpc_socks[i].w_off = 0;
        lpc_socks[i].w_len = 0;

        current_object->flags |= O_EFUN_SOCKET;

        debug(sockets, ("socket_create: created socket %d mode %d fd %d\n",
                    i, mode, fd));
    }

    return i;
}
Ejemplo n.º 15
0
//--    setup_server_socket()   ///{{{1///////////////////////////////////////
static int setup_server_socket( short port )
{
    // create new socket file descriptor
    int fd = socket( AF_INET, SOCK_STREAM, 0 );
    if( -1 == fd )
	{
	    perror( "socket() failed" );
	    return -1;
	}

    // bind socket to local address
    sockaddr_in servAddr; 
    memset( &servAddr, 0, sizeof(servAddr) );

    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(port);

    if( -1 == bind( fd, (const sockaddr*)&servAddr, sizeof(servAddr) ) )
	{
	    perror( "bind() failed" );
	    close( fd );
	    return -1;
	}

    // get local address (i.e. the address we ended up being bound to)
    sockaddr_in actualAddr;
    socklen_t actualAddrLen = sizeof(actualAddr);
    memset( &actualAddr, 0, sizeof(actualAddr) );

    if( -1 == getsockname( fd, (sockaddr*)&actualAddr, &actualAddrLen ) )
	{
	    perror( "getsockname() failed" );
	    close( fd );
	    return -1;
	}

    char actualBuff[128];
    printf( "Socket is bound to %s %d\n", 
	    inet_ntop( AF_INET, &actualAddr.sin_addr, actualBuff, sizeof(actualBuff) ),
	    ntohs(actualAddr.sin_port)
	    );

    // and start listening for incoming connections
    if( -1 == listen( fd, kServerBacklog ) )
	{
	    perror( "listen() failed" );
	    close( fd );
	    return -1;
	}

    // allow immediate reuse of the address (ip+port)
    int one = 1;
    if( -1 == setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int) ) )
	{
	    perror( "setsockopt() failed" );
	    close( fd );
	    return -1;
	}

#	if NONBLOCKING
    // enable non-blocking mode
    if( !set_socket_nonblocking( fd ) )
	{
	    close( fd );
	    return -1;
	}
#	endif

    return fd;
}
Ejemplo n.º 16
0
inline void set_socket_nonblocking( Socket const &s )
{
    set_socket_nonblocking( s.fd() );
}
Ejemplo n.º 17
0
inline void set_socket_nonblocking( SocketPtr const &s )
{
    set_socket_nonblocking( s->fd() );
}
Ejemplo n.º 18
0
/* accept incoming connection */
static void telnet_accept(unsigned int i)
{
  gnetwork_t *backup;
  char *msg;
  dccchat_t *chat;
  SIGNEDSOCK int addrlen;

  updatecontext();

  chat = irlist_add(&gdata.dccchats, sizeof(dccchat_t));
  chat->name = "telnet"; /* NOTRANSLATE */
  chat->status = DCCCHAT_UNUSED;
  chat->con.family = telnet_family[i];
  if (chat->con.family != AF_INET) {
    addrlen = sizeof (struct sockaddr_in6);
    chat->con.clientsocket = accept(telnet_listen[i], &(chat->con.remote.sa), &addrlen);
  } else {
    addrlen = sizeof (struct sockaddr_in);
    chat->con.clientsocket = accept(telnet_listen[i], &(chat->con.remote.sa), &addrlen);
  }
  if (chat->con.clientsocket < 0) {
    outerror(OUTERROR_TYPE_WARN, "Accept Error, Aborting: %s", strerror(errno));
    return;
  }

  if (set_socket_nonblocking(chat->con.clientsocket, 1) < 0 ) {
    outerror(OUTERROR_TYPE_WARN, "Couldn't Set Non-Blocking");
  }

  addrlen = sizeof(chat->con.local);
  if (getsockname(chat->con.clientsocket, &(chat->con.local.sa), &addrlen) < 0) {
    outerror(OUTERROR_TYPE_WARN_LOUD, "Couldn't get sock name: %s", strerror(errno));
    shutdown_close(chat->con.clientsocket);
    chat->con.clientsocket = FD_UNUSED;
    return;
  }

  ++(gdata.num_dccchats);
  chat->status = DCCCHAT_AUTHENTICATING;
  chat->net = 0;
  chat->nick = mystrdup("telnet"); /* NOTRANSLATE */
  chat->hostmask = to_hostmask(chat->nick, "telnet"); /* NOTRANSLATE */
  chat->con.localport = gdata.telnet_port;
  chat->con.connecttime = gdata.curtime;
  chat->con.lastcontact = gdata.curtime;

  msg = mymalloc(maxtextlength);
  my_getnameinfo(msg, maxtextlength -1, &(chat->con.remote.sa));
  chat->con.localaddr = mystrdup(msg);
  my_getnameinfo(msg, maxtextlength -1, &(chat->con.local.sa));
  chat->con.remoteaddr = mystrdup(msg);
  ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
          "Telnet connection received from %s",  msg);
  mydelete(msg);

  if (is_in_badip(&(chat->con.remote))) {
    shutdowndccchat(chat, 0);
    return;
  }

  if (irlist_size(&gdata.telnet_allow) > 0) {
    if (!verify_cidr(&gdata.telnet_allow, &(chat->con.remote))) {
      shutdowndccchat(chat, 0);
      return;
    }
  }

  if (verify_cidr(&gdata.telnet_deny, &(chat->con.remote))) {
    shutdowndccchat(chat, 0);
    return;
  }

  ir_boutput_init(&chat->boutput, chat->con.clientsocket, 0);

  backup = gnetwork;
  gnetwork = &(gdata.networks[chat->net]);
  setup_chat_banner(chat);
  gnetwork = backup;
}
Ejemplo n.º 19
0
static void t_passive(transfer * const tr, ir_uint16 remoteport)
{
    char *msg;
    ir_uint32 netval;
    SIGNEDSOCK int addrlen;
    int retval;

    updatecontext();

    bzero ((char *) &(tr->con.remote), sizeof(tr->con.remote));
    tr->con.clientsocket = socket(tr->con.family, SOCK_STREAM, 0);
    if (tr->con.clientsocket < 0) {
        t_closeconn(tr, "Socket Error", errno);
        return;
    }

    if (tr->con.family == AF_INET ) {
        addrlen = sizeof(struct sockaddr_in);
        tr->con.remote.sin.sin_family = AF_INET;
        tr->con.remote.sin.sin_port = htons(remoteport);
        netval = atoul(tr->con.remoteaddr);
        tr->con.remote.sin.sin_addr.s_addr = htonl(netval);
    } else {
        addrlen = sizeof(struct sockaddr_in6);
        tr->con.remote.sin6.sin6_family = AF_INET6;
        tr->con.remote.sin6.sin6_port = htons(remoteport);
        retval = inet_pton(AF_INET6, tr->con.remoteaddr, &(tr->con.remote.sin6.sin6_addr));
        if (retval < 0)
            outerror(OUTERROR_TYPE_WARN_LOUD, "Invalid IP: %s", tr->con.remoteaddr);
    }

    if (t_check_ip_access(tr))
        return;

    if (bind_irc_vhost(tr->con.family, tr->con.clientsocket) != 0) {
        t_closeconn(tr, "Couldn't Bind Virtual Host, Sorry", errno);
        return;
    }

    if (set_socket_nonblocking(tr->con.clientsocket, 1) < 0 ) {
        outerror(OUTERROR_TYPE_WARN, "Couldn't Set Non-Blocking");
    }

    if (gdata.debug > 0) {
        msg = mymalloc(maxtextlength);
        my_getnameinfo(msg, maxtextlength -1, &(tr->con.remote.sa));
        ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
                "DCC SEND passive sent to %s on %s, connecting to %s",
                tr->nick, gnetwork->name, msg);
        mydelete(msg);
    }

    alarm(CTIMEOUT);
    retval = connect(tr->con.clientsocket, &(tr->con.remote.sa), addrlen);
    if ( (retval < 0) && !((errno == EINPROGRESS) || (errno == EAGAIN)) ) {
        t_closeconn(tr, "Couldn't Connect", errno);
        alarm(0);
        return;
    }
    alarm(0);

    tr->tr_status = TRANSFER_STATUS_CONNECTING;
}
Ejemplo n.º 20
0
//--    main()              ///{{{1///////////////////////////////////////////
int main( int argc, char* argv[] )
{
	int serverPort = kServerPort;

	// did the user specify a port?
	if( 2 == argc )
	{
		serverPort = atoi(argv[1]);
	}

#	if VERBOSE
	printf( "Attempting to bind to port %d\n", serverPort );
#	endif

	// set up listening socket - see setup_server_socket() for details.
	int listenfd = setup_server_socket( serverPort );

	if( -1 == listenfd )
		return 1;

	// loop forever
	while( 1 )
	{
		sockaddr_in clientAddr;
		socklen_t addrSize = sizeof(clientAddr);

		// accept a single incoming connection
		int clientfd = accept( listenfd, (sockaddr*)&clientAddr, &addrSize );
		printf("Accepted a new client.. \n");

		if( -1 == clientfd )
		{
			perror( "accept() failed" );
			continue; // attempt to accept a different client.
		}

#			if VERBOSE
		// print some information about the new client
		char buff[128];
		printf( "Connection from %s:%d -> socket %d\n",
			inet_ntop( AF_INET, &clientAddr.sin_addr, buff, sizeof(buff) ),
			ntohs(clientAddr.sin_port),
			clientfd
		);
		fflush( stdout );
#			endif

#			if NONBLOCKING
		// enable non-blocking sends and receives on this socket
		if( !set_socket_nonblocking( clientfd ) )
			continue;
#			endif

		// initialize connection data
		ConnectionData connData;
		memset( &connData, 0, sizeof(connData) );

		connData.sock = clientfd;
		connData.state = eConnStateReceiving;

		// Repeatedly receive and re-send data from the connection. When
		// the connection closes, process_client_*() will return false, no
		// further processing is done.
		bool processFurther = true;
		while( processFurther )
		{
			while( processFurther && connData.state == eConnStateReceiving )
				processFurther = process_client_recv( connData );

			while( processFurther && connData.state == eConnStateSending )
				processFurther = process_client_send( connData );
		}

		// done - close connection
		close( connData.sock );
	}

	// The program will never reach this part, but for demonstration purposes,
	// we'll clean up the server resources here and then exit nicely.
	close( listenfd );

	return 0;
}
Ejemplo n.º 21
0
/** Allocate a new set of alert sockets, and set the appropriate function
 * pointers, in <b>socks_out</b>. */
int
alert_sockets_create(alert_sockets_t *socks_out, uint32_t flags)
{
  tor_socket_t socks[2] = { TOR_INVALID_SOCKET, TOR_INVALID_SOCKET };

#ifdef HAVE_EVENTFD
  /* First, we try the Linux eventfd() syscall.  This gives a 64-bit counter
   * associated with a single file descriptor. */
#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
  if (!(flags & ASOCKS_NOEVENTFD2))
    socks[0] = eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK);
#endif
  if (socks[0] < 0 && !(flags & ASOCKS_NOEVENTFD)) {
    socks[0] = eventfd(0,0);
    if (socks[0] >= 0) {
      if (fcntl(socks[0], F_SETFD, FD_CLOEXEC) < 0 ||
          set_socket_nonblocking(socks[0]) < 0) {
        close(socks[0]);
        return -1;
      }
    }
  }
  if (socks[0] >= 0) {
    socks_out->read_fd = socks_out->write_fd = socks[0];
    socks_out->alert_fn = eventfd_alert;
    socks_out->drain_fn = eventfd_drain;
    return 0;
  }
#endif

#ifdef HAVE_PIPE2
  /* Now we're going to try pipes. First type the pipe2() syscall, if we
   * have it, so we can save some calls... */
  if (!(flags & ASOCKS_NOPIPE2) &&
      pipe2(socks, O_NONBLOCK|O_CLOEXEC) == 0) {
    socks_out->read_fd = socks[0];
    socks_out->write_fd = socks[1];
    socks_out->alert_fn = pipe_alert;
    socks_out->drain_fn = pipe_drain;
    return 0;
  }
#endif

#ifdef HAVE_PIPE
  /* Now try the regular pipe() syscall.  Pipes have a bit lower overhead than
   * socketpairs, fwict. */
  if (!(flags & ASOCKS_NOPIPE) &&
      pipe(socks) == 0) {
    if (fcntl(socks[0], F_SETFD, FD_CLOEXEC) < 0 ||
        fcntl(socks[1], F_SETFD, FD_CLOEXEC) < 0 ||
        set_socket_nonblocking(socks[0]) < 0 ||
        set_socket_nonblocking(socks[1]) < 0) {
      close(socks[0]);
      close(socks[1]);
      return -1;
    }
    socks_out->read_fd = socks[0];
    socks_out->write_fd = socks[1];
    socks_out->alert_fn = pipe_alert;
    socks_out->drain_fn = pipe_drain;
    return 0;
  }
#endif

  /* If nothing else worked, fall back on socketpair(). */
  if (!(flags & ASOCKS_NOSOCKETPAIR) &&
      tor_socketpair(AF_UNIX, SOCK_STREAM, 0, socks) == 0) {
    if (set_socket_nonblocking(socks[0]) < 0 ||
        set_socket_nonblocking(socks[1])) {
      tor_close_socket(socks[0]);
      tor_close_socket(socks[1]);
      return -1;
    }
    socks_out->read_fd = socks[0];
    socks_out->write_fd = socks[1];
    socks_out->alert_fn = sock_alert;
    socks_out->drain_fn = sock_drain;
    return 0;
  }
  return -1;
}
Ejemplo n.º 22
0
int setupdccchat(const char *nick,
                 const char *hostmask,
                 const char *line)
{
  char *ip, *port;
  SIGNEDSOCK int addrlen;
  int retval;
  dccchat_t *chat;
  char *msg;
  
  updatecontext();
  
  ip = getpart(line,7);
  port = getpart(line,8);
  
  if ( !ip || !port )
    {
      mydelete(ip);
      mydelete(port);
      return 1;
    }
  
  /* support passive dcc */
  if (strcmp(port, "0") == 0)
    {
      char *token;

      mydelete(ip);
      mydelete(port);
      if (gdata.passive_dcc_chat)
        {
          token = getpart(line, 9);
          setupdccchatout(nick, hostmask, token);
          mydelete(token);
        }
      else
        {
          notice(nick, "DCC passive Chat denied, use \"/MSG %s ADMIN password CHATME\" instead.", get_user_nick());
          ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
                  "DCC CHAT attempt denied from %s (%s on %s)",
                  nick, hostmask, gnetwork->name);
        }
      return 1;
    }
  
  chat = irlist_add(&gdata.dccchats, sizeof(dccchat_t));
  chat->name = gnetwork->name;
  
  bzero((char *) &(chat->con.remote), sizeof(chat->con.remote));
  
  chat->con.family = (strchr(ip, ':')) ? AF_INET6 : AF_INET;
  chat->con.clientsocket = socket(chat->con.family, SOCK_STREAM, 0);
  if (chat->con.clientsocket < 0)
    {
      outerror(OUTERROR_TYPE_WARN_LOUD,"Socket Error: %s", strerror(errno));
      chat->con.clientsocket = FD_UNUSED;
      mydelete(ip);
      mydelete(port);
      return 1;
    }
  
  port[strlen(port)-1] = '\0';
  if (chat->con.family == AF_INET)
    {
      addrlen = sizeof(struct sockaddr_in);
      chat->con.remote.sin.sin_family = AF_INET;
      chat->con.remote.sin.sin_port = htons(atoi(port));
      chat->con.remote.sin.sin_addr.s_addr = htonl(atoul(ip));
    }
  else
    {
      addrlen = sizeof(struct sockaddr_in6);
      chat->con.remote.sin6.sin6_family = AF_INET6;
      chat->con.remote.sin6.sin6_port = htons(atoi(port));
      retval = inet_pton(AF_INET6, ip, &(chat->con.remote.sin6.sin6_addr));
      if (retval != 0)
        outerror(OUTERROR_TYPE_WARN_LOUD, "Invalid IP: %s", ip);
    }
  
  mydelete(port);
  mydelete(ip);
  
  if (is_in_badip(&(chat->con.remote))) {
    shutdowndccchat(chat, 0);
    return 1;
  }
  
  if (bind_irc_vhost(chat->con.family, chat->con.clientsocket) != 0)
    {
      outerror(OUTERROR_TYPE_WARN_LOUD, "Couldn't Bind To Virtual Host: %s", strerror(errno));
      chat->con.clientsocket = FD_UNUSED;
      return 1;
    }
  
  if (set_socket_nonblocking(chat->con.clientsocket, 1) < 0 )
    {
      outerror(OUTERROR_TYPE_WARN,"Couldn't Set Non-Blocking");
    }
  
  alarm(CTIMEOUT);
  retval = connect(chat->con.clientsocket, &(chat->con.remote.sa), addrlen);
  if ((retval < 0) && !((errno == EINPROGRESS) || (errno == EAGAIN)))
    {
      outerror(OUTERROR_TYPE_WARN_LOUD,"Connection to DCC Chat Failed: %s", strerror(errno));
      chat->con.clientsocket = FD_UNUSED;
      return 1;
    }
  alarm(0);
  
  addrlen = sizeof(chat->con.local);
  if (getsockname(chat->con.clientsocket, &(chat->con.local.sa), &addrlen) < 0)
    {
      outerror(OUTERROR_TYPE_WARN_LOUD,"Couldn't get sock name: %s", strerror(errno));
      chat->con.clientsocket = FD_UNUSED;
      return 1;
    }
  
  if (gdata.debug > 0)
    {
      ioutput(OUT_S, COLOR_YELLOW, "dccchat socket = %d", chat->con.clientsocket);
    }
  
  gdata.num_dccchats++;
  chat->status = DCCCHAT_CONNECTING;
  chat->nick = mystrdup(nick);
  chat->hostmask = mystrdup(hostmask);
  chat->con.localport  = 0;
  chat->con.connecttime = gdata.curtime;
  chat->con.lastcontact = gdata.curtime;
  chat->net = gnetwork->net;
  
  msg = mymalloc(maxtextlength);
  my_getnameinfo(msg, maxtextlength -1, &(chat->con.local.sa));
  chat->con.localaddr = mystrdup(msg);
  my_getnameinfo(msg, maxtextlength -1, &(chat->con.remote.sa));
  chat->con.remoteaddr = mystrdup(msg);
  mydelete(msg);
  ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
          "DCC CHAT received from %s on %s, attempting connection to %s",
          nick, chat->name, chat->con.remoteaddr);
  return 0;
}
Ejemplo n.º 23
0
/*
 * Initialize connection socket.
 */
void init_conn_sock (int port_num, char * ipaddress)
{
#ifdef IPV6
	struct sockaddr_in6 sin;
#else
    struct sockaddr_in sin;
#endif
    socklen_t sin_len;
    int optval;
#ifdef WINSOCK
    WSADATA WSAData;

    WSAStartup(MAKEWORD(1,1), &WSAData);
    atexit(cleanup_sockets);
#endif

    /*
     * create socket of proper type.
     */
#ifdef IPV6
    if ((conn_fd = socket(AF_INET6, SOCK_STREAM, 0)) == INVALID_SOCKET) {
#else
    if ((conn_fd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
#endif
	socket_perror("init_conn_sock: socket", 0);
	exit(1);
    }
    /*
     * enable local address reuse.
     */
    optval = 1;
    if (setsockopt(conn_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &optval,
		   sizeof(optval)) == -1) {
	socket_perror("init_conn_sock: setsockopt", 0);
	exit(2);
    }
    /*
     * fill in socket address information.
     */
#ifdef IPV6
    sin.sin6_family = AF_INET6;
    if(ipaddress)
       	inet_pton(AF_INET6, ipaddress, &(sin.sin6_addr));
    else
       	sin.sin6_addr = in6addr_any;
    sin.sin6_port = htons((u_short) port_num);
#else
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = (ipaddress ? inet_addr(ipaddress) : INADDR_ANY);
    sin.sin_port = htons((u_short) port_num);
#endif
    /*
     * bind name to socket.
     */
    if (bind(conn_fd, (struct sockaddr *) & sin, sizeof(sin)) == -1) {
	socket_perror("init_conn_sock: bind", 0);
	exit(3);
    }
    /*
     * get socket name.
     */
    sin_len = sizeof(sin);
    if (getsockname(conn_fd, (struct sockaddr *) & sin, &sin_len) == -1) {
	socket_perror("init_conn_sock: getsockname", 0);
	exit(4);
    }
    /*
     * register signal handler for SIGPIPE.
     */
#if defined(SIGPIPE) && defined(SIGNAL_ERROR)/* windows has no SIGPIPE */
    if (signal(SIGPIPE, sigpipe_handler) == SIGNAL_ERROR) {
	socket_perror("init_conn_sock: signal SIGPIPE", 0);
	exit(5);
    }
#endif
    /*
     * set socket non-blocking
     */
    if (set_socket_nonblocking(conn_fd, 1) == -1) {
	socket_perror("init_conn_sock: set_socket_nonblocking 1", 0);
	exit(8);
    }
    /*
     * listen on socket for connections.
     */
    if (listen(conn_fd, 128) == -1) {
	socket_perror("init_conn_sock: listen", 0);
	exit(10);
    }
    DBG(("listening for connections on port %d", port_num));
}

/*
 * SIGPIPE handler -- does very little for now.
 */
#ifdef SIGNAL_FUNC_TAKES_INT
void sigpipe_handler (int sig)
{
#else
void sigpipe_handler()
{
#endif
    fprintf(stderr, "SIGPIPE received.\n");
}
Ejemplo n.º 24
0
/*
 * Initialize connection socket.
 */
void init_conn_sock P1(int, port_num)
{
    struct sockaddr_in sin;
    int sin_len;
    int optval;
#ifdef WINSOCK
    WSADATA WSAData;

#define CLEANUP WSACleanup()

    WSAStartup(MAKEWORD(1,1), &WSAData);
#else
#define CLEANUP
#endif

    /*
     * create socket of proper type.
     */
    if ((conn_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	perror("init_conn_sock: socket");
	CLEANUP;
	exit(1);
    }
    /*
     * enable local address reuse.
     */
    optval = 1;
    if (setsockopt(conn_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &optval,
		   sizeof(optval)) == -1) {
	perror("init_conn_sock: setsockopt");
	CLEANUP;
	exit(2);
    }
    /*
     * fill in socket address information.
     */
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons((u_short) port_num);
    /*
     * bind name to socket.
     */
    if (bind(conn_fd, (struct sockaddr *) & sin, sizeof(sin)) == -1) {
	perror("init_conn_sock: bind");
	CLEANUP;
	exit(3);
    }
    /*
     * get socket name.
     */
    sin_len = sizeof(sin);
    if (getsockname(conn_fd, (struct sockaddr *) & sin, &sin_len) == -1) {
	perror("init_conn_sock: getsockname");
	CLEANUP;
	exit(4);
    }
    /*
     * register signal handler for SIGPIPE.
     */
#if !defined(LATTICE) && defined(SIGPIPE) /* windows has no SIGPIPE */
    if (signal(SIGPIPE, sigpipe_handler) == SIGNAL_ERROR) {
	perror("init_conn_sock: signal SIGPIPE");
	CLEANUP;
	exit(5);
    }
#endif
    /*
     * set socket non-blocking
     */
    if (set_socket_nonblocking(conn_fd, 1) == -1) {
	perror("init_user_conn: set_socket_nonblocking 1");
	CLEANUP;
	exit(8);
    }
    /*
     * listen on socket for connections.
     */
    if (listen(conn_fd, 128) == -1) {
	perror("init_conn_sock: listen");
	CLEANUP;
	exit(10);
    }
    debug(512, ("addr_server: listening for connections on port %d\n",
		port_num));
}