static void server_recv_cb (EV_P_ ev_io *w, int revents) { struct server_ctx *server_recv_ctx = (struct server_ctx *)w; struct server *server = server_recv_ctx->server; struct remote *remote = NULL; int len = server->buf_len; char **buf = &server->buf; ev_timer_again(EV_A_ &server->recv_ctx->watcher); if (server->stage != 0) { remote = server->remote; buf = &remote->buf; len = 0; } ssize_t r = recv(server->fd, *buf + len, BUF_SIZE - len, 0); if (r == 0) { // connection closed if (verbose) { LOGD("server_recv close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else if (r == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; } else { ERROR("server recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } // handle incomplete header if (server->stage == 0) { r += server->buf_len; if (r <= enc_get_iv_len()) { // wait for more if (verbose) { LOGD("imcomplete header: %zu", r); } server->buf_len = r; return; } else { server->buf_len = 0; } } *buf = ss_decrypt(BUF_SIZE, *buf, &r, server->d_ctx); if (*buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } // handshake and transmit data if (server->stage == 5) { int s = send(remote->fd, remote->buf, r, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf_len = r; remote->buf_idx = 0; ev_io_stop(EV_A_ &server_recv_ctx->io); ev_io_start(EV_A_ &remote->send_ctx->io); } else { ERROR("server_recv_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; ev_io_stop(EV_A_ &server_recv_ctx->io); ev_io_start(EV_A_ &remote->send_ctx->io); } return; } else if (server->stage == 0) { /* * Shadowsocks Protocol: * * +------+----------+----------+ * | ATYP | DST.ADDR | DST.PORT | * +------+----------+----------+ * | 1 | Variable | 2 | * +------+----------+----------+ */ int offset = 0; char atyp = server->buf[offset++]; char host[256] = {0}; char port[64] = {0}; // get remote addr and port if (atyp == 1) { // IP V4 size_t in_addr_len = sizeof(struct in_addr); if (r > in_addr_len) { inet_ntop(AF_INET, (const void *)(server->buf + offset), host, INET_ADDRSTRLEN); offset += in_addr_len; } } else if (atyp == 3) { // Domain name uint8_t name_len = *(uint8_t *)(server->buf + offset); if (name_len < r && name_len < 255 && name_len > 0) { memcpy(host, server->buf + offset + 1, name_len); offset += name_len + 1; } } else if (atyp == 4) { // IP V6 size_t in6_addr_len = sizeof(struct in6_addr); if (r > in6_addr_len) { inet_ntop(AF_INET6, (const void*)(server->buf + offset), host, INET6_ADDRSTRLEN); offset += in6_addr_len; } } if (offset == 1) { LOGE("invalid header with addr type %d", atyp); close_and_free_server(EV_A_ server); return; } sprintf(port, "%d", ntohs(*(uint16_t *)(server->buf + offset))); offset += 2; if (verbose) { LOGD("connect to: %s:%s", host, port); } struct addrinfo hints; asyncns_query_t *query; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; query = asyncns_getaddrinfo(server->listen_ctx->asyncns, host, port, &hints); if (query == NULL) { ERROR("asyncns_getaddrinfo"); close_and_free_server(EV_A_ server); return; } asyncns_setuserdata(server->listen_ctx->asyncns, query, server); // XXX: should handle buffer carefully if (r > offset) { server->buf_len = r - offset; server->buf_idx = offset; } server->stage = 4; server->query = query; ev_io_stop(EV_A_ &server_recv_ctx->io); return; } // should not reach here FATAL("server context error."); }
int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAX_PACKET_LEN]; struct addrinfo hints, *servinfo, *p; int status; char s[INET6_ADDRSTRLEN]; // Command Line arguments will fill these out char* hostname; char* port; unsigned char operation; char* message_in; if (argc != 5) { fprintf(stderr, "Usage Error: Params\n"); exit(1); } // Get the params from command line hostname = argv[1]; port = argv[2]; operation = (unsigned char)atoi(argv[3]); message_in = argv[4]; if (DEBUG) { printf("argv[1] or hostname: %s\n", argv[1]); printf("argv[2] or port: %s\n", argv[2]); printf("argv[3] or operation: %s\n", argv[3]); printf("argv[4] or message: %s\n", argv[4]); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((status = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); return 1; } // Loop through all the results and connect to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Socket error"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Connect error"); continue; } break; } if (p == NULL) { fprintf(stderr, "Failed to connect!\n"); return 2; } if (DEBUG) { inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("Connected to: %s\n", s); } freeaddrinfo(servinfo); // All done with this structure // Create the outgoing packet and fill it in tx_packet packet_out; strcpy(packet_out.message, message_in); packet_out.TML = htons(sizeof(packet_out.TML) + sizeof(packet_out.RID) + sizeof(packet_out.operation) + strlen(packet_out.message)); packet_out.operation = operation; // Create a random RID, between 0 and 60,000 // Bug: If you send multiple packets within 1 second of each other they will // have the same RID. Caused by time() only updating every second. srand(time(NULL)); unsigned short random = rand() % 600001; packet_out.RID = htons(random); if (DEBUG) { printf("packet_out.TML: %d\n", ntohs(packet_out.TML)); printf("packet_out.RID: %d\n", ntohs(packet_out.RID)); printf("packet_out.TML: %d\n", packet_out.operation); printf("packet_out.TML: %s\n", packet_out.message); } if (send(sockfd, (char *)&packet_out, ntohs(packet_out.TML), 0) == -1) { perror("Send Error"); } // Depending on the operation we requested will decide what kind of packet we will recieve // vLength was requested if (operation == V_LENGTH) { // Prepare the packet int numbytes_rec_vLength; rx_vLength packet_in_vLength; if ((numbytes_rec_vLength = recv(sockfd, (char *)&packet_in_vLength, MAX_PACKET_LEN, 0)) == -1) { perror("recv error"); exit(1); } if(DEBUG) { printf("Packet Recieved!\n"); printf("packet_in_vLength.TML: %d\n", ntohs(packet_in_vLength.TML)); printf("packet_in_vLength.RID: %d\n", ntohs(packet_in_vLength.RID)); printf("packet_in_vLength.vLength: %d\n", ntohs(packet_in_vLength.vLength)); } } // disVowel was requested if (operation == DISEMVOWEL) { // Prepare the packet int numbytes_rec_disVowel; rx_disVowel packet_in_disVowel; if ((numbytes_rec_disVowel = recv(sockfd, (char *)&packet_in_disVowel, MAX_PACKET_LEN, 0)) == -1) { perror("recv error"); exit(1); } // Add the null terminator, just in case. -4 becuase of header packet_in_disVowel.message[numbytes_rec_disVowel - 4] = '\0'; if(DEBUG) { printf("Packet Recieved!\n"); printf("packet_in_disVowel.TML: %d\n", ntohs(packet_in_disVowel.TML)); printf("packet_in_disVowel.RID: %d\n", ntohs(packet_in_disVowel.RID)); printf("packet_in_disVowel.message: %s\n", packet_in_disVowel.message); } } close(sockfd); return 0; }
int main(void) { int lfd,cfd,len,i,cli_len,j; int serv_port=SERV_PORT; pid_t pid; char buf[1024],cli_ip[128]; struct sockaddr_in ser_addr,cli_addr; struct sigaction act; act.sa_flags=0; act.sa_handler=do_sig; sigemptyset(&act.sa_mask); sigaction(SIGCHLD,&act,NULL); lfd=socket(AF_INET,SOCK_STREAM,0); bzero(&ser_addr,sizeof(ser_addr)); ser_addr.sin_family=AF_INET; ser_addr.sin_port=htons((short)serv_port); ser_addr.sin_addr.s_addr=htonl(INADDR_ANY); bind(lfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)); listen(lfd,128); j=0; while(1){ cli_len=sizeof(cli_addr); cfd=accept(lfd,(struct sockaddr*)&cli_addr,&cli_len); if(cfd<0){ if((errno==ECONNABORTED)||(errno=EINTR)){ continue; }else { break; } } printf("client is connect %d :%s[%d]\n",j++,inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,cli_ip,sizeof(cli_ip)),ntohs(cli_addr.sin_port)); pid=fork(); if(pid==0){ close(lfd); while(1){ len=read(cfd,buf,sizeof(buf)); if(len<=0){ break; } write(STDOUT_FILENO,buf,len); for(i=0;i<len;i++){ buf[i]=toupper(buf[i]); } write(cfd,buf,len); } close(cfd); exit(1); } else if(pid>0) { close(cfd); } else { perror("fork"); exit(1); } } close(lfd); return 0; }
TCPStream::TCPStream(int sd, struct sockaddr_in* address) : m_sd(sd) { char ip[50]; inet_ntop(PF_INET, (struct in_addr*)&(address->sin_addr.s_addr), ip, sizeof(ip)-1); m_peerIP = ip; m_peerPort = ntohs(address->sin_port); }
/** * Install state of type 'type' for a dynamic session. * The hash table contains two type of rules: * - regular rules (O_KEEP_STATE) * - rules for sessions with limited number of sess per user * (O_LIMIT). When they are created, the parent is * increased by 1, and decreased on delete. In this case, * the third parameter is the parent rule and not the chain. * - "parent" rules for the above (O_LIMIT_PARENT). */ static ipfw_dyn_rule * add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule) { ipfw_dyn_rule *r; int i; IPFW_DYN_LOCK_ASSERT(); if (V_ipfw_dyn_v == NULL || (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) { realloc_dynamic_table(); if (V_ipfw_dyn_v == NULL) return NULL; /* failed ! */ } i = hash_packet(id); r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO); if (r == NULL) { printf ("ipfw: sorry cannot allocate state\n"); return NULL; } /* increase refcount on parent, and set pointer */ if (dyn_type == O_LIMIT) { ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule; if ( parent->dyn_type != O_LIMIT_PARENT) panic("invalid parent"); parent->count++; r->parent = parent; rule = parent->rule; } r->id = *id; r->expire = time_uptime + V_dyn_syn_lifetime; r->rule = rule; r->dyn_type = dyn_type; r->pcnt = r->bcnt = 0; r->count = 0; r->bucket = i; r->next = V_ipfw_dyn_v[i]; V_ipfw_dyn_v[i] = r; V_dyn_count++; DEB({ struct in_addr da; #ifdef INET6 char src[INET6_ADDRSTRLEN]; char dst[INET6_ADDRSTRLEN]; #else char src[INET_ADDRSTRLEN]; char dst[INET_ADDRSTRLEN]; #endif #ifdef INET6 if (IS_IP6_FLOW_ID(&(r->id))) { ip6_sprintf(src, &r->id.src_ip6); ip6_sprintf(dst, &r->id.dst_ip6); } else #endif { da.s_addr = htonl(r->id.src_ip); inet_ntop(AF_INET, &da, src, sizeof(src)); da.s_addr = htonl(r->id.dst_ip); inet_ntop(AF_INET, &da, dst, sizeof(dst)); } printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n", dyn_type, src, r->id.src_port, dst, r->id.dst_port, V_dyn_count); }) return r;
void f_aap_log_as_commonlog_to_file(INT32 args) { struct log_entry *le; struct log *l = LTHIS->log; int n = 0; int mfd, ot=0; struct object *f; struct tm tm; FILE *foo; static const char *month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Sep", "Nov", "Dec", }; get_all_args("log_as_commonlog_to_file", args, "%o", &f); f->refs++; pop_n_elems(args); apply(f, "query_fd", 0); mfd = fd_dup(sp[-1].u.integer); if(mfd < 1)Pike_error("Bad fileobject to ->log_as_commonlog_to_file\n"); pop_stack(); foo = fdopen( mfd, "w" ); if(!foo) Pike_error("Bad fileobject to ->log_as_commonlog_to_file\n"); THREADS_ALLOW(); mt_lock( &l->log_lock ); le = l->log_head; l->log_head = l->log_tail = 0; mt_unlock( &l->log_lock ); while(le) { int i; struct tm *tm_p; struct log_entry *l = le->next; /* remotehost rfc931 authuser [date] "request" status bytes */ if(le->t != ot) { time_t t = (time_t)le->t; #ifdef HAVE_GMTIME_R gmtime_r( &t, &tm ); #else #ifdef HAVE_GMTIME tm_p = gmtime( &t ); /* This will break if two threads run gmtime() at once. */ #else #ifdef HAVE_LOCALTIME tm_p = localtime( &t ); /* This will break if two threads run localtime() at once. */ #endif #endif if (tm_p) tm = *tm_p; #endif ot = le->t; } /* date format: [03/Feb/1998:23:08:20 +0000] */ /* GET [URL] HTTP/1.0 */ for(i=13; i<le->raw.len; i++) if(le->raw.str[i] == '\r') { le->raw.str[i] = 0; break; } #ifdef HAVE_INET_NTOP if(SOCKADDR_FAMILY(le->from) != AF_INET) { char buffer[64]; fprintf(foo, "%s - %s [%02d/%s/%d:%02d:%02d:%02d +0000] \"%s\" %d %ld\n", inet_ntop(SOCKADDR_FAMILY(le->from), SOCKADDR_IN_ADDR(le->from), buffer, sizeof(buffer)), /* hostname */ "-", /* remote-user */ tm.tm_mday, month[tm.tm_mon], tm.tm_year+1900, tm.tm_hour, tm.tm_min, tm.tm_sec, /* date */ le->raw.str, /* request line */ le->reply, /* reply code */ DO_NOT_WARN((long)le->sent_bytes)); /* bytes transfered */ } else #endif /* HAVE_INET_NTOP */ fprintf(foo, "%d.%d.%d.%d - %s [%02d/%s/%d:%02d:%02d:%02d +0000] \"%s\" %d %ld\n", ((unsigned char *)&le->from.ipv4.sin_addr)[ 0 ], ((unsigned char *)&le->from.ipv4.sin_addr)[ 1 ], ((unsigned char *)&le->from.ipv4.sin_addr)[ 2 ], ((unsigned char *)&le->from.ipv4.sin_addr)[ 3 ], /* hostname */ "-", /* remote-user */ tm.tm_mday, month[tm.tm_mon], tm.tm_year+1900, tm.tm_hour, tm.tm_min, tm.tm_sec, /* date */ le->raw.str, /* request line */ le->reply, /* reply code */ DO_NOT_WARN((long)le->sent_bytes)); /* bytes transfered */ free_log_entry( le ); n++; le = l; } fclose(foo); fd_close(mfd); THREADS_DISALLOW(); push_int(n); }
int main(int argc, char *argv[]) { int sock, intfsock; int opt; struct sockaddr_in addr, foreignaddr; socklen_t foreignaddrlen; int len; char addrtext[32], addrtext2[32], *paddrtext; struct ip_mreqn mreq; char *miface, *mifacename; #define MAX_IFS 20 struct ifreq ifaces[MAX_IFS]; int mifaceind; u_int8_t mifacehwaddr[IFHWADDRLEN]; struct in_addr mifaceaddr; char servername[64] = MSGKEY; int server; //int serverport = 49152; //int clientport = 49153; int serverport = 23058; int clientport = 23059; bootp_packet bp, br; struct pumpNetIntf bi; int vendorlen; time_t time0; /* * See ftp://ftp.microsoft.com/bussys/winsock/ms-ext/multcast.txt * on the use of multicast addresses */ char *multiaddr = "225.0.0.1"; int multittl = 31; char *filename = NULL; char ident[8], recvalue[BUFLEN]; int result; char command[BUFLEN]; char netinfo[BUFLEN]; int bonding = 0; //miface = NULL; miface = "eth0"; mifacename = NULL; mifaceind = 0; memset(&mifaceaddr, 0, sizeof(mifaceaddr)); mifaceaddr.s_addr = htonl(INADDR_ANY); memset(&mifacehwaddr, 0, sizeof(mifacehwaddr)); server = 0; debug = 0; while ((opt=getopt(argc,argv,"si:g:t:o:S:C:I:d:v")) != EOF) { switch(opt) { case 's': server = 1; break; case 'i': miface = optarg; break; case 'g': multiaddr = strdup(optarg); break; case 't': multittl = strtol(optarg, NULL, 0); if (errno) error("TTL must be a number"); break; case 'S': serverport = strtol(optarg, NULL, 0); if (errno) error("SERVER_PORT must be a number"); break; case 'C': clientport = strtol(optarg, NULL, 0); if (errno) error("CLIENT_PORT must be a number"); break; case 'I': strcat(servername,strdup(optarg)); break; case 'd': debug = 1; break; case 'v': printf("Version:%s\n", VERSION); exit(0); default: usage(); } } openlog("fagent+", LOG_PID | LOG_NDELAY | (debug ? LOG_PERROR : 0), LOG_DAEMON); sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) error("socket"); if (miface != NULL) { if (!if_readlist_proc(miface)) { mifacename = miface; struct ifreq ifr; intfsock = socket(AF_INET, SOCK_DGRAM, 0); //intfsock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); strncpy(ifr.ifr_name, miface, sizeof(ifr.ifr_name)); if (ioctl(intfsock, SIOCGIFHWADDR, &ifr) < 0) { error("ioctl SIOCGIFHWADDR"); } memcpy(&mifacehwaddr, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN); //unsigned char *s = &mifacehwaddr; //printf("%x %x %x %x %x %x\n", s[0],s[1],s[2],s[3],s[4],s[5]); ifr.ifr_addr.sa_family = AF_INET; if (ioctl(intfsock, SIOCGIFADDR, &ifr) < 0) { char bondip_file[16] = {0}; strcat(bondip_file, "/tmp/bondip_"); strcat(bondip_file, miface); //printf("not ip!!it is bond slave get ip from perl script\n"); sprintf(command, _PATH_PERL_GETNETDEVIP" %s > %s", miface, bondip_file); system(command); FILE *fp = fopen(bondip_file, "r"); if (fp) { unsigned char *i = &mifaceaddr; while ( !feof(fp) ) { fscanf(fp,"%d.%d.%d.%d", &i[0], &i[1], &i[2], &i[3]); } fclose(fp); unlink(bondip_file); } else { error("error get ip\n"); } //error("ioctl SIOCGIFADDR"); } else { mifaceaddr = ((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr; } //s = &mifaceaddr; //printf("%d %d %d %d\n", s[0],s[1],s[2],s[3]); close(intfsock); } } #if 0 again: if (miface != NULL) { struct ifconf ifconfig; int i; ifconfig.ifc_len = sizeof(ifaces); ifconfig.ifc_req = (struct ifreq *)&ifaces; if (ioctl(sock, SIOCGIFCONF, &ifconfig) < 0) error("ioctl SIOCGIFCONF"); for (i = 0; i < ifconfig.ifc_len / sizeof(struct ifreq); i++) { printf("ifname %s\n", ifaces[i].ifr_name); ifaces[i].ifr_addr.sa_family = AF_INET; if (ioctl(sock, SIOCGIFADDR, &ifaces[i]) < 0) error("ioctl SIOCGIFADDR"); } if (strchr(miface, '.') != NULL) { if (!inet_aton(miface, &addr.sin_addr)) error("inet_aton: multicast interface address"); for (i = 0; i < ifconfig.ifc_len / sizeof(struct ifreq); i++) if (((struct sockaddr_in *) &(ifaces[i].ifr_addr))->sin_addr.s_addr == addr.sin_addr.s_addr) mifaceind = i + 1; } else { for (i = 0; i < ifconfig.ifc_len / sizeof(struct ifreq); i++) if (!strcmp(ifaces[i].ifr_name, miface)) mifaceind = i + 1; } if (mifaceind) { struct ifreq ifr; mifaceaddr = ((struct sockaddr_in *) &(ifaces[mifaceind - 1].ifr_addr))->sin_addr; mifacename = ifaces[mifaceind - 1].ifr_name; strncpy(ifr.ifr_name, mifacename, sizeof(ifr.ifr_name)); ifr.ifr_addr.sa_family = AF_INET; if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) error("ioctl SIOCGIFHWADDR"); memcpy(&mifacehwaddr, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN); unsigned char *s = &mifacehwaddr; //printf("%x %x %x %x %x %x\n", s[0],s[1],s[2],s[3],s[4],s[5]); } else { miface = "bond0"; bonding = 1; goto again; } } if (bonding) mifaceind = 0; #endif if (mifacename == NULL) mifacename = "default"; memset(&bp, 0, sizeof(bp)); bp.opcode = (server ? 2 : 1); // client will request first bp.hw = 1; // ethernet bp.hwlength = IFHWADDRLEN; // length of the hardware address bp.hopcount = 255; // can be used by a proxy server, // shouldn't affect multicast bp.xid = htonl(0x12345678); bp.secs = htons(0); bp.flags = htons(0); if (server) { memset(&bp.ciaddr, 0, 4); memcpy(&bp.yiaddr, &your_ip, 4); memcpy(&bp.server_ip, &mifaceaddr, 4); } else { memcpy(&bp.ciaddr, &mifaceaddr, 4); memset(&bp.yiaddr, 0, 4); memset(&bp.server_ip, 0, 4); } memset(&bp.bootp_gw_ip, 0, 4); memcpy(&bp.hwaddr, &mifacehwaddr, sizeof(mifacehwaddr)); strncpy((char *)&bp.servername, servername, sizeof(bp.servername)); #if 0 memcpy(&bp.vendor, &magic_cookie, 4); vendorlen = 4; if (server) { memcpy(((void *)&bp.vendor) + 4, &test_server_data, sizeof(test_server_data)); vendorlen += sizeof(test_server_data); }; #else vendorlen = 0; #endif bp.vendor[vendorlen++] = 0xFF; // Print // fprintf(stdout, "Server Name = %s\n", servername); // fprintf(stdout, "bp.hwaddr = %d %d %d %d %d %d\n", // bp.hwaddr[0], bp.hwaddr[1], bp.hwaddr[2], bp.hwaddr[3], bp.hwaddr[4], bp.hwaddr[5]); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; /* 67 -- server, 68 -- client */ if (server) addr.sin_port = htons(serverport); else addr.sin_port = htons(clientport); // addr.sin_addr = mifaceaddr; addr.sin_addr.s_addr = htonl(INADDR_ANY); if ((paddrtext = (char *)inet_ntop(AF_INET, &addr.sin_addr, addrtext, sizeof(addrtext))) == NULL) error("inet_ntop"); //syslog(LOG_INFO, "Local address %s, port %d\n", // paddrtext, ntohs(addr.sin_port)); opt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) error("setsockopt SO_REUSEADDR"); #if 0 // see "man 4 ip", "man 7 socket" on SO_BROADCAST -- the option is discouraged if (server) { opt = 1; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) < 0) error("setsockopt SO_BROADCAST"); } #endif if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) error("bind"); if (!inet_aton(multiaddr, &mreq.imr_multiaddr)) error("inet_aton"); #if 1 mreq.imr_address = mifaceaddr; mreq.imr_ifindex = mifaceind; #elif 0 mreq.imr_address = mifaceaddr; mreq.imr_ifindex = 0; #else mreq.imr_address.s_addr = htonl(INADDR_ANY); mreq.imr_ifindex = 0; mifacename = "default"; #endif if (setsockopt(sock, SOL_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) error("setsockopt IP_ADD_MEMBERSHIP"); if (setsockopt(sock, SOL_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq)) < 0) error("setsockopt IP_MULTICAST_IF"); opt = multittl; if (setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &opt, sizeof(opt)) < 0) error("setsockopt IP_MULTI_TTL"); opt = 0; if (setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &opt, sizeof(opt)) < 0) error("setsockopt IP_MULTI_LOOP"); if (inet_ntop(AF_INET, &mreq.imr_multiaddr, addrtext, sizeof(addrtext)) == NULL) error("inet_ntop mreq.imr_multiaddr"); if (inet_ntop(AF_INET, &mreq.imr_address, addrtext2, sizeof(addrtext2)) == NULL) error("inet_ntop mreq.imr_address"); //syslog(LOG_INFO, "Joined multicast group %s on %s (interface %s)\n", // addrtext, addrtext2, mifacename); time0 = time(NULL); // Get Net Info, do here will speed up the response packet for the "NAV+" //unlink(_PATH_TMP_NETINFO); // sprintf(command, "killall net_util_getnet.pl >/dev/null 2>/dev/null"); system(command); //kill the last net_util_getnet.pl to prevent some error. // sprintf(command, _PATH_PERL_GETNETINFO" >/dev/null 2>/dev/null"); system(command); //call the perl before run fagent+ // getnetinfo(netinfo, miface); while (1) { //crond_chk();//Minging.Tsai. 2014/5/1. Add a walk around to make sure the crond always on. struct timeval tv; fd_set fdset; int retcode; //sprintf(command, "killall net_util_getnet.pl >/dev/null 2>/dev/null"); system(command); //kill the last net_util_getnet.pl to prevent some error. //sprintf(command, _PATH_PERL_GETNETINFO" >/dev/null 2>/dev/null"); system(command); //call the perl before run fagent+ getnetinfo(netinfo, miface); FD_ZERO(&fdset); FD_SET(sock, &fdset); tv.tv_sec = 5; tv.tv_usec = 0; // linux specifics: tv gets updated automatically while (((retcode = select(sock + 1, &fdset, NULL, NULL, &tv)) < 0) && (errno == EINTR)); if (retcode < 0) error("select"); else if (!retcode) { //if (debug) //syslog(LOG_INFO, "timeout waiting for input"); } else { if ((len = recvfrom(sock, &br, sizeof(br), 0, (struct sockaddr *) &foreignaddr, &foreignaddrlen)) < 0) error("recvfrom"); inet_ntop(AF_INET, &foreignaddr.sin_addr, addrtext, sizeof(addrtext)); /*syslog(LOG_INFO, "From %s:%d \"%s\"\n", addrtext, ntohs(foreignaddr.sin_port), len >= sizeof(br) - sizeof(br.bootfile) - sizeof(br.vendor) ? (char *)&br.servername : "(BOOTP packet too small)");*/ process_bootp_packet(&br, len, &bi); // Print // fprintf(stdout, "IP = %d.%d.%d.%d\n", // br.yiaddr[0], br.yiaddr[1], br.yiaddr[2], br.yiaddr[3]); // fprintf(stdout, "HWADDR = %d %d %d %d %d %d\n", // br.hwaddr[0], br.hwaddr[1], br.hwaddr[2], br.hwaddr[3], br.hwaddr[4], br.hwaddr[5]); if (br.hwaddr[0] == 0 && br.hwaddr[1] == 0 && br.hwaddr[2] == 0 && br.hwaddr[3] == 0 && br.hwaddr[4] == 0 && br.hwaddr[5] == 0 ) { if ( br.yiaddr[0] == 0 && br.yiaddr[1] == 0 && br.yiaddr[2] == 0 && br.yiaddr[3] == 0 ) { //syslog (LOG_DEBUG, "%s", br.bootfile); strncpy( ident, br.bootfile, 4); ident[4] = '\0'; if ( ! strcmp(ident,"NAV+") ) { // printf("Got NAV+ from %s\n", miface); sprintf(command, "echo \"receive nasfinder NAV+ `date -u`\">/tmp/fagent+"); system(command); //kill the last net_util_getnet.pl to prevent some error. // sprintf(command, _PATH_PERL_GETNETINFO" >/dev/null 2>/dev/null"); system(command); //call the perl before run fagent+ //Minging.Tsai. 2013/10/25. //char recv_helios_sn[19]; //strncpy( recv_helios_sn, br.bootfile + 4, 19); //recv_helios_sn[18] = '\0'; //printf("recv_helios_sn=\"%s\"\n", recv_helios_sn); //char recv_helios_ip[INET_ADDRSTRLEN]; //inet_ntop(AF_INET, &(foreignaddr.sin_addr), recv_helios_ip, INET_ADDRSTRLEN); //printf("recv_helios_ip=\"%s\"\n", recv_helios_ip); //char cmd[128]; //memset(cmd, 0, 128); //sprintf(cmd, "/nasapp/perl/util/net_util_chkjoininfo.pl \"%s\" \"%s\" &", recv_helios_ip, recv_helios_sn); //system(cmd); memset(&bp.bootfile, 0, sizeof(bp.bootfile)); //unlink(_PATH_TMP_NETINFO);//Minging.Tsai. 2013/8/13. For nasfinder can get lastest information. //sprintf(command, _PATH_PERL_GETNETINFO" >/dev/null 2>/dev/null"); system(command); //sleep(3); getnetinfo(netinfo, miface); strncpy((char *)&bp.bootfile, netinfo, sizeof(bp.bootfile)); memset(&foreignaddr, 0, sizeof(foreignaddr)); foreignaddr.sin_family = AF_INET; foreignaddrlen = sizeof(foreignaddr); if (!server) { foreignaddr.sin_addr = mreq.imr_multiaddr; foreignaddr.sin_port = htons(serverport); //printf("bp.bootfile=%s\n", (char *)&bp.bootfile); bp.secs = htons((u_int16_t)(time(NULL) - time0)); int error_count = 0; while ((len = sendto(sock, &bp, sizeof(bp), 0, (struct sockaddr *) &foreignaddr, foreignaddrlen)) < 0) { //printf("sendto error?\n"); sleep(2); if(error_count > 10) { break; } error_count++; perror("client sendto request"); //error("client sendto request"); //error() will call exit() to terminate the program } //printf("len =%d\n",len); sprintf(command, "echo \"reply nasfinder len=%d, error_count=%d\">>/tmp/fagent+", len, error_count); system(command); //kill the last net_util_getnet.pl to prevent some error. } //fprintf(stdout, "Say Hello\n"); } } } else if(br.hwaddr[0] == bp.hwaddr[0] && br.hwaddr[1] == bp.hwaddr[1] && br.hwaddr[2] == bp.hwaddr[2] && br.hwaddr[3] == bp.hwaddr[3] && br.hwaddr[4] == bp.hwaddr[4] && br.hwaddr[5] == bp.hwaddr[5] ) { //printf("Get something!!\n"); //syslog (LOG_DEBUG, "%s", br.bootfile); strncpy( ident, br.bootfile, 4); ident[4] = '\0'; strcpy(recvalue,br.bootfile+5); if ( ! strcmp(ident,"AUTH") ) { //syslog (LOG_DEBUG, "AUTH: %s %s", ident, recvalue); result = login(recvalue); //syslog (LOG_DEBUG, "AUTH: RESULT %d", result); if ( result == 0 ) { strncpy((char *)&bp.bootfile, "AUTH&OK&", sizeof(bp.bootfile)); } else { strncpy((char *)&bp.bootfile, "AUTH&FAIL&", sizeof(bp.bootfile)); } memset(&foreignaddr, 0, sizeof(foreignaddr)); foreignaddr.sin_family = AF_INET; foreignaddrlen = sizeof(foreignaddr); if (!server) { foreignaddr.sin_addr = mreq.imr_multiaddr; foreignaddr.sin_port = htons(serverport); bp.secs = htons((u_int16_t)(time(NULL) - time0)); if ((len = sendto(sock, &bp, sizeof(bp) - sizeof(bp.vendor) + vendorlen, 0 , (struct sockaddr *) &foreignaddr, foreignaddrlen)) < 0) error("client sendto request"); } } else if ( ! strcmp(ident,"SNET") ) { //printf("SNET!!\n"); /* it will receive the same packet three times */ //printf("Got SNET from %s\n", miface); if (strncmp(br.servername, servername, sizeof(br.servername))) { sprintf(command, _PATH_PERL_SETHOSTNAME" \"/tmp/null\" \"%s\" >/dev/null 2>/dev/null", br.servername+8/*promise&*/); system(command); } //sprintf( command, "/bin/echo \"%s\" > /tmp/fagent+", recvalue ); sprintf(command, _PATH_SH_SETNET" \"%s\" >/dev/null 2>/dev/null", recvalue); system(command); } else { sprintf( command, "/bin/echo \"%s\" > /tmp/fagent+", br.bootfile ); system(command); } } //if (!strncmp(br.servername, servername, sizeof(br.servername))) // break; } } if (setsockopt(sock, SOL_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) error("setsockopt IP_DROP_MEMBERSHIP"); close(sock); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; printf("client: received '%s'\n",buf); close(sockfd); return 0; }
int main(int argc, char *argv[]) { state_t s; struct sockaddr_in6 addr; int optval; int i; s.port = DEFAULT_PORT; s.max_clients = DEFAULT_MAX_CLIENTS; opterr = 0; while((i = getopt(argc, argv, "p:m:")) != -1) { switch(i) { case 'p': s.port = atoi(optarg); break; case 'm': s.max_clients = atoi(optarg); break; case '?': exit_usage(); } } if(optind < argc) exit_usage(); if(s.max_clients <= 0) { fprintf(stderr, "Maximum clients is invalid\n"); exit_usage(); } /* Ignore annoying signal */ signal(SIGPIPE, SIG_IGN); s.fin = stdin; /* Allocate memory for the frame in buffer */ s.in = malloc(IN_SIZE); if(!s.in) { perror("malloc"); return(-1); } s.in_len = 0; /* Same for output frame buffer */ s.out = malloc(OUT_SIZE); if(!s.out) { perror("malloc"); return(-1); } s.out_len = 0; s.out_key_frame_offset = 0; /* Create the listener sockets */ s.in_sock = socket(AF_INET6, SOCK_STREAM, 0); if(s.in_sock < 0) { perror("socket"); return(-1); } optval = 1; if(setsockopt(s.in_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { perror("setsockopt"); return(-1); } memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = htons(s.port); if(bind(s.in_sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { perror("bind"); return(-1); } if(listen(s.in_sock, 10) < 0) { perror("listen"); return(-1); } /* Allocate an empty client list */ s.in_client = calloc(s.max_clients, sizeof(int)); if(!s.in_client) { perror("calloc"); return(-1); } /* Read the next frame */ while(1) { fd_set rd; int maxfd, r; /* Check for incoming socket or H.264 data */ FD_ZERO(&rd); FD_SET(fileno(s.fin), &rd); FD_SET(s.in_sock, &rd); maxfd = (fileno(s.fin) > s.in_sock ? fileno(s.fin) : s.in_sock) + 1; select(maxfd, &rd, NULL, NULL, NULL); if(FD_ISSET(s.in_sock, &rd)) { struct sockaddr_in6 raddr; socklen_t raddrlen; char host[INET6_ADDRSTRLEN]; /* Find a clear client slot */ for(i = 0; i < s.max_clients; i++) if(s.in_client[i] == 0) break; /* No space? */ if(i == s.max_clients) { /* Accept and close the socket */ int sock = accept(s.in_sock, NULL, NULL); if(sock >= 0) close(sock); continue; } /* Get the socket */ if((s.in_client[i] = accept(s.in_sock, NULL, NULL)) < 0) { perror("accept"); s.in_client[i] = 0; continue; } raddrlen = sizeof(raddr); getpeername(s.in_client[i], (struct sockaddr *) &raddr, &raddrlen); if(inet_ntop(AF_INET6, &raddr.sin6_addr, host, sizeof(host))) fprintf(stderr, "Connection from %s\n", host); /* Write the buffered frames */ r = send_block(s.in_client[i], s.out, s.out_len); if(r < 0) { /* Failed to send all data */ close(s.in_client[i]); s.in_client[i] = 0; } } if(FD_ISSET(fileno(s.fin), &rd)) { if(read_to_marker(&s) == EOF) break; if(s.in_len == 0) continue; switch(s.in[0]) { case 0x27: /* Header frames? */ case 0x28: s.out_len = s.out_key_frame_offset; write_frame(&s); s.out_key_frame_offset = s.out_len; break; case 0x25: /* Key frame */ s.out_len = s.out_key_frame_offset; write_frame(&s); break; case 0x21: /* I frame */ write_frame(&s); break; default: fprintf(stderr, "Unknown frame type 0x%02X\n", s.in[0]); break; } for(i = 0; i < s.max_clients; i++) { if(s.in_client[i] == 0) continue; /* Write the frame */ r = send_frame(&s, s.in_client[i]); if(r < 0) { /* Failed to send all data */ close(s.in_client[i]); s.in_client[i] = 0; } } } } close(s.in_sock); for(i = 0; i < s.max_clients; i++) if(s.in_client[i] != 0) close(s.in_client[i]); free(s.in_client); fclose(s.fin); free(s.in); fprintf(stderr, "EOF\n"); return(0); }
static int do_attr_rewrite(void *instance, REQUEST *request) { rlm_attr_rewrite_t *data = (rlm_attr_rewrite_t *) instance; int ret = RLM_MODULE_NOOP; VALUE_PAIR *attr_vp = NULL; VALUE_PAIR *tmp = NULL; regex_t preg; regmatch_t pmatch[9]; int cflags = 0; int err = 0; char done_xlat = 0; unsigned int len = 0; char err_msg[MAX_STRING_LEN]; unsigned int i = 0; unsigned int j = 0; unsigned int counter = 0; char new_str[MAX_STRING_LEN]; char *ptr, *ptr2; char search_STR[MAX_STRING_LEN]; char replace_STR[MAX_STRING_LEN]; if ((attr_vp = pairfind(request->config_items, PW_REWRITE_RULE, 0, TAG_ANY)) != NULL){ if (data->name == NULL || strcmp(data->name,attr_vp->vp_strvalue)) return RLM_MODULE_NOOP; } if (data->new_attr){ /* new_attribute = yes */ if (!radius_xlat(replace_STR, sizeof(replace_STR), data->replace, request, NULL, NULL)) { DEBUG2("%s: xlat on replace string failed.", data->name); return ret; } attr_vp = pairmake(data->attribute,replace_STR,0); if (attr_vp == NULL){ DEBUG2("%s: Could not add new attribute %s with value '%s'", data->name, data->attribute,replace_STR); return ret; } switch(data->searchin){ case RLM_REGEX_INPACKET: pairadd(&request->packet->vps,attr_vp); break; case RLM_REGEX_INCONFIG: pairadd(&request->config_items,attr_vp); break; case RLM_REGEX_INREPLY: pairadd(&request->reply->vps,attr_vp); break; #ifdef WITH_PROXY case RLM_REGEX_INPROXY: if (!request->proxy) { pairbasicfree(attr_vp); return RLM_MODULE_NOOP; } pairadd(&request->proxy->vps, attr_vp); break; case RLM_REGEX_INPROXYREPLY: if (!request->proxy_reply) { pairbasicfree(attr_vp); return RLM_MODULE_NOOP; } pairadd(&request->proxy_reply->vps, attr_vp); break; #endif default: radlog(L_ERR, "%s: Illegal value for searchin. Changing to packet.", data->name); data->searchin = RLM_REGEX_INPACKET; pairadd(&request->packet->vps,attr_vp); break; } DEBUG2("%s: Added attribute %s with value '%s'", data->name,data->attribute,replace_STR); ret = RLM_MODULE_OK; } else { int replace_len = 0; /* new_attribute = no */ switch (data->searchin) { case RLM_REGEX_INPACKET: if (!data->da->vendor && (data->da->attr == PW_USER_NAME)) attr_vp = request->username; else if (!data->da->vendor && (data->da->attr == PW_USER_PASSWORD)) attr_vp = request->password; else tmp = request->packet->vps; break; case RLM_REGEX_INCONFIG: tmp = request->config_items; break; case RLM_REGEX_INREPLY: tmp = request->reply->vps; break; #ifdef WITH_PROXY case RLM_REGEX_INPROXYREPLY: if (!request->proxy_reply) return RLM_MODULE_NOOP; tmp = request->proxy_reply->vps; break; case RLM_REGEX_INPROXY: if (!request->proxy) return RLM_MODULE_NOOP; tmp = request->proxy->vps; break; #endif default: radlog(L_ERR, "%s: Illegal value for searchin. Changing to packet.", data->name); data->searchin = RLM_REGEX_INPACKET; attr_vp = pairfind(request->packet->vps, data->da->attr, data->da->vendor, TAG_ANY); break; } do_again: if (tmp != NULL) attr_vp = pairfind(tmp, data->da->attr, data->da->vendor, TAG_ANY); if (attr_vp == NULL) { DEBUG2("%s: Could not find value pair for attribute %s", data->name,data->attribute); return ret; } if (attr_vp->vp_strvalue == NULL || attr_vp->length == 0){ DEBUG2("%s: Attribute %s string value NULL or of zero length", data->name,data->attribute); return ret; } cflags |= REG_EXTENDED; if (data->nocase) cflags |= REG_ICASE; if (!radius_xlat(search_STR, sizeof(search_STR), data->search, request, NULL, NULL) && data->search_len != 0) { DEBUG2("%s: xlat on search string failed.", data->name); return ret; } if ((err = regcomp(&preg,search_STR,cflags))) { regerror(err, &preg, err_msg, MAX_STRING_LEN); DEBUG2("%s: regcomp() returned error: %s", data->name,err_msg); return ret; } if ((attr_vp->type == PW_TYPE_IPADDR) && (attr_vp->vp_strvalue[0] == '\0')) { inet_ntop(AF_INET, &(attr_vp->vp_ipaddr), attr_vp->vp_strvalue, sizeof(attr_vp->vp_strvalue)); } ptr = new_str; ptr2 = attr_vp->vp_strvalue; counter = 0; for ( i = 0 ;i < (unsigned)data->num_matches; i++) { err = regexec(&preg, ptr2, REQUEST_MAX_REGEX, pmatch, 0); if (err == REG_NOMATCH) { if (i == 0) { DEBUG2("%s: Does not match: %s = %s", data->name, data->attribute, attr_vp->vp_strvalue); regfree(&preg); goto to_do_again; } else break; } if (err != 0) { regfree(&preg); radlog(L_ERR, "%s: match failure for attribute %s with value '%s'", data->name, data->attribute, attr_vp->vp_strvalue); return ret; } if (pmatch[0].rm_so == -1) break; len = pmatch[0].rm_so; if (data->append) { len = len + (pmatch[0].rm_eo - pmatch[0].rm_so); } counter += len; if (counter >= MAX_STRING_LEN) { regfree(&preg); DEBUG2("%s: Replacement out of limits for attribute %s with value '%s'", data->name, data->attribute, attr_vp->vp_strvalue); return ret; } memcpy(ptr, ptr2,len); ptr += len; *ptr = '\0'; ptr2 += pmatch[0].rm_eo; if (i == 0){ /* * We only run on the first match, sorry */ for(j = 0; j <= REQUEST_MAX_REGEX; j++){ char *p; char buffer[sizeof(attr_vp->vp_strvalue)]; /* * Stolen from src/main/valuepair.c, paircompare() */ /* * Delete old matches if the corresponding match does not * exist in the current regex */ if (pmatch[j].rm_so == -1){ p = request_data_get(request,request,REQUEST_DATA_REGEX | j); if (p){ free(p); continue; } break; } memcpy(buffer, attr_vp->vp_strvalue + pmatch[j].rm_so, pmatch[j].rm_eo - pmatch[j].rm_so); buffer[pmatch[j].rm_eo - pmatch[j].rm_so] = '\0'; p = strdup(buffer); request_data_add(request,request,REQUEST_DATA_REGEX | j,p,free); } } if (!done_xlat){ if (data->replace_len != 0 && radius_xlat(replace_STR, sizeof(replace_STR), data->replace, request, NULL, NULL) == 0) { DEBUG2("%s: xlat on replace string failed.", data->name); return ret; } replace_len = (data->replace_len != 0) ? strlen(replace_STR) : 0; done_xlat = 1; } counter += replace_len; if (counter >= MAX_STRING_LEN) { regfree(&preg); DEBUG2("%s: Replacement out of limits for attribute %s with value '%s'", data->name, data->attribute, attr_vp->vp_strvalue); return ret; } if (replace_len){ memcpy(ptr, replace_STR, replace_len); ptr += replace_len; *ptr = '\0'; } } regfree(&preg); len = strlen(ptr2) + 1; /* We add the ending NULL */ counter += len; if (counter >= MAX_STRING_LEN){ DEBUG2("%s: Replacement out of limits for attribute %s with value '%s'", data->name, data->attribute, attr_vp->vp_strvalue); return ret; } memcpy(ptr, ptr2, len); ptr[len] = '\0'; DEBUG2("%s: Changed value for attribute %s from '%s' to '%s'", data->name, data->attribute, attr_vp->vp_strvalue, new_str); if (pairparsevalue(attr_vp, new_str) == NULL) { DEBUG2("%s: Could not write value '%s' into attribute %s: %s", data->name, new_str, data->attribute, fr_strerror()); return ret; } to_do_again: ret = RLM_MODULE_OK; if (tmp != NULL){ tmp = attr_vp->next; if (tmp != NULL) goto do_again; } } return ret; }
int main(void) { struct sockaddr_in sin; struct sockaddr_in cin; int s_fd; int port = 8000; socklen_t addr_len; char buf[MAX_LINE]; char addr_p[INET_ADDRSTRLEN]; int n; bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; /* Using IPv4 */ sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(port); s_fd = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == s_fd) { perror("fail to create socket"); exit(1); } if (-1 == bind(s_fd, (struct sockaddr_t *)&sin, sizeof(sin))) { perror("fail to bind"); exit(1); } while (1) { addr_len = sizeof(cin); n = recvfrom(s_fd, buf, MAX_LINE, 0, (struct sockaddr_t *)&cin, &addr_len); if (-1 == n) { perror("fail to receive"); exit(1); } inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p)); printf("client IP is %s, prot is %d\n", addr_p, ntohs(cin.sin_port)); my_func(buf); n = sendto(s_fd, buf, n, 0, (struct sockaddr_in *)&cin, addr_len); if (-1 == n) { perror("fail to send"); exit(1); } } if (-1 == close(s_fd)) { perror("fail to close"); exit(1); } return 0; }
/* * Input an Neighbor Solicitation Message. * * Based on RFC 2461 * Based on RFC 2462 (duplicated address detection) */ void nd6_ns_input(struct mbuf *m, int off, int icmp6len) { struct ifnet *ifp = m->m_pkthdr.rcvif; struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); struct nd_neighbor_solicit *nd_ns; struct in6_addr saddr6 = ip6->ip6_src; struct in6_addr daddr6 = ip6->ip6_dst; struct in6_addr taddr6; struct in6_addr myaddr6; char *lladdr = NULL; struct ifaddr *ifa = NULL; int lladdrlen = 0; int anycast = 0, proxy = 0, tentative = 0; int router = ip6_forwarding; int tlladdr; union nd_opts ndopts; struct sockaddr_dl *proxydl = NULL; char addr[INET6_ADDRSTRLEN], addr0[INET6_ADDRSTRLEN]; IP6_EXTHDR_GET(nd_ns, struct nd_neighbor_solicit *, m, off, icmp6len); if (nd_ns == NULL) { icmp6stat.icp6s_tooshort++; return; } ip6 = mtod(m, struct ip6_hdr *); /* adjust pointer for safety */ taddr6 = nd_ns->nd_ns_target; if (ip6->ip6_hlim != 255) { nd6log((LOG_ERR, "nd6_ns_input: invalid hlim (%d) from %s to %s on %s\n", ip6->ip6_hlim, inet_ntop(AF_INET6, &ip6->ip6_src, addr, sizeof(addr)), inet_ntop(AF_INET6, &ip6->ip6_dst, addr0, sizeof(addr0)), ifp->if_xname)); goto bad; } if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) { /* dst has to be solicited node multicast address. */ /* don't check ifindex portion */ if (daddr6.s6_addr16[0] == __IPV6_ADDR_INT16_MLL && daddr6.s6_addr32[1] == 0 && daddr6.s6_addr32[2] == __IPV6_ADDR_INT32_ONE && daddr6.s6_addr8[12] == 0xff) { ; /*good*/ } else { nd6log((LOG_INFO, "nd6_ns_input: bad DAD packet " "(wrong ip6 dst)\n")); goto bad; } } else { /* * Make sure the source address is from a neighbor's address. */ if (!in6_ifpprefix(ifp, &saddr6)) { nd6log((LOG_INFO, "nd6_ns_input: " "NS packet from non-neighbor\n")); goto bad; } } if (IN6_IS_ADDR_MULTICAST(&taddr6)) { nd6log((LOG_INFO, "nd6_ns_input: bad NS target (multicast)\n")); goto bad; } if (IN6_IS_SCOPE_EMBED(&taddr6)) taddr6.s6_addr16[1] = htons(ifp->if_index); icmp6len -= sizeof(*nd_ns); nd6_option_init(nd_ns + 1, icmp6len, &ndopts); if (nd6_options(&ndopts) < 0) { nd6log((LOG_INFO, "nd6_ns_input: invalid ND option, ignored\n")); /* nd6_options have incremented stats */ goto freeit; } if (ndopts.nd_opts_src_lladdr) { lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1); lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3; } if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) && lladdr) { nd6log((LOG_INFO, "nd6_ns_input: bad DAD packet " "(link-layer address option)\n")); goto bad; } /* * Attaching target link-layer address to the NA? * (RFC 2461 7.2.4) * * NS IP dst is unicast/anycast MUST NOT add * NS IP dst is solicited-node multicast MUST add * * In implementation, we add target link-layer address by default. * We do not add one in MUST NOT cases. */ #if 0 /* too much! */ ifa = &in6ifa_ifpwithaddr(ifp, &daddr6)->ia_ifa; if (ifa && (ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST)) tlladdr = 0; else #endif if (!IN6_IS_ADDR_MULTICAST(&daddr6)) tlladdr = 0; else tlladdr = 1; /* * Target address (taddr6) must be either: * (1) Valid unicast/anycast address for my receiving interface, * (2) Unicast address for which I'm offering proxy service, or * (3) "tentative" address on which DAD is being performed. */ /* (1) and (3) check. */ ifa = &in6ifa_ifpwithaddr(ifp, &taddr6)->ia_ifa; #if NCARP > 0 if (ifp->if_type == IFT_CARP && ifa && !carp_iamatch6(ifp, lladdr, &proxydl)) ifa = NULL; #endif /* (2) check. */ if (!ifa) { struct rtentry *rt; struct sockaddr_in6 tsin6; bzero(&tsin6, sizeof tsin6); tsin6.sin6_len = sizeof(struct sockaddr_in6); tsin6.sin6_family = AF_INET6; tsin6.sin6_addr = taddr6; rt = rtalloc1(sin6tosa(&tsin6), 0, m->m_pkthdr.rdomain); if (rt && (rt->rt_flags & RTF_ANNOUNCE) != 0 && rt->rt_gateway->sa_family == AF_LINK) { /* * proxy NDP for single entry */ ifa = &in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY | IN6_IFF_ANYCAST)->ia_ifa; if (ifa) { proxy = 1; proxydl = SDL(rt->rt_gateway); router = 0; /* XXX */ } } if (rt) rtfree(rt); } if (!ifa) { /* * We've got an NS packet, and we don't have that address * assigned for us. We MUST silently ignore it. * See RFC2461 7.2.3. */ goto freeit; } myaddr6 = *IFA_IN6(ifa); anycast = ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST; tentative = ifatoia6(ifa)->ia6_flags & IN6_IFF_TENTATIVE; if (ifatoia6(ifa)->ia6_flags & IN6_IFF_DUPLICATED) goto freeit; if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) { nd6log((LOG_INFO, "nd6_ns_input: lladdrlen mismatch for %s " "(if %d, NS packet %d)\n", inet_ntop(AF_INET6, &taddr6, addr, sizeof(addr)), ifp->if_addrlen, lladdrlen - 2)); goto bad; } if (IN6_ARE_ADDR_EQUAL(&myaddr6, &saddr6)) { log(LOG_INFO, "nd6_ns_input: duplicate IP6 address %s\n", inet_ntop(AF_INET6, &saddr6, addr, sizeof(addr))); goto freeit; } /* * We have neighbor solicitation packet, with target address equals to * one of my tentative address. * * src addr how to process? * --- --- * multicast of course, invalid (rejected in ip6_input) * unicast somebody is doing address resolution -> ignore * unspec dup address detection * * The processing is defined in RFC 2462. */ if (tentative) { /* * If source address is unspecified address, it is for * duplicated address detection. * * If not, the packet is for address resolution; * silently ignore it. */ if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) nd6_dad_ns_input(ifa); goto freeit; } /* * If the source address is unspecified address, entries must not * be created or updated. * It looks that sender is performing DAD. Output NA toward * all-node multicast address, to tell the sender that I'm using * the address. * S bit ("solicited") must be zero. */ if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) { saddr6 = in6addr_linklocal_allnodes; saddr6.s6_addr16[1] = htons(ifp->if_index); nd6_na_output(ifp, &saddr6, &taddr6, ((anycast || proxy || !tlladdr) ? 0 : ND_NA_FLAG_OVERRIDE) | (router ? ND_NA_FLAG_ROUTER : 0), tlladdr, (struct sockaddr *)proxydl); goto freeit; } nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_NEIGHBOR_SOLICIT, 0); nd6_na_output(ifp, &saddr6, &taddr6, ((anycast || proxy || !tlladdr) ? 0 : ND_NA_FLAG_OVERRIDE) | (router ? ND_NA_FLAG_ROUTER : 0) | ND_NA_FLAG_SOLICITED, tlladdr, (struct sockaddr *)proxydl); freeit: m_freem(m); return; bad: nd6log((LOG_ERR, "nd6_ns_input: src=%s\n", inet_ntop(AF_INET6, &saddr6, addr, sizeof(addr)))); nd6log((LOG_ERR, "nd6_ns_input: dst=%s\n", inet_ntop(AF_INET6, &daddr6, addr, sizeof(addr)))); nd6log((LOG_ERR, "nd6_ns_input: tgt=%s\n", inet_ntop(AF_INET6, &taddr6, addr, sizeof(addr)))); icmp6stat.icp6s_badns++; m_freem(m); }
static void start_server (void) { int client_sd; int daemon_sd; int connected_sd; struct sockaddr_in client_sa; struct sockaddr_in daemon_sa; struct sockaddr_in connected_sa; socklen_t size; fd_set socket_set; int nfds; struct ifreq if_info; struct sockaddr_in *if_addr; char addr[INET_ADDRSTRLEN]; struct client *c; struct daemon *d; struct parsed_cmd *pcmd = NULL; char *ident_msg; int port; char *colon; /* Prepare all the threads */ slow_pool = NULL; fast_pool = NULL; clients_pool = NULL; daemons_pool = NULL; ABORT_IF (!(slow_pool = pool_create (prefs->nb_proc)), "Unable to create slow_pool") ABORT_IF (!(fast_pool = pool_create (prefs->nb_proc)), "Unable to create fast_pool") ABORT_IF (!(clients_pool = pool_create (prefs->max_clients)), "Unable to create clients_pool") ABORT_IF (!(daemons_pool = pool_create (prefs->max_daemons)), "Unable to create daemons_pool") nb_clients.count = 0; ABORT_IF (sem_init (&nb_clients.lock, 0, 1) < 0, "Unable to create nb_clients lock") nb_daemons.count = 0; ABORT_IF (sem_init (&nb_daemons.lock, 0, 1) < 0, "Unable to create nb_daemons lock") /* Create the shared directory if it does not exist already */ ABORT_IF (create_dir (prefs->shared_folder, (mode_t)0755) < 0, "Unable to create shared directory") /* Initialize global pointers and their semaphores */ clients = NULL; ABORT_IF (sem_init (&clients_lock, 0, 1) < 0, "Unable to sem_init clients_lock") daemons = NULL; ABORT_IF (sem_init (&daemons_lock, 0, 1) < 0, "Unable to sem_init daemons_lock") file_cache = NULL; ABORT_IF (sem_init (&file_cache_lock, 0, 1) < 0, "Unable to sem_init file_cache_lock") list_client = NULL; ABORT_IF (sem_init (&list_lock, 0, 1) < 0, "Unable to sem_init list_lock") downloads = NULL; ABORT_IF (sem_init (&downloads_lock, 0, 1) < 0, "Unable to sem_init download_queue_lock") client_sa.sin_family = AF_INET; client_sa.sin_addr.s_addr = INADDR_ANY; client_sa.sin_port = htons (prefs->client_port); client_sd = socket_init (&client_sa); ABORT_IF (client_sd < 0, "Unable to socket_init client_sd") daemon_sa.sin_family = AF_INET; daemon_sa.sin_addr.s_addr = INADDR_ANY; daemon_sa.sin_port = htons (prefs->daemon_port); daemon_sd = socket_init (&daemon_sa); ABORT_IF (daemon_sd < 0, "Unable to socket_init daemon_sd") #if 1 /* We get our ip */ memcpy (if_info.ifr_name, prefs->interface, strlen (prefs->interface) + 1); if (ioctl (daemon_sd, SIOCGIFADDR, &if_info) == -1) { log_failure (log_file, "Can't get my ip from interface"); log_failure (log_file, "LOL ERRNO : %s\n", strerror (errno)); goto abort; } if_addr = (struct sockaddr_in *)&if_info.ifr_addr; inet_ntop (AF_INET, &if_addr->sin_addr, my_ip, INET_ADDRSTRLEN); log_success (log_file, "Found my IP : %s", my_ip); #endif /* socket_set contains both client_sd and daemon_sd */ FD_ZERO (&socket_set); size = sizeof (connected_sa); nfds = NFDS (client_sd, daemon_sd); for (;;) { /* * It is VERY important to FD_SET at each loop, because select * will FD_UNSET the socket descriptors */ FD_SET (client_sd, &socket_set); FD_SET (daemon_sd, &socket_set); /* Block until a socket is ready to accept */ if (select (nfds, &socket_set, NULL, NULL, NULL) < 0) { log_failure (log_file, "main () : select failed"); } if (FD_ISSET (client_sd, &socket_set)) { if ((connected_sd = (accept (client_sd, (struct sockaddr *) &connected_sa, &size))) < 0) { log_failure (log_file, "Failed to accept incoming connection."); break; } /* Can we handle this client? */ sem_wait (&nb_clients.lock); if (nb_clients.count < prefs->max_clients) { nb_clients.count++; sem_post (&nb_clients.lock); } else { sem_post (&nb_clients.lock); socket_sendline (connected_sd, " < Too many clients\n"); goto close_socket; } /* Then, let's handle him */ if (!inet_ntop (AF_INET, &connected_sa.sin_addr, addr, INET_ADDRSTRLEN)) { socket_sendline (connected_sd, " < Oops\n"); goto failed_handling_client; } if (!(c = client_new (connected_sd, addr))) { socket_sendline (connected_sd, " < Sorry pal :(\n"); } pool_queue (clients_pool, handle_client, c); } else if (FD_ISSET (daemon_sd, &socket_set)) { if ((connected_sd = (accept (daemon_sd, (struct sockaddr *) &connected_sa, &size))) < 0) { log_failure (log_file, "Failed to accept incoming connection."); break; } /* Can we handle this daemon? */ sem_wait (&nb_daemons.lock); if (nb_daemons.count < prefs->max_daemons) { /* Remember client_request_connect is also creating daemons, so we increment the counter even if we have to decrement it on a possible following failure */ nb_daemons.count++; sem_post (&nb_daemons.lock); } else { sem_post (&nb_daemons.lock); socket_sendline (connected_sd, " < Too many daemons\n"); goto close_socket; } /* Let's identify him first */ ident_msg = socket_try_getline (connected_sd, IDENTIFICATION_TIMEOUT); if (!ident_msg) { socket_sendline (connected_sd, "error: identification timed out\n"); goto failed_handling_daemon; } if (cmd_parse_failed ((pcmd = cmd_parse (ident_msg, NULL)))) { pcmd = NULL; goto failed_handling_daemon; } if (pcmd->argc < 2) goto failed_handling_daemon; if (strcmp (pcmd->argv[0], "neighbour") != 0) goto failed_handling_daemon; if (!(colon = strchr (pcmd->argv[1], ':'))) goto failed_handling_daemon; port = atoi (colon + 1); free (ident_msg); cmd_parse_free (pcmd); pcmd = NULL; if (!inet_ntop (AF_INET, &connected_sa.sin_addr, addr, INET_ADDRSTRLEN)) { socket_sendline (connected_sd, " < Oops\n"); goto failed_handling_daemon; } /* Now we've got his port, let him go in */ if (!(d = daemon_new (connected_sd, addr, port))) { socket_sendline (connected_sd, " < Sorry pal :(\n"); goto failed_handling_daemon; } pool_queue (daemons_pool, handle_daemon, d); } else { /* This should never happen : neither client nor daemon!? */ log_failure (log_file, "Unknown connection"); } continue; failed_handling_client: sem_wait (&nb_clients.lock); --nb_clients.count; sem_post (&nb_clients.lock); goto close_socket; /* We jump here if we reserved a slot for a daemon, but failed to create it */ failed_handling_daemon: sem_wait (&nb_daemons.lock); --nb_daemons.count; sem_post (&nb_daemons.lock); /* goto close_socket; */ close_socket: if (pcmd) { cmd_parse_free (pcmd); pcmd = NULL; } close (connected_sd); } abort: if (slow_pool) pool_destroy (slow_pool); if (fast_pool) pool_destroy (fast_pool); if (clients_pool) pool_destroy (clients_pool); if (daemons_pool) pool_destroy (daemons_pool); conf_free (prefs); exit (EXIT_FAILURE); }
/* * Function: print_attack_info() * * Print attack details (when the verbose ("-v") option is specified). */ void print_attack_info(struct iface_data *idata){ if(floods_f) printf("Flooding the target from %u different IPv6 Source Addresses\n", nsources); if(!floods_f){ if(ether_ntop(&(idata->hsrcaddr), plinkaddr, sizeof(plinkaddr)) == 0){ puts("ether_ntop(): Error converting address"); exit(EXIT_FAILURE); } printf("Ethernet Source Address: %s%s\n", plinkaddr, ((!idata->hsrcaddr_f)?" (randomized)":"")); } else{ if(idata->hsrcaddr_f){ if(ether_ntop(&(idata->hsrcaddr), plinkaddr, sizeof(plinkaddr)) == 0){ puts("ether_ntop(): Error converting address"); exit(EXIT_FAILURE); } printf("Ethernet Source Address: %s\n", plinkaddr); } else puts("Ethernet Source Address: randomized for each packet"); } if(ether_ntop(&(idata->hdstaddr), phdstaddr, sizeof(phdstaddr)) == 0){ puts("ether_ntop(): Error converting address"); exit(EXIT_FAILURE); } printf("Ethernet Destination Address: %s%s\n", phdstaddr, \ ((!idata->hdstaddr_f)?" (all-routers multicast)":"")); if(inet_ntop(AF_INET6, &(idata->srcaddr), psrcaddr, sizeof(psrcaddr)) == NULL){ puts("inet_ntop(): Error converting IPv6 Source Address to presentation format"); exit(EXIT_FAILURE); } if(!floods_f){ printf("IPv6 Source Address: %s%s\n", psrcaddr, ((!idata->srcaddr_f)?" (randomized)":"")); } else{ printf("IPv6 Source Address: randomized, from the %s/%u prefix%s\n", psrcaddr, idata->srcpreflen, \ (!idata->srcprefix_f)?" (default)":""); } if(inet_ntop(AF_INET6, &(idata->dstaddr), pdstaddr, sizeof(pdstaddr)) == NULL){ perror("inet_ntop()"); exit(EXIT_FAILURE); } printf("IPv6 Destination Address: %s%s\n", pdstaddr, \ ((!idata->dstaddr_f)?" (all-routers link-local multicast)":"")); printf("IPv6 Hop Limit: %u%s\n", hoplimit, (hoplimit_f)?"":" (default)"); for(i=0; i<ndstoptuhdr; i++) printf("Destination Options Header (Unfragmentable part): %u bytes\n", dstoptuhdrlen[i]); for(i=0; i<nhbhopthdr; i++) printf("Hop by Hop Options Header: %u bytes\n", hbhopthdrlen[i]); for(i=0; i<ndstopthdr; i++) printf("Destination Options Header: %u bytes\n", dstopthdrlen[i]); if(idata->fragh_f) printf("Sending each packet in fragments of %u bytes (plus the Unfragmentable part)\n", nfrags); for(i=0;i<nlinkaddr;i++){ if(ether_ntop(&linkaddr[i], plinkaddr, sizeof(plinkaddr)) == 0){ puts("ether_ntop(): Error converting address"); exit(EXIT_FAILURE); } printf("Source Link-layer Address option -> Address: %s\n", \ ((floods_f && !sllopta_f)?"(randomized for each packet)":plinkaddr)); } }
/*! \brief Returns a MEM STACK with the requested DNS records */ PKI_MEM_STACK *URL_get_data_dns_url(URL *url, ssize_t size) { PKI_MEM_STACK *ret = NULL; #ifdef HAVE_LIBRESOLV int type = T_A; PKI_MEM *obj = NULL; if( (!url) || (!url->addr)) { return NULL; } unsigned char response[NS_PACKETSZ]; ns_msg dnsMessage; ns_rr dnsRecord; int dnsRecordSection = ns_s_an; int dns_msgCount = 0; int len = 0; // Check the Type of record if ((type = URL_get_dns_type(url->attrs)) == -1) return NULL; PKI_log_debug("DNS URI: Searching for %s (%s/%d)", url->addr, url->attrs, type); if ((len = res_search(url->addr, C_IN, type, response, sizeof(response))) < 0) { // An Error Occurred PKI_log_err("DNS URI: search failed\n"); return NULL; } if (ns_initparse(response, len, &dnsMessage) < 0) { // This should not happen if the record is correct PKI_log_err("DNS URI: can not init DNS parsing of the dnsMessage\n"); return NULL; } len = ns_msg_count(dnsMessage, dnsRecordSection); PKI_log_debug("DNS_URI: msg count ==> %d\n", len); if (len <= 0) return NULL; if((ret = PKI_STACK_MEM_new()) == NULL ) { PKI_log_debug ("DNS URI: Memory Failure"); return NULL; } for (dns_msgCount = 0; dns_msgCount < len; dns_msgCount++) { PKI_log_debug("DNS URI: Retrieving DNS record #%d",dns_msgCount); if (ns_parserr(&dnsMessage, dnsRecordSection, dns_msgCount, &dnsRecord)) { // ERROR: ns_parserr failed, let's continue to the next record PKI_log_err("DNS URI: Can not parse record %d of %d", dns_msgCount, len); continue; } PKI_log_debug("DNS URI: type = %d (req: %d)\n", ns_rr_type(dnsRecord), type); if (type == pki_ns_t_address) { switch (ns_rr_type(dnsRecord)) { case T_A: case T_AAAA: case T_CNAME: break; default: continue; } } else if (type != ns_rr_type(dnsRecord)) { PKI_log_debug("DNS URI: recived type %d is different from requested (%d)", type, ns_rr_type(dnsRecord)); // continue; } // int i = 0; int rv = 0; // int len = 0; int offset = 0; char dnsRecordName[MAXDNAME]; memset(dnsRecordName, '\x0', MAXDNAME); // Parse the different types of DNS records if ((ns_rr_type(dnsRecord) == T_A) || (ns_rr_type(dnsRecord) == T_AAAA)) { // These require Translation using IPv4/IPv6 functions int family = AF_INET; if (ns_rr_type(dnsRecord) == T_A) family = AF_INET; else family = AF_INET6; if(inet_ntop(family, ns_rr_rdata(dnsRecord), dnsRecordName, sizeof(dnsRecordName)) == NULL) { // Can not convert continue; } } else if ((ns_rr_type(dnsRecord) == T_CNAME) || (ns_rr_type(dnsRecord) == T_MX) || (ns_rr_type(dnsRecord) == T_NS)) { if (ns_rr_type(dnsRecord) == T_MX) offset = NS_INT16SZ; rv = ns_name_uncompress(ns_msg_base(dnsMessage), ns_msg_end(dnsMessage), ns_rr_rdata(dnsRecord) + offset, dnsRecordName, MAXDNAME); // ERROR, can not uncompress the names if (rv < 0) continue; } else if (ns_rr_type(dnsRecord) == T_SRV) { // This requires special handling, the format is [SHORT][SHORT][SHORT][DATA] // unsigned short *pri = (unsigned short *) ns_rr_rdata(dnsRecord); // unsigned short *weight = (unsigned short *) &(ns_rr_rdata(dnsRecord)[2]); // unsigned short *port = (unsigned short *) &(ns_rr_rdata(dnsRecord)[4]); // Shall we return the additional data too ? // printf("PRI : %d\n", *pri); // printf("WEIGHT : %d\n", ntohs(*weight)); // printf("PORT : %d\n", ntohs(*port)); offset = 6; rv = ns_name_uncompress(ns_msg_base(dnsMessage), ns_msg_end(dnsMessage), ns_rr_rdata(dnsRecord) + offset, dnsRecordName, MAXDNAME); if (rv < 0) continue; } else if (ns_rr_type(dnsRecord) == T_TXT) { // Special handling required. Format is [BYTE][DATA] unsigned char *p = (unsigned char *)ns_rr_rdata(dnsRecord); snprintf(dnsRecordName, (size_t) *p+1, "%s", &ns_rr_rdata(dnsRecord)[1]); } else { PKI_log_debug("DNS URI: record type not supported [%d]", ns_rr_type(dnsRecord)); continue; } if((obj = PKI_MEM_new_null()) == NULL ) { // Memory Allocation Error, we abort break; } if (strlen(dnsRecordName) > 0) { // If it is a printable value, we add the parsed version of the // record if(PKI_MEM_add(obj, (char *) dnsRecordName, strlen(dnsRecordName)) == PKI_ERR) { /* ERROR in memory growth */; PKI_log_err("DNS URI: Memory Allocation Error"); break; } } else { // The value is not parsed/parsable, we return the raw data // the application should know what to do with the data! if(PKI_MEM_add(obj, (char *) ns_rr_rdata(dnsRecord), ns_rr_rdlen(dnsRecord)) == PKI_ERR) { /* ERROR in memory growth */; PKI_log_err("DNS URI: Memory Allocation Error"); break; } } /* printf("MSG Data [%d]:\n", ns_rr_rdlen(dnsRecord)); for (i=0; i < ns_rr_rdlen(dnsRecord); i++) { unsigned char *kk; kk = (unsigned char *) &ns_rr_rdata(dnsRecord)[i]; printf("%x:", *kk); }; printf("\n"); fprintf(stderr, "DEBUG: RV => %d (err: %d, %s)\n", rv, h_errno, hstrerror(h_errno)); fprintf(stderr, "DEBUG: name => %s (%s)\n", ns_rr_name(dnsRecord), url->addr); fprintf(stderr, "DEBUG: value => %s\n", dnsRecordName); fprintf(stderr, "DEBUG: type => %d\n", ns_rr_type(dnsRecord)); fprintf(stderr, "DEBUG: class => %d\n", ns_rr_class(dnsRecord)); */ PKI_STACK_MEM_push(ret, obj); // PKI_log_debug("DNS URI: Added object #%d to stack", PKI_STACK_MEM_elements(ret)); } #endif return ret; };
static void table_show_value(char *buf, size_t bufsize, ipfw_table_value *v, uint32_t vmask, int print_ip) { char abuf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2]; struct sockaddr_in6 sa6; uint32_t flag, i, l; size_t sz; struct in_addr a4; sz = bufsize; /* * Some shorthands for printing values: * legacy assumes all values are equal, so keep the first one. */ if (vmask == IPFW_VTYPE_LEGACY) { if (print_ip != 0) { flag = htonl(v->tag); inet_ntop(AF_INET, &flag, buf, sz); } else snprintf(buf, sz, "%u", v->tag); return; } for (i = 1; i < (1 << 31); i *= 2) { if ((flag = (vmask & i)) == 0) continue; l = 0; switch (flag) { case IPFW_VTYPE_TAG: l = snprintf(buf, sz, "%u,", v->tag); break; case IPFW_VTYPE_PIPE: l = snprintf(buf, sz, "%u,", v->pipe); break; case IPFW_VTYPE_DIVERT: l = snprintf(buf, sz, "%d,", v->divert); break; case IPFW_VTYPE_SKIPTO: l = snprintf(buf, sz, "%d,", v->skipto); break; case IPFW_VTYPE_NETGRAPH: l = snprintf(buf, sz, "%u,", v->netgraph); break; case IPFW_VTYPE_FIB: l = snprintf(buf, sz, "%u,", v->fib); break; case IPFW_VTYPE_NAT: l = snprintf(buf, sz, "%u,", v->nat); break; case IPFW_VTYPE_LIMIT: l = snprintf(buf, sz, "%u,", v->limit); break; case IPFW_VTYPE_NH4: a4.s_addr = htonl(v->nh4); inet_ntop(AF_INET, &a4, abuf, sizeof(abuf)); l = snprintf(buf, sz, "%s,", abuf); break; case IPFW_VTYPE_DSCP: l = snprintf(buf, sz, "%d,", v->dscp); break; case IPFW_VTYPE_NH6: sa6.sin6_family = AF_INET6; sa6.sin6_len = sizeof(sa6); sa6.sin6_addr = v->nh6; sa6.sin6_port = 0; sa6.sin6_scope_id = v->zoneid; if (getnameinfo((const struct sockaddr *)&sa6, sa6.sin6_len, abuf, sizeof(abuf), NULL, 0, NI_NUMERICHOST) == 0) l = snprintf(buf, sz, "%s,", abuf); break; } buf += l; sz -= l; } if (sz != bufsize) *(buf - 1) = '\0'; }
std::string Ip() const { char buf[INET6_ADDRSTRLEN]; const char* p = inet_ntop(AF_INET, &m_Addr.sin_addr, buf, sizeof(buf)); return (p != nullptr) ? p : ""; }
static void table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent) { char *comma, tbuf[128], pval[128]; void *paddr; struct tflow_entry *tfe; table_show_value(pval, sizeof(pval), &tent->v.value, i->vmask, co.do_value_as_ip); switch (i->type) { case IPFW_TABLE_ADDR: /* IPv4 or IPv6 prefixes */ inet_ntop(tent->subtype, &tent->k, tbuf, sizeof(tbuf)); printf("%s/%u %s\n", tbuf, tent->masklen, pval); break; case IPFW_TABLE_INTERFACE: /* Interface names */ printf("%s %s\n", tent->k.iface, pval); break; case IPFW_TABLE_NUMBER: /* numbers */ printf("%u %s\n", tent->k.key, pval); break; case IPFW_TABLE_FLOW: /* flows */ tfe = &tent->k.flow; comma = ""; if ((i->tflags & IPFW_TFFLAG_SRCIP) != 0) { if (tfe->af == AF_INET) paddr = &tfe->a.a4.sip; else paddr = &tfe->a.a6.sip6; inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf)); printf("%s%s", comma, tbuf); comma = ","; } if ((i->tflags & IPFW_TFFLAG_PROTO) != 0) { printf("%s%d", comma, tfe->proto); comma = ","; } if ((i->tflags & IPFW_TFFLAG_SRCPORT) != 0) { printf("%s%d", comma, ntohs(tfe->sport)); comma = ","; } if ((i->tflags & IPFW_TFFLAG_DSTIP) != 0) { if (tfe->af == AF_INET) paddr = &tfe->a.a4.dip; else paddr = &tfe->a.a6.dip6; inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf)); printf("%s%s", comma, tbuf); comma = ","; } if ((i->tflags & IPFW_TFFLAG_DSTPORT) != 0) { printf("%s%d", comma, ntohs(tfe->dport)); comma = ","; } printf(" %s\n", pval); } }
static int socketevent_tcp_connect(lua_State *L) { // sock struct LSocketEventTCP *sock = luaL_checkudata(L, 1, LUA_SOCKETEVENT_TCP_HANDLE); // check connect state if (sock->state != 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, 6, "socket has connect"); return 0; } sock->state++; // get params const char *host = luaL_checkstring(L, 2); lua_Integer port = luaL_checkinteger(L, 3); #if defined(_WIN32) WSADATA wsa; // WinSock Startup if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, 2, "c WSAStartup function error!"); return 0; } #endif sock->host = host; if (-1 == inet_addr(host)) { struct hostent *hostinfo; if ((hostinfo = (struct hostent*)gethostbyname(host)) == NULL) { #if defined(_WIN32) socketevent_tcp_trigger_error(sock, sock->L, __LINE__, h_errno, hstrerror(h_errno)); #else socketevent_tcp_trigger_error(sock, sock->L, __LINE__, 18, "domain not found!"); #endif return 0; } if (hostinfo->h_addrtype == AF_INET && hostinfo->h_addr_list != NULL) { #if defined(_WIN32) char ipstr[16]; char * ipbyte = *(hostinfo->h_addr_list); sprintf(ipstr, "%d.%d.%d.%d", *ipbyte, *(ipbyte++), *(ipbyte+2), *(ipbyte+3)); sock->ip = ipstr; #else char ipstr[16]; inet_ntop(hostinfo->h_addrtype, *(hostinfo->h_addr_list), ipstr, sizeof(ipstr)); sock->ip = ipstr; #endif } else { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, 3, "not support ipv6!"); return 0; } } else { sock->ip = host; } sock->port = port; // create socket if ((sock->socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, errno, strerror(errno)); return 0; } #if defined(__linux__) || defined(__ANDROID__) // tcp option set if (sock->keepalive == 1) { if (setsockopt(sock->socket, SOL_SOCKET, SO_KEEPALIVE, (void *)&(sock->keepalive), sizeof(sock->keepalive)) < 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, errno, strerror(errno)); return 0; } if (setsockopt(sock->socket, SOL_TCP, TCP_KEEPIDLE, (void *)&(sock->keepidle), sizeof(sock->keepidle)) < 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, errno, strerror(errno)); return 0; } if (setsockopt(sock->socket, SOL_TCP, TCP_KEEPINTVL, (void *)&(sock->keepintvl), sizeof(sock->keepintvl)) < 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, errno, strerror(errno)); return 0; } if (setsockopt(sock->socket, SOL_TCP, TCP_KEEPCNT, (void *)&(sock->keepcnt), sizeof(sock->keepcnt)) < 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, errno, strerror(errno)); return 0; } } #endif // start thread #if defined(_WIN32) _beginthread(socketevent_tcp_data_win, 0, sock); #else int retval = pthread_create(&sock->thread, NULL, socketevent_tcp_data, sock); if (retval != 0) { socketevent_tcp_trigger_error(sock, sock->L, __LINE__, retval, strerror(retval)); return 0; } #endif return 1; }
/* returns -1 if forbidden, 0 if no tcpwrap check, or 1 if explicitely allowed */ int xio_tcpwrap_check(xiosingle_t *xfd, union sockaddr_union *us, union sockaddr_union *them) { char *save_hosts_allow_table, *save_hosts_deny_table; struct request_info ri; #if WITH_IP6 char clientaddr[INET6_ADDRSTRLEN] = "", serveraddr[INET6_ADDRSTRLEN] = ""; #else char clientaddr[INET_ADDRSTRLEN] = "", serveraddr[INET_ADDRSTRLEN] = ""; #endif int allow; if (!xfd->para.socket.ip.dolibwrap) { return 0; } if (us == NULL || them == NULL) { return -1; } #if defined(HAVE_HOSTS_ALLOW_TABLE) save_hosts_allow_table = hosts_allow_table; if (xfd->para.socket.ip.hosts_allow_table) { Debug1("hosts_allow_table = \"%s\"", xfd->para.socket.ip.hosts_allow_table); hosts_allow_table = xfd->para.socket.ip.hosts_allow_table; } #endif /* defined(HAVE_HOSTS_ALLOW_TABLE) */ #if defined(HAVE_HOSTS_DENY_TABLE) save_hosts_deny_table = hosts_deny_table; if (xfd->para.socket.ip.hosts_deny_table) { Debug1("hosts_deny_table = \"%s\"", xfd->para.socket.ip.hosts_deny_table); hosts_deny_table = xfd->para.socket.ip.hosts_deny_table; } #endif /* defined(HAVE_HOSTS_DENY_TABLE) */ hosts_access_verbose = 32767; if (inet_ntop(them->soa.sa_family, #if WITH_IP6 them->soa.sa_family==PF_INET6 ? (void *)&them->ip6.sin6_addr : #endif (void *)&them->ip4.sin_addr, clientaddr, sizeof(clientaddr)) == NULL) { Warn1("inet_ntop(): %s", strerror(errno)); } if (inet_ntop(us->soa.sa_family, #if WITH_IP6 us->soa.sa_family==PF_INET6 ? (void *)&us->ip6.sin6_addr : #endif (void *)&us->ip4.sin_addr, serveraddr, sizeof(serveraddr)) == NULL) { Warn1("inet_ntop(): %s", strerror(errno)); } Debug7("request_init(%p, RQ_FILE, %d, RQ_CLIENT_SIN, {%s:%u}, RQ_SERVER_SIN, {%s:%u}, RQ_DAEMON, \"%s\", 0", &ri, xfd->fd, clientaddr, ntohs(((struct sockaddr_in *)them)->sin_port), serveraddr, ntohs(us->ip4.sin_port), xfd->para.socket.ip.libwrapname?xfd->para.socket.ip.libwrapname:(char *)diag_get_string('p')); request_init(&ri, RQ_FILE, xfd->fd, RQ_CLIENT_SIN, them, RQ_SERVER_SIN, &us->soa, RQ_DAEMON, xfd->para.socket.ip.libwrapname?xfd->para.socket.ip.libwrapname:(char *)diag_get_string('p'), 0); Debug("request_init() ->"); Debug1("sock_methods(%p)", &ri); sock_methods(&ri); Debug("sock_methods() ->"); Debug1("hosts_access(%p)", &ri); allow = hosts_access(&ri); Debug1("hosts_access() -> %d", allow); #if defined(HAVE_HOSTS_ALLOW_TABLE) hosts_allow_table = save_hosts_allow_table; #endif #if defined(HAVE_HOSTS_DENY_TABLE) hosts_deny_table = save_hosts_deny_table; #endif if (allow == 0) { return -1; } return 1; }
/* Interface between zebra message and rtm message. */ static int kernel_rtm_ipv4 (int cmd, struct prefix *p, struct rib *rib, int family) { struct sockaddr_in *mask = NULL; struct sockaddr_in sin_dest, sin_mask, sin_gate; struct nexthop *nexthop, *tnexthop; int recursing; int nexthop_num = 0; unsigned int ifindex = 0; int gate = 0; int error; char prefix_buf[INET_ADDRSTRLEN]; if (IS_ZEBRA_DEBUG_RIB) inet_ntop (AF_INET, &p->u.prefix, prefix_buf, INET_ADDRSTRLEN); memset (&sin_dest, 0, sizeof (struct sockaddr_in)); sin_dest.sin_family = AF_INET; #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin_dest.sin_len = sizeof (struct sockaddr_in); #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ sin_dest.sin_addr = p->u.prefix4; memset (&sin_mask, 0, sizeof (struct sockaddr_in)); memset (&sin_gate, 0, sizeof (struct sockaddr_in)); sin_gate.sin_family = AF_INET; #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin_gate.sin_len = sizeof (struct sockaddr_in); #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ /* Make gateway. */ for (ALL_NEXTHOPS_RO(rib->nexthop, nexthop, tnexthop, recursing)) { if (CHECK_FLAG (nexthop->flags, NEXTHOP_FLAG_RECURSIVE)) continue; gate = 0; char gate_buf[INET_ADDRSTRLEN] = "NULL"; /* * XXX We need to refrain from kernel operations in some cases, * but this if statement seems overly cautious - what about * other than ADD and DELETE? */ if ((cmd == RTM_ADD && CHECK_FLAG (nexthop->flags, NEXTHOP_FLAG_ACTIVE)) || (cmd == RTM_DELETE && CHECK_FLAG (nexthop->flags, NEXTHOP_FLAG_FIB) )) { if (nexthop->type == NEXTHOP_TYPE_IPV4 || nexthop->type == NEXTHOP_TYPE_IPV4_IFINDEX) { sin_gate.sin_addr = nexthop->gate.ipv4; gate = 1; } if (nexthop->type == NEXTHOP_TYPE_IFINDEX || nexthop->type == NEXTHOP_TYPE_IFNAME || nexthop->type == NEXTHOP_TYPE_IPV4_IFINDEX) ifindex = nexthop->ifindex; if (nexthop->type == NEXTHOP_TYPE_BLACKHOLE) { struct in_addr loopback; loopback.s_addr = htonl (INADDR_LOOPBACK); sin_gate.sin_addr = loopback; gate = 1; } if (gate && p->prefixlen == 32) mask = NULL; else { masklen2ip (p->prefixlen, &sin_mask.sin_addr); sin_mask.sin_family = AF_INET; #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin_mask.sin_len = sin_masklen (sin_mask.sin_addr); #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ mask = &sin_mask; } error = rtm_write (cmd, (union sockunion *)&sin_dest, (union sockunion *)mask, gate ? (union sockunion *)&sin_gate : NULL, ifindex, rib->flags, rib->metric); if (IS_ZEBRA_DEBUG_RIB) { if (!gate) { zlog_debug ("%s: %s/%d: attention! gate not found for rib %p", __func__, prefix_buf, p->prefixlen, rib); rib_dump (p, rib); } else inet_ntop (AF_INET, &sin_gate.sin_addr, gate_buf, INET_ADDRSTRLEN); } switch (error) { /* We only flag nexthops as being in FIB if rtm_write() did its work. */ case ZEBRA_ERR_NOERROR: nexthop_num++; if (IS_ZEBRA_DEBUG_RIB) zlog_debug ("%s: %s/%d: successfully did NH %s", __func__, prefix_buf, p->prefixlen, gate_buf); if (cmd == RTM_ADD) SET_FLAG (nexthop->flags, NEXTHOP_FLAG_FIB); break; /* The only valid case for this error is kernel's failure to install * a multipath route, which is common for FreeBSD. This should be * ignored silently, but logged as an error otherwise. */ case ZEBRA_ERR_RTEXIST: if (cmd != RTM_ADD) zlog_err ("%s: rtm_write() returned %d for command %d", __func__, error, cmd); continue; break; /* Given that our NEXTHOP_FLAG_FIB matches real kernel FIB, it isn't * normal to get any other messages in ANY case. */ case ZEBRA_ERR_RTNOEXIST: case ZEBRA_ERR_RTUNREACH: default: /* This point is reachable regardless of debugging mode. */ if (!IS_ZEBRA_DEBUG_RIB) inet_ntop (AF_INET, &p->u.prefix, prefix_buf, INET_ADDRSTRLEN); zlog_err ("%s: %s/%d: rtm_write() unexpectedly returned %d for command %s", __func__, prefix_buf, p->prefixlen, error, lookup (rtm_type_str, cmd)); break; } } /* if (cmd and flags make sense) */ else if (IS_ZEBRA_DEBUG_RIB) zlog_debug ("%s: odd command %s for flags %d", __func__, lookup (rtm_type_str, cmd), nexthop->flags); } /* for (ALL_NEXTHOPS_RO(...))*/ /* If there was no useful nexthop, then complain. */ if (nexthop_num == 0 && IS_ZEBRA_DEBUG_KERNEL) zlog_debug ("%s: No useful nexthops were found in RIB entry %p", __func__, rib); return 0; /*XXX*/ }
/* * Convert IPv4/IPv6 address to text. */ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, char *dst, int size) { PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL); *dst = '\0'; PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EAFNOTSUP); #if defined(PJ_SOCK_HAS_INET_NTOP) && PJ_SOCK_HAS_INET_NTOP != 0 /* * Implementation using inet_ntop() */ if (inet_ntop(af, src, dst, size) == NULL) { pj_status_t status = pj_get_netos_error(); if (status == PJ_SUCCESS) status = PJ_EUNKNOWN; return status; } return PJ_SUCCESS; #elif defined(PJ_WIN32) || defined(PJ_WIN32_WINCE) /* * Implementation on Windows, using WSAAddressToString(). * Should also work on Unicode systems. */ { PJ_DECL_UNICODE_TEMP_BUF(wtempaddr,PJ_INET6_ADDRSTRLEN) pj_sockaddr sock_addr; DWORD addr_len, addr_str_len; int rc; pj_bzero(&sock_addr, sizeof(sock_addr)); sock_addr.addr.sa_family = (pj_uint16_t)af; if (af == PJ_AF_INET) { if (size < PJ_INET_ADDRSTRLEN) return PJ_ETOOSMALL; pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4); addr_len = sizeof(pj_sockaddr_in); addr_str_len = PJ_INET_ADDRSTRLEN; } else if (af == PJ_AF_INET6) { if (size < PJ_INET6_ADDRSTRLEN) return PJ_ETOOSMALL; pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16); addr_len = sizeof(pj_sockaddr_in6); addr_str_len = PJ_INET6_ADDRSTRLEN; } else { pj_assert(!"Unsupported address family"); return PJ_EAFNOTSUP; } #if PJ_NATIVE_STRING_IS_UNICODE rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, NULL, wtempaddr, &addr_str_len); if (rc == 0) { pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size); } #else rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len, NULL, dst, &addr_str_len); #endif if (rc != 0) { pj_status_t status = pj_get_netos_error(); if (status == PJ_SUCCESS) status = PJ_EUNKNOWN; return status; } return PJ_SUCCESS; } #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0 /* IPv6 support is disabled, just return error without raising assertion */ return PJ_EIPV6NOTSUP; #else pj_assert(!"Not supported"); return PJ_EIPV6NOTSUP; #endif }
/* * Receives a packet, assuming that the RADIUS_PACKET structure * has been filled out already. * * This ASSUMES that the packet is allocated && fields * initialized. * * This ASSUMES that the socket is marked as O_NONBLOCK, which * the function above does set, if your system supports it. * * Calling this function MAY change sockfd, * if src_ipaddr.af == AF_UNSPEC. */ int fr_tcp_read_packet(RADIUS_PACKET *packet, int flags) { ssize_t len; /* * No data allocated. Read the 4-byte header into * a temporary buffer. */ if (!packet->data) { int packet_len; len = recv(packet->sockfd, packet->vector + packet->data_len, 4 - packet->data_len, 0); if (len == 0) return -2; /* clean close */ #ifdef ECONNRESET if ((len < 0) && (errno == ECONNRESET)) { /* forced */ return -2; } #endif if (len < 0) { fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno)); return -1; } packet->data_len += len; if (packet->data_len < 4) { /* want more data */ return 0; } packet_len = (packet->vector[2] << 8) | packet->vector[3]; if (packet_len < AUTH_HDR_LEN) { fr_strerror_printf("Discarding packet: Smaller than RFC minimum of 20 bytes"); return -1; } /* * If the packet is too big, then the socket is bad. */ if (packet_len > MAX_PACKET_LEN) { fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes"); return -1; } packet->data = talloc_array(packet, uint8_t, packet_len); if (!packet->data) { fr_strerror_printf("Out of memory"); return -1; } packet->data_len = packet_len; packet->partial = 4; memcpy(packet->data, packet->vector, 4); } /* * Try to read more data. */ len = recv(packet->sockfd, packet->data + packet->partial, packet->data_len - packet->partial, 0); if (len == 0) return -2; /* clean close */ #ifdef ECONNRESET if ((len < 0) && (errno == ECONNRESET)) { /* forced */ return -2; } #endif if (len < 0) { fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno)); return -1; } packet->partial += len; if (packet->partial < packet->data_len) { return 0; } /* * See if it's a well-formed RADIUS packet. */ if (!rad_packet_ok(packet, flags, NULL)) { return -1; } /* * Explicitly set the VP list to empty. */ packet->vps = NULL; if (fr_debug_flag) { char ip_buf[128], buffer[256]; if (packet->src_ipaddr.af != AF_UNSPEC) { inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, ip_buf, sizeof(ip_buf)); snprintf(buffer, sizeof(buffer), "host %s port %d", ip_buf, packet->src_port); } else { snprintf(buffer, sizeof(buffer), "socket %d", packet->sockfd); } if (is_radius_code(packet->code)) { DEBUG("Received %s packet from %s", fr_packet_codes[packet->code], buffer); } else { DEBUG("Received packet from %s code %d", buffer, packet->code); } DEBUG(", id=%d, length=%zu\n", packet->id, packet->data_len); } return 1; /* done reading the packet */ }
/* {{{ ftp_getdata */ databuf_t* ftp_getdata(ftpbuf_t *ftp) { int fd = -1; databuf_t *data; php_sockaddr_storage addr; struct sockaddr *sa; socklen_t size; union ipbox ipbox; char arg[sizeof("255, 255, 255, 255, 255, 255")]; struct timeval tv; /* ask for a passive connection if we need one */ if (ftp->pasv && !ftp_pasv(ftp, 1)) { return NULL; } /* alloc the data structure */ data = ecalloc(1, sizeof(*data)); data->listener = -1; data->fd = -1; data->type = ftp->type; sa = (struct sockaddr *) &ftp->localaddr; /* bind/listen */ if ((fd = socket(sa->sa_family, SOCK_STREAM, 0)) == SOCK_ERR) { php_error_docref(NULL, E_WARNING, "socket() failed: %s (%d)", strerror(errno), errno); goto bail; } /* passive connection handler */ if (ftp->pasv) { /* clear the ready status */ ftp->pasv = 1; /* connect */ /* Win 95/98 seems not to like size > sizeof(sockaddr_in) */ size = php_sockaddr_size(&ftp->pasvaddr); tv.tv_sec = ftp->timeout_sec; tv.tv_usec = 0; if (php_connect_nonb(fd, (struct sockaddr*) &ftp->pasvaddr, size, &tv) == -1) { php_error_docref(NULL, E_WARNING, "php_connect_nonb() failed: %s (%d)", strerror(errno), errno); goto bail; } data->fd = fd; ftp->data = data; return data; } /* active (normal) connection */ /* bind to a local address */ php_any_addr(sa->sa_family, &addr, 0); size = php_sockaddr_size(&addr); if (bind(fd, (struct sockaddr*) &addr, size) != 0) { php_error_docref(NULL, E_WARNING, "bind() failed: %s (%d)", strerror(errno), errno); goto bail; } if (getsockname(fd, (struct sockaddr*) &addr, &size) != 0) { php_error_docref(NULL, E_WARNING, "getsockname() failed: %s (%d)", strerror(errno), errno); goto bail; } if (listen(fd, 5) != 0) { php_error_docref(NULL, E_WARNING, "listen() failed: %s (%d)", strerror(errno), errno); goto bail; } data->listener = fd; #if HAVE_IPV6 && HAVE_INET_NTOP if (sa->sa_family == AF_INET6) { /* need to use EPRT */ char eprtarg[INET6_ADDRSTRLEN + sizeof("|x||xxxxx|")]; char out[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &((struct sockaddr_in6*) sa)->sin6_addr, out, sizeof(out)); snprintf(eprtarg, sizeof(eprtarg), "|2|%s|%hu|", out, ntohs(((struct sockaddr_in6 *) &addr)->sin6_port)); if (!ftp_putcmd(ftp, "EPRT", eprtarg)) { goto bail; } if (!ftp_getresp(ftp) || ftp->resp != 200) { goto bail; } ftp->data = data; return data; } #endif /* send the PORT */ ipbox.ia[0] = ((struct sockaddr_in*) sa)->sin_addr; ipbox.s[2] = ((struct sockaddr_in*) &addr)->sin_port; snprintf(arg, sizeof(arg), "%u,%u,%u,%u,%u,%u", ipbox.c[0], ipbox.c[1], ipbox.c[2], ipbox.c[3], ipbox.c[4], ipbox.c[5]); if (!ftp_putcmd(ftp, "PORT", arg)) { goto bail; } if (!ftp_getresp(ftp) || ftp->resp != 200) { goto bail; } ftp->data = data; return data; bail: if (fd != -1) { closesocket(fd); } efree(data); return NULL; }
int main(void) { fd_set master; // master file descriptor list fd_set read_fds; // temp file descriptor list for select() int fdmax; // maximum file descriptor number int listener; // listening socket descriptor int newfd; // newly accept()ed socket descriptor struct sockaddr_storage remoteaddr; // client address socklen_t addrlen; char buf[256]; // buffer for client data int nbytes; int connected_clients[10] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int clients_fds[10] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; char remoteIP[INET6_ADDRSTRLEN]; int yes=1; // for setsockopt() SO_REUSEADDR, below int i, j, rv; struct addrinfo hints, *ai, *p; FD_ZERO(&master); // clear the master and temp sets FD_ZERO(&read_fds); // get us a socket and bind it memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) { fprintf(stderr, "selectserver: %s\n", gai_strerror(rv)); exit(1); } for(p = ai; p != NULL; p = p->ai_next) { listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listener < 0) { continue; } // lose the pesky "address already in use" error message setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) { close(listener); continue; } break; } // if we got here, it means we didn't get bound if (p == NULL) { fprintf(stderr, "selectserver: failed to bind\n"); exit(2); } freeaddrinfo(ai); // all done with this // listen if (listen(listener, 10) == -1) { perror("listen"); exit(3); } // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; // so far, it's this one // main loop for(;;) { read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } // run through the existing connections looking for data to read for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { // we got one!! if (i == listener) { // handle new connections addrlen = sizeof remoteaddr; newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen); if (newfd == -1) { perror("accept"); } else { FD_SET(newfd, &master); // add to master set if (newfd > fdmax) { // keep track of the max fdmax = newfd; } printf("selectserver: new connection from %s on " "socket %d\n", inet_ntop(remoteaddr.ss_family, get_in_addr((struct sockaddr*)&remoteaddr), remoteIP, INET6_ADDRSTRLEN), newfd); } } else { // handle data from a client if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) { // got error or connection closed by client if (nbytes == 0) { // connection closed printf("selectserver: socket %d hung up\n", i); // TODO: remove hung up client from our list. } else { perror("recv"); } close(i); // bye! FD_CLR(i, &master); // remove from master set } else { printf("Received data %s from client.\n", buf); fflush(stdout); /* THIS IS THE IMPORTANT PART*/ // this is where all info from the client is processed. int tokenval = 0; char *token[255]; //user input and array to hold max possible tokens. token[0] = strtok(buf, " "); //get pointer to first token found and store in 0 //place in array while(token[tokenval]!= NULL) { //ensure a pointer was found tokenval++; token[tokenval] = strtok(NULL, " "); //continue to tokenize the string } if (strcmp(token[0], "identify") == 0) { int clival = atoi(token[1]); printf("received an identification of a client.\n"); // loop through our connected clients and find a place to put him. int foundspot = 0; for (j = 0; j < 10; j++) { if (connected_clients[j] == clival) { close(i); // duplicate client identifier. FD_CLR(i, &master); // remove from master set foundspot = 1; break; } if (connected_clients[j] < 0) { foundspot = 1; // found an empty spot. connected_clients[j] = clival; clients_fds[j] = i; break; } } if (!foundspot) { close(i); // too many connections. FD_CLR(i, &master); // remove from master set } fflush(stdout); } else if (strcmp(token[0], "listclients") == 0) // inquire about # of connected clients. { int clients = 0; for (j = 0; j < 10; j++) { if (connected_clients[j] >= 0) { clients += 1; } } char temp[10]; sprintf(temp, "%i", clients); send(i, temp, 5, 0); /* // TODO: use our list of clients to find out the # of clients instead of inspecting // this file structure. for(j = 0; j <= fdmax; j++) { // count up everyone if (FD_ISSET(j, &master)) { // except ourselves if (j != i) {//(j != listener && j != i) { clients += 1; } } } */ /* for(j = 0; j <= fdmax; j++) { // send to everyone! if (FD_ISSET(j, &master)) { // except the listener and ourselves if (j != listener && j != i) { fflush(stdout); if (send(j, buf, nbytes, 0) == -1) { perror("send"); } } } }*/ } } } // END handle data from client } // END got new incoming connection } // END looping through file descriptors } // END for(;;)--and you thought it would never end! return 0; }
int nntp_connect(void) { char *q, *ipver = NULL, ipstr[INET6_ADDRSTRLEN], servport[10]; struct addrinfo hints, *res = NULL, *p; int rc; if (nntpsock != -1) return nntpsock; if (!strlen(CFG.nntpnode)) { WriteError("NNTP: host not configured"); return -1; } snprintf(servport, 9, "%d", CFG.nntpport); Syslog('+', "NNTP: connecting host: %s port %s", CFG.nntpnode, servport); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rc = getaddrinfo(CFG.nntpnode, servport, &hints, &res)) != 0) { WriteError("getaddrinfo %s:%s %s\n", CFG.nntpnode, servport, gai_strerror(rc)); return -1; } for (p = res; p != NULL; p = p->ai_next) { void *addr; if (p->ai_family == AF_INET) { struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr; addr = &(ipv4->sin_addr); ipver = (char *)"IPv4"; } else { struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; addr = &(ipv6->sin6_addr); ipver = (char *)"IPv6"; } inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); Syslog('+', "Trying %s %s port %s", ipver, ipstr, servport); if ((nntpsock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { WriteError("$socket()"); return -1; } else { if (connect(nntpsock, p->ai_addr, p->ai_addrlen) == -1) { WriteError("$connect %s port %s", ipstr, servport); close(nntpsock); } else { break; } } } if (p == NULL) { return -1; /* Not connected */ } q = nntp_receive(); if (strlen(q) == 0) { WriteError("NNTP: no response"); nntp_close(); return -1; } Syslog('+', "NNTP: %s", q); if ((strncmp(q, "480", 3) == 0) || CFG.nntpforceauth) { /* * Must login with username and password */ if (nntp_auth() == FALSE) { WriteError("Authorisation failure"); nntp_close(); return -1; } } else if (strncmp(q, "200", 3)) { WriteError("NNTP: bad response: %s", q); // nntp_close(); FIXME: Don't close, the other end might have done that already // If we do also, this program hangs. Must be fixed! return -1; } if (CFG.modereader) { Syslog('+', "NNTP: setting mode reader"); nntp_send((char *)"MODE READER\r\n"); q = nntp_receive(); Syslog('+', "NNTP: %s", q); if (strncmp(q, "480", 3) == 0) { /* * Must login with username and password */ Syslog('+', "NNTP: %s", q); if (nntp_auth() == FALSE) { WriteError("NNTP: authorisation failure"); nntp_close(); return -1; } } else if (strncmp(q, "200", 3)) { WriteError("NNTP: bad response: %s", q); nntp_close(); return -1; } } return nntpsock; }
std::string CNetworkInterfaceLinux::GetCurrentDefaultGateway(void) { std::string result; #if defined(TARGET_DARWIN) FILE* pipe = popen("echo \"show State:/Network/Global/IPv4\" | scutil | grep Router", "r"); Sleep(100); if (pipe) { std::string tmpStr; char buffer[256] = {'\0'}; if (fread(buffer, sizeof(char), sizeof(buffer), pipe) > 0 && !ferror(pipe)) { tmpStr = buffer; if (tmpStr.length() >= 11) result = tmpStr.substr(11); } pclose(pipe); } if (result.empty()) CLog::Log(LOGWARNING, "Unable to determine gateway"); #elif defined(TARGET_FREEBSD) size_t needed; int mib[6]; char *buf, *next, *lim; char line[16]; struct rt_msghdr *rtm; struct sockaddr *sa; struct sockaddr_in *sockin; mib[0] = CTL_NET; mib[1] = PF_ROUTE; mib[2] = 0; mib[3] = 0; mib[4] = NET_RT_DUMP; mib[5] = 0; if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) return result; if ((buf = (char *)malloc(needed)) == NULL) return result; if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { free(buf); return result; } lim = buf + needed; for (next = buf; next < lim; next += rtm->rtm_msglen) { rtm = (struct rt_msghdr *)next; sa = (struct sockaddr *)(rtm + 1); sa = (struct sockaddr *)(SA_SIZE(sa) + (char *)sa); sockin = (struct sockaddr_in *)sa; if (inet_ntop(AF_INET, &sockin->sin_addr.s_addr, line, sizeof(line)) == NULL) { free(buf); return result; } result = line; break; } free(buf); #else FILE* fp = fopen("/proc/net/route", "r"); if (!fp) { // TBD: Error return result; } char* line = NULL; char iface[16]; char dst[128]; char gateway[128]; size_t linel = 0; int n; int linenum = 0; while (getdelim(&line, &linel, '\n', fp) > 0) { // skip first two lines if (linenum++ < 1) continue; // search where the word begins n = sscanf(line, "%16s %128s %128s", iface, dst, gateway); if (n < 3) continue; if (strcmp(iface, m_interfaceName.c_str()) == 0 && strcmp(dst, "00000000") == 0 && strcmp(gateway, "00000000") != 0) { unsigned char gatewayAddr[4]; int len = CNetwork::ParseHex(gateway, gatewayAddr); if (len == 4) { struct in_addr in; in.s_addr = (gatewayAddr[0] << 24) | (gatewayAddr[1] << 16) | (gatewayAddr[2] << 8) | (gatewayAddr[3]); result = inet_ntoa(in); break; } } } free(line); fclose(fp); #endif return result; }
int main(int argc, char *argv[]) { struct sockaddr_in sockname, client; struct sigaction sa; struct tm* time_struct; FILE * logfile; socklen_t clientlen; int sd; char timec[80]; char dircopy[80]; char *ep; time_t rawtime; u_short port; pid_t pid; u_long p; /* * first, figure out what port we will listen on - it should * be our first parameter. */ if (argc != 4) { usage(); errno = 0; } p = strtoul(argv[1], &ep, 10); if (*argv[1] == '\0' || *ep != '\0') { /* parameter wasn't a number, or was empty */ fprintf(stderr, "%s - not a number\n", argv[1]); usage(); } if ((errno == ERANGE && p == ULONG_MAX) || (p > USHRT_MAX)) { /* It's a number, but it either can't fit in an unsigned * long, or is too big for an unsigned short */ fprintf(stderr, "%s - value out of range\n", argv[1]); usage(); } strncpy(dircopy, argv[2], sizeof(dircopy)); /* Checking if the directory exists. * adapted from * http://stackoverflow.com/a/12510903 */ if (opendir(dircopy) == NULL) { fprintf(stderr, "Directory does not exist.\n"); usage(); } /* * Check to make sure logfile can open and does exist */ logfile = fopen(argv[3], "a"); if (logfile == NULL) { fprintf(stderr, "Error opening logfile.\n"); usage(); } fclose(logfile); /* used strncpy as I found out assignment is not possible */ strncpy(docdir, argv[2], sizeof(docdir)); strncpy(logdir, argv[3], sizeof(logdir)); /* now safe to do this */ if (daemon(1, 0) == -1) { fprintf(stderr, "Could not daemonize.\n"); usage(); } port = p; memset(&sockname, 0, sizeof(sockname)); sockname.sin_family = AF_INET; sockname.sin_port = htons(port); sockname.sin_addr.s_addr = htonl(INADDR_ANY); sd=socket(AF_INET,SOCK_STREAM,0); if ( sd == -1) err(1, "socket failed"); if (bind(sd, (struct sockaddr *) &sockname, sizeof(sockname)) == -1) err(1, "bind failed"); if (listen(sd,3) == -1) err(1, "listen failed"); /* * we're now bound, and listening for connections on "sd" - * each call to "accept" will return us a descriptor talking to * a connected client */ /* * first, let's make sure we can have children without leaving * zombies around when they die - we can do this by catching * SIGCHLD. */ sa.sa_handler = kidhandler; sigemptyset(&sa.sa_mask); /* * we want to allow system calls like accept to be restarted if they * get interrupted by a SIGCHLD */ sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) err(1, "sigaction failed"); /* * finally - the main loop. accept connections and deal with 'em */ for(;;) { int clientsd; clientlen = sizeof(&client); clientsd = accept(sd, (struct sockaddr *)&client, &clientlen); if (clientsd == -1) err(1, "accept failed"); /* * We fork child to deal with each connection, this way more * than one client can connect to us and get served at any one * time. */ pid = fork(); if (pid == -1) err(1, "fork failed"); if(pid == 0) { /* * Using INET to determine client ip * code adapted from * http://stackoverflow.com/a/3060988 */ char clientip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(client.sin_addr), clientip, INET_ADDRSTRLEN); /* * Getting current time using time library * code adapted from * http://stackoverflow.com/a/10332099 */ time(&rawtime); time_struct = localtime(&rawtime); strftime(timec, 80, "%a, %d %b %Y %X %Z", time_struct); client_request(clientsd, timec, clientip); exit(0); } close(clientsd); } }
/* returns socket fd, and sets ipaddr to IP (4 or 6) of host when connected */ int fsaf_connect_to_admind(char *host, int port, struct addrinfo *hints, char *ipaddr) { char cport[6]; /* 16 bit int + '\0' */ int rv; int sock_fd; struct addrinfo *server_ai, *p; /* convert integer port to string */ sprintf(cport, "%d", port); rv = getaddrinfo(host, cport, hints, &server_ai); if (rv != 0) { fsa_error(LOG_DEBUG, "getaddrinfo failed: %s", gai_strerror(rv)); errno = rv; /* use gai_strerror to get value */ return -1; } /* connect to first available socket */ for (p = server_ai; p != NULL; p = p->ai_next) { sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sock_fd == -1) { fsa_error(LOG_DEBUG, "socket failed: %s", strerror(errno)); continue; } rv = connect(sock_fd, p->ai_addr, p->ai_addrlen); if (rv == -1) { fsa_error(LOG_DEBUG, "connect failed: %s", strerror(errno)); close(sock_fd); continue; } /* no errors, so break */ break; } /* check that we actually connected */ if (p == NULL) { fsa_error(LOG_DEBUG, "failed to connect to %s:%d", host, port); freeaddrinfo(server_ai); errno = ADM_ERR_CONN_FAILED; return -1; } if (server_ai->ai_family == AF_INET6) { struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)server_ai->ai_addr; inet_ntop(AF_INET6, &(ipv6->sin6_addr), ipaddr, INET6_ADDRSTRLEN); } else if (server_ai->ai_family == AF_INET) { struct sockaddr_in *ipv4 = (struct sockaddr_in *)server_ai->ai_addr; inet_ntop(AF_INET, &(ipv4->sin_addr), ipaddr, INET6_ADDRSTRLEN); } freeaddrinfo(server_ai); fsa_error(LOG_DEBUG, "connected to %s:%d (%s) on sock_fd %d", host, port, ipaddr, sock_fd); return sock_fd; }
GOS_ERROR_CODE rtn_ipv6_route(int wanIndex) { int i = 0, prefix = 0; char cmdStr[512] = {0}; char tempcmd[256] = {0}; char buf[64] = {0}, appname[32] = {0}; RG_IPV6_SROUTE_RULE_T *pData; if (gRtnParams.wan_cfg[wanIndex].ip6State != RG_WAN_IF_UP) { RTN_LOG("Cfg ipv6 route wan%d not up, state:%d, return!", wanIndex, gRtnParams.wan_cfg[wanIndex].ip6State); return GOS_OK; } RTN_LOG("IPv6 Routing count = %d", gRtnParams.route_cfg.sroutev6.count); for(i = 0; i <gRtnParams.route_cfg.sroutev6.count; i++) { pData = &gRtnParams.route_cfg.sroutev6.rules[i]; if(pData->wan_index == 0) { sprintf(appname, "br0"); } else if (pData->wan_index != (wanIndex+1)) { continue; } else { memset(appname, 0, sizeof(appname)); strcpy(appname, gRtnParams.wan_cfg[wanIndex].wanInfo.appName); } if(pData->static_mode == TRUE) { inet_ntop(AF_INET6, pData->dest_ip, buf, sizeof(buf)); prefix = pData->dest_prefixlen; sprintf(cmdStr, "ip -6 route add %s/%d ", buf, prefix); inet_ntop(AF_INET6, pData->next_hop, buf, sizeof(buf)); sprintf(tempcmd, "via %s ", buf); strcat(cmdStr, tempcmd); sprintf(tempcmd, "dev %s ", appname); strcat(cmdStr, tempcmd); RTN_LOG("%s\n", cmdStr); system(cmdStr); } else { inet_ntop(AF_INET6, pData->src_ip, buf, sizeof(buf)); prefix = pData->src_prefixlen; sprintf(cmdStr, "ip -6 rule add from %s/%d table %d pref %d ", buf, prefix, i + POLICY_ROUTEV6_OFFSET, i + POLICY_ROUTEV6_OFFSET); system(cmdStr); RTN_LOG("%s", cmdStr); sprintf(cmdStr, "ip -6 route add default "); inet_ntop(AF_INET6, pData->next_hop, buf, sizeof(buf)); sprintf(tempcmd, "via %s ", buf); strcat(cmdStr, tempcmd); sprintf(tempcmd, "dev %s table %d ", appname, i + POLICY_ROUTEV6_OFFSET); strcat(cmdStr, tempcmd); system(cmdStr); RTN_LOG("%s\n", cmdStr); } } return GOS_OK; }