void CWE190_Integer_Overflow__int_connect_socket_square_66_bad() { int data; int dataArray[5]; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* put data in array */ dataArray[2] = data; CWE190_Integer_Overflow__int_connect_socket_square_66b_badSink(dataArray); }
int main(int argc, char * argv[]) { int sock, result, TCP_PORT; //struct sockaddr_in server, client; char word_f[MAXBUF]; //char word_b[MAXBUF]; struct sockaddr_in address; if( argc != 3 ) { printf("USAGE: %s hostname port\n",argv[0]); exit(-1); } TCP_PORT = atoi(argv[2]); sock = socket(AF_INET, SOCK_STREAM, 0); if( sock < 0) { perror("creating stream socket"); exit(1); } address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(argv[1]); address.sin_port = htons(TCP_PORT); //len = sizeof(address); result = connect(sock, (struct sockaddr *)&address, sizeof(address)); if(result == -1) { perror("Error on client"); exit(1); } printf("Enter word: "); while (fgets (word_f, MAXBUF, stdin) != NULL) { char *temp; temp = strtok (word_f, "\n"); int w; w = write (sock, temp, sizeof(temp)); if (w<0) { perror ("Writing message"); exit(1); } // Added this for exiting the client if (strcmp (temp, "-exit")==0){ printf("Exiting...\n"); close(sock); exit(0); } int r, tf; r = read (sock, &tf, sizeof(int)); if (r<0) { perror ("Reading message"); exit(1); } if (tf) { printf ("The word %s is spelled correctly\n", temp); } else { printf ("The word %s is spelled incorrectly\n", temp); int r2; char list[10][MAXBUF]; r2 = read (sock, list, sizeof(list)); if (r2<0) { perror ("Reading message"); exit(1); } for (int i=0; i<10; i++) { if (list[i][0]!='\0'){ printf("%s\n", list[i]); } } } printf("\nEnter word: "); } //return 0; }
int main(int argc, char* argv[]) { //---------------------- // Initialize Winsock. WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != NO_ERROR) { wprintf(L"WSAStartup failed with error: %ld\n", iResult); return 1; } //---------------------- // Create a SOCKET for connecting to server SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ConnectSocket == INVALID_SOCKET) { printf("Error at socket(): %ld\n", WSAGetLastError() ); WSACleanup(); return 1; } //---------------------- // The sockaddr_in structure specifies the address family, // IP address, and port for the socket that is being bound. sockaddr_in addrServer; addrServer.sin_family = AF_INET; addrServer.sin_addr.s_addr = inet_addr( "127.0.0.1" ); addrServer.sin_port = htons(20131); //---------------------- // Connect to server. iResult = connect( ConnectSocket, (SOCKADDR*) &addrServer, sizeof(addrServer) ); if ( iResult == SOCKET_ERROR) { closesocket (ConnectSocket); printf("Unable to connect to server: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } char buf[1024+1]; //以一个无限循环的方式,不停地接收输入,发送到server while(1) { int count = _read (0, buf, 1024);//从标准输入读入 if(count<=0)break; int sendCount,currentPosition=0; while( count>0 && (sendCount=send(ConnectSocket ,buf+currentPosition,count,0))!=SOCKET_ERROR) { count-=sendCount; currentPosition+=sendCount; } if(sendCount==SOCKET_ERROR)break; count =recv(ConnectSocket ,buf,1024,0); if(count==0)break;//被对方关闭 if(count==SOCKET_ERROR)break;//错误count<0 buf[count]='\0'; printf("%s",buf); } //结束连接 closesocket(ConnectSocket); WSACleanup(); return 0; }
int8 Wechat_data_produce(void *args, uint8 **r_data, uint32 *r_len) { static uint16 bleDemoHeadLen = sizeof(WechatBlueDemoHead); wechat_info *info = (wechat_info *)args; BaseRequest basReq = {NULL}; static uint8 fix_head_len = sizeof(BpFixHead); BpFixHead fix_head = {0xFE, 1, 0, htons(ECI_req_auth), 0}; wechatSta.seq++; int ret; switch (info->cmd) { case WECHAT_CMD_AUTH: { #if defined EAM_md5AndAesEnrypt uint8 deviceid[] = DEVICE_ID; static uint32 seq = 0x00000001;// uint32 ran = 0x11223344;//ΪÁË·½±ãÆð¼ûÕâÀï·ÅÁËÒ»¸ö¹Ì¶¨Öµ×öΪËæ»úÊý£¬ÔÚʹÓÃʱÇë×ÔÐÐÉú³ÉËæ»úÊý¡£ ran = t_htonl(ran); seq = t_htonl(seq); uint8 id_len = osal_strlen(DEVICE_ID); uint8* data = osal_mem_alloc(id_len+8); if(!data) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } memcpy(data,deviceid,id_len); memcpy(data+id_len,(uint8*)&ran,4); memcpy(data+id_len+4,(uint8*)&seq,4); uint32 crc = crc32(0, data, id_len+8); crc = t_htonl(crc); NPI_Printf("Wechat_data_produce 0x%x!\r\n", crc); osal_memset(data,0x00,id_len+8); memcpy(data,(uint8*)&ran,4); memcpy(data+4,(uint8*)&seq,4); memcpy(data+8,(uint8*)&crc,4); //uint8 CipherText[16]; //AES_Init(key); //AES_Encrypt_PKCS7 (data, CipherText, 12, key); uint8 CipherText[128]; encrypt_data(data, CipherText, key); if(data) { osal_mem_free(data); data = NULL; } AuthRequest authReq = { &basReq, true, {md5_type_and_id, MD5_TYPE_AND_ID_LENGTH}, PROTO_VERSION, AUTH_PROTO, (EmAuthMethod)AUTH_METHOD, true , {CipherText, CIPHER_TEXT_LENGTH}, false, {NULL, 0}, false, {NULL, 0}, false, {NULL, 0}, true, {DEVICE_ID,sizeof(DEVICE_ID)} }; seq++; #endif #if defined EAM_macNoEncrypt static uint8 mac_address[MAC_ADDRESS_LENGTH]; wechat_get_mac_addr(mac_address); AuthRequest authReq = { &basReq, false, {NULL, 0}, PROTO_VERSION, AUTH_PROTO, (EmAuthMethod)AUTH_METHOD, false, {NULL, 0}, true, {mac_address, MAC_ADDRESS_LENGTH}, false, {NULL, 0}, false, {NULL, 0}, true, {DEVICE_ID,sizeof(DEVICE_ID)} }; #endif #if defined EAM_md5AndNoEnrypt AuthRequest authReq = { &basReq, true, {md5_type_and_id, MD5_TYPE_AND_ID_LENGTH}, PROTO_VERSION, (EmAuthMethod)AUTH_PROTO, (EmAuthMethod)AUTH_METHOD, false , {NULL, 0}, false, {NULL, 0}, false, {NULL, 0}, false, {NULL, 0}, true, {DEVICE_ID,sizeof(DEVICE_ID)} }; #endif *r_len = (uint32)epb_auth_request_pack_size(&authReq) + fix_head_len; *r_data = (uint8 *)osal_mem_alloc(*r_len); if(!(*r_data)) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } ret = epb_pack_auth_request(&authReq, *r_data+fix_head_len, *r_len-fix_head_len); if( ret <0) { osal_mem_free(*r_data); *r_data = NULL; NPI_Printf("epb pack auth request failed!\r\n"); return ret; } fix_head.nCmdId = htons(ECI_req_auth); fix_head.nLength = htons((uint16)*r_len); fix_head.nSeq = htons(wechatSta.seq); memcpy(*r_data, &fix_head, fix_head_len); break; } case WECHAT_CMD_INIT: { //has challeange InitRequest initReq = {&basReq,false, {NULL, 0},true, {challeange, CHALLENAGE_LENGTH}}; *r_len = epb_init_request_pack_size(&initReq) + fix_head_len; #if defined EAM_md5AndAesEnrypt uint8 length = *r_len; uint8 *p = osal_mem_alloc(AES_get_length( *r_len-fix_head_len)); if(!p) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } *r_len = AES_get_length( *r_len-fix_head_len)+fix_head_len; #endif //pack data *r_data = (uint8 *)osal_mem_alloc(*r_len); if(!(*r_data)) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } ret = epb_pack_init_request(&initReq, *r_data+fix_head_len, *r_len-fix_head_len); if( ret < 0 ) { osal_mem_free(*r_data); *r_data = NULL; return ret; } //encrypt body #if defined EAM_md5AndAesEnrypt //AES_Init(session_key); //AES_Encrypt_PKCS7(*r_data+fix_head_len,p,length-fix_head_len,session_key);//ÔʼÊý¾Ý³¤¶È //uint8 CipherText[128]; encrypt_data(*r_data+fix_head_len,p, session_key); memcpy(*r_data + fix_head_len, p, *r_len-fix_head_len); if(p) osal_mem_free(p); #endif fix_head.nCmdId = htons(ECI_req_init); fix_head.nLength = htons(*r_len); fix_head.nSeq = htons(wechatSta.seq); memcpy(*r_data, &fix_head, fix_head_len); break; } case WECHAT_CMD_TEST_SENDDAT: { //NPI_Printf("test msg to send : %s \r\n",(uint8*)info->send_msg.str); WechatBlueDemoHead *bleDemoHead = (WechatBlueDemoHead*)osal_mem_alloc(bleDemoHeadLen+info->send_msg.len); if(!bleDemoHead) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } bleDemoHead->m_magicCode[0] = WECHAT_MAGICCODE_H; bleDemoHead->m_magicCode[1] = WECHAT_MAGICCODE_L; bleDemoHead->m_version = htons( WECHAT_VERSION); bleDemoHead->m_totalLength = htons(bleDemoHeadLen + info->send_msg.len); bleDemoHead->m_cmdid = htons(sendTextReq); bleDemoHead->m_seq = htons(wechatSta.seq); bleDemoHead->m_errorCode = 0; /*connect body and head.*/ /*turn to uint8* befort offset.*/ memcpy((uint8*)bleDemoHead+bleDemoHeadLen, info->send_msg.str, info->send_msg.len); SendDataRequest sendDatReq = {&basReq, {(uint8*) bleDemoHead, (bleDemoHeadLen + info->send_msg.len)}, false, (EmDeviceDataType)NULL}; *r_len = epb_send_data_request_pack_size(&sendDatReq) + fix_head_len; #if defined EAM_md5AndAesEnrypt uint16 length = *r_len; uint8 *p = osal_mem_alloc(AES_get_length( *r_len-fix_head_len)); if(!p) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } *r_len = AES_get_length( *r_len-fix_head_len)+fix_head_len; #endif *r_data = (uint8 *)osal_mem_alloc(*r_len); if(!(*r_data)) { NPI_Printf("Not enough memory!\r\n"); return ( bleMemAllocError ); } ret = epb_pack_send_data_request(&sendDatReq, *r_data+fix_head_len, *r_len-fix_head_len); if( ret < 0 ) { *r_data = NULL; #if defined EAM_md5AndAesEnrypt if(p) { osal_mem_free(p); p = NULL; } #endif NPI_Printf("\r\nepb_pack_send_data_request error!"); return ret; } #if defined EAM_md5AndAesEnrypt //encrypt body //AES_Init(session_key); //AES_Encrypt_PKCS7(*r_data+fix_head_len,p,length-fix_head_len,session_key);//ÔʼÊý¾Ý³¤¶È encrypt_data(*r_data+fix_head_len,p, session_key); memcpy(*r_data + fix_head_len, p, *r_len-fix_head_len); if(p) { osal_mem_free(p); p = NULL; } #endif fix_head.nCmdId = htons(ECI_req_sendData); fix_head.nLength = htons(*r_len); fix_head.nSeq = htons(wechatSta.seq); memcpy(*r_data, &fix_head, fix_head_len); if(bleDemoHead) { osal_mem_free(bleDemoHead); bleDemoHead = NULL; } #if 0 NPI_Printf("##send data: "); uint8 *d = *r_data; for(uint8 i=0;i<*r_len;++i) { NPI_Printf(" %x",d[i]); } BpFixHead *fix_head = (BpFixHead *)*r_data; NPI_Printf("\r\n CMDID: %d\r\n",ntohs(fix_head->nCmdId)); NPI_Printf("len: %d\r\n", ntohs(fix_head->nLength )); NPI_Printf("Seq: %d\r\n", ntohs(fix_head->nSeq)); #endif wechatSta.send_data_seq++; break; } } return SUCCESS; }
void dnsproxy_query(PNATState pData, struct socket *so, struct mbuf *m, int iphlen) #endif { #ifndef VBOX char buf[MAX_BUFSPACE]; unsigned int fromlen = sizeof(fromaddr); struct timeval tv; #else struct ip *ip; char *buf; int retransmit; struct udphdr *udp; #endif struct sockaddr_in addr; struct request *req = NULL; #ifndef VBOX struct sockaddr_in fromaddr; #else struct sockaddr_in fromaddr = { 0, }; #endif int byte = 0; ++all_queries; #ifndef VBOX /* Reschedule event */ event_add((struct event *)arg, NULL); /* read packet from socket */ if ((byte = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&fromaddr, &fromlen)) == -1) { LogRel(("recvfrom failed: %s\n", strerror(errno))); ++dropped_queries; return; } /* check for minimum dns packet length */ if (byte < 12) { LogRel(("query too short from %s\n", inet_ntoa(fromaddr.sin_addr))); ++dropped_queries; return; } /* allocate new request */ if ((req = calloc(1, sizeof(struct request))) == NULL) { LogRel(("calloc failed\n")); ++dropped_queries; return; } req->id = QUERYID; memcpy(&req->client, &fromaddr, sizeof(struct sockaddr_in)); memcpy(&req->clientid, &buf[0], 2); /* where is this query coming from? */ if (is_internal(pData, fromaddr.sin_addr)) { req->recursion = RD(buf); DPRINTF(("Internal query RD=%d\n", req->recursion)); } else { /* no recursion for foreigners */ req->recursion = 0; DPRINTF(("External query RD=%d\n", RD(buf))); } /* insert it into the hash table */ hash_add_request(pData, req); /* overwrite the original query id */ memcpy(&buf[0], &req->id, 2); if (req->recursion) { /* recursive queries timeout in 90s */ event_set(&req->timeout, -1, 0, timeout, req); tv.tv_sec=recursive_timeout; tv.tv_usec=0; event_add(&req->timeout, &tv); /* send it to our recursive server */ if ((byte = sendto(sock_answer, buf, (unsigned int)byte, 0, (struct sockaddr *)&recursive_addr, sizeof(struct sockaddr_in))) == -1) { LogRel(("sendto failed: %s\n", strerror(errno))); ++dropped_queries; return; } ++recursive_queries; } else { /* authoritative queries timeout in 10s */ event_set(&req->timeout, -1, 0, timeout, req); tv.tv_sec=authoritative_timeout; tv.tv_usec=0; event_add(&req->timeout, &tv); /* send it to our authoritative server */ if ((byte = sendto(sock_answer, buf, (unsigned int)byte, 0, (struct sockaddr *)&authoritative_addr, sizeof(struct sockaddr_in))) == -1) { LogRel(("sendto failed: %s\n", strerror(errno))); ++dropped_queries; return; } ++authoritative_queries; } #else /* VBOX */ AssertPtr(pData); /* m->m_data points to IP header */ #if 0 /* XXX: for some reason it make gdb ill, * it good to have this assert here with assumption above. */ M_ASSERTPKTHDR(m); #endif ip = mtod(m, struct ip *); udp = (struct udphdr *)(m->m_data + iphlen); fromaddr.sin_addr.s_addr = ip->ip_src.s_addr; fromaddr.sin_port = udp->uh_sport; fromaddr.sin_family = AF_INET; /* iphlen equals to lenght of ip header */ Assert(iphlen == sizeof(struct ip)); iphlen += sizeof (struct udphdr); byte = m->m_len - iphlen; buf = m->m_data + iphlen; /* check for minimum dns packet length */ if (byte < 12) { LogRel(("NAT: Query too short from %RTnaipv4\n", fromaddr.sin_addr)); ++dropped_queries; return; } req = so->so_timeout_arg; if (!req) { Assert(!so->so_timeout_arg); if ((req = RTMemAllocZ(sizeof(struct request) + byte)) == NULL) { LogRel(("NAT: calloc failed\n")); ++dropped_queries; return; } req->id = QUERYID; memcpy(&req->client, &fromaddr, sizeof(struct sockaddr_in)); memcpy(&req->clientid, &buf[0], 2); req->dns_server = TAILQ_LAST(&pData->pDnsList, dns_list_head); req->dnsgen = pData->dnsgen; if (req->dns_server == NULL) { RTMemFree(req); return; } retransmit = 0; so->so_timeout = timeout; so->so_timeout_arg = req; req->nbyte = byte; memcpy(req->byte, buf, byte); /* copying original request */ } else { if (req->dnsgen != pData->dnsgen) { /* XXX: Log2 */ LogRel(("NAT: dnsproxy: query: req %p dnsgen %u != %u on %R[natsock]\n", req, req->dnsgen, pData->dnsgen, so)); /* * XXX: TODO: this probably requires more cleanup. * Cf. XXX comment for sendto() failure below, but that * error leg is probably untested since ~never taken. */ ++dropped_queries; return; } retransmit = 1; } req->recursion = 0; DPRINTF(("External query RD=%d\n", RD(buf))); if (retransmit == 0) hash_add_request(pData, req); /* overwrite the original query id */ memcpy(&buf[0], &req->id, 2); /* let's slirp to care about expiration */ so->so_expire = curtime + recursive_timeout * 1000; memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; if (req->dns_server->de_addr.s_addr == (pData->special_addr.s_addr | RT_H2N_U32_C(CTL_ALIAS))) { /* undo loopback remapping done in get_dns_addr_domain() */ addr.sin_addr.s_addr = RT_N2H_U32_C(INADDR_LOOPBACK); } else { addr.sin_addr.s_addr = req->dns_server->de_addr.s_addr; } addr.sin_port = htons(53); /* send it to our authoritative server */ Log2(("NAT: request will be %ssent to %RTnaipv4 on %R[natsock]\n", retransmit ? "re" : "", addr.sin_addr, so)); byte = sendto(so->s, buf, (unsigned int)byte, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); if (byte == -1) { /* XXX: is it really enough? */ LogRel(("NAT: sendto failed: %s\n", strerror(errno))); ++dropped_queries; return; } so->so_state = SS_ISFCONNECTED; /* now it's selected */ Log2(("NAT: request was %ssent to %RTnaipv4 on %R[natsock]\n", retransmit ? "re" : "", addr.sin_addr, so)); ++authoritative_queries; # if 0 /* XXX: this stuff for _debugging_ only, * first enforce guest to send next request * and second for faster getting timeout callback * other option is adding couple entries in resolv.conf with * invalid nameservers. * * For testing purposes could be used * namebench -S -q 10000 -m random or -m chunk */ /* RTThreadSleep(3000); */ /* curtime += 300; */ # endif #endif /* VBOX */ }
int send_file(HTHREAD_PTR descr, char *filename) { WSADATA wsa_data; SOCKET data_socket = INVALID_SOCKET; struct sockaddr_in send_data_addr; HPACKET packet; HPARTITION partition; FILE *fp; int return_code; unsigned long at_location, read_amount, tries; unsigned char packet_count; char control_message[MAX_INPUT_LENGTH]; if(fopen_s(&fp, filename, "rb") > 0) { memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); control_message[0] = CONTROL_MESSAGE_NO_SUCH_FILE; return_code = send(descr->socket, control_message, (int)strlen(control_message), 0); return 1; } for(tries = 0; tries < CONTROL_MESSAGE_RECV_RETRIES; tries++) { memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); return_code = recv(descr->socket, control_message, MAX_INPUT_LENGTH-1, 0); if(return_code < 1) { printf("failed to recv command: %d\n", WSAGetLastError()); closesocket(data_socket); return 0; } if(control_message[0] == CONTROL_MESSAGE_OK_START_SENDING) break; } if(tries >= CONTROL_MESSAGE_RECV_RETRIES) { printf("No CONTROL_MESSAGE_OK_START_SENDING from %s\n", inet_ntoa(descr->address.sin_addr)); closesocket(data_socket); return 0; } WSAStartup(MAKEWORD(2,2), &wsa_data); data_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); send_data_addr.sin_family = AF_INET; send_data_addr.sin_port = htons(CONNECT_PORT_N);//descr->address.sin_port; send_data_addr.sin_addr = descr->address.sin_addr;//inet_addr("123.456.789.1"); packet.partition_id = 0; packet.reserved = 0; while(!feof(fp)) { memset(partition.packet_stats, 0, MAX_PARTITION_DIVISIONS+1); partition.actual_size = (unsigned long)fread(partition.data, 1, PARTITION_LENGTH_TOTAL, fp); packet_count = (unsigned char)ceil(partition.actual_size / PACKET_LENGTH_DATA); memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); sprintf_s(control_message, MAX_INPUT_LENGTH, " %u", partition.actual_size); control_message[0] = CONTROL_MESSAGE_SENDING_DATA; return_code = send(descr->socket, control_message, (int)strlen(control_message)+1, 0); if(return_code == SOCKET_ERROR) { printf("failed to send command: %d\n", WSAGetLastError()); closesocket(data_socket); return 0; } while(1) { for(packet.packet_id = 0; packet.packet_id < packet_count; packet.packet_id++) { if(partition.packet_stats[packet.packet_id] != 1) break; } if(packet.packet_id == packet_count) break; for(packet.packet_id = 0; packet.packet_id < packet_count; packet.packet_id++) { if(partition.packet_stats[packet.packet_id] != 1) { memset(packet.data, 0, sizeof(PARTITION_LENGTH_TOTAL)); at_location = packet.packet_id * PACKET_LENGTH_DATA; read_amount = at_location + PACKET_LENGTH_DATA < partition.actual_size ? PACKET_LENGTH_DATA : partition.actual_size - at_location; memcpy(packet.data, &partition.data[at_location], read_amount); packet.crc = compute_crc((const unsigned char *)packet.data, PACKET_LENGTH_DATA); return_code = sendto(data_socket, (char *)&packet, sizeof(packet), 0, (SOCKADDR *)&send_data_addr, sizeof(send_data_addr)); if(return_code == SOCKET_ERROR) { printf("failed to send command: %d\n", WSAGetLastError()); closesocket(data_socket); return 0; } Sleep(5); } } memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); control_message[0] = CONTROL_MESSAGE_PARTITION_SENT; return_code = send(descr->socket, control_message, (int)strlen(control_message)+1, 0); if(return_code == SOCKET_ERROR) { printf("failed to send command: %d\n", WSAGetLastError()); closesocket(data_socket); return 0; } for(tries = 0; tries < CONTROL_MESSAGE_RECV_RETRIES; tries++) { memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); return_code = recv(descr->socket, control_message, MAX_INPUT_LENGTH-1, 0); if(return_code < 1) { printf("failed to recv command: %d\n", WSAGetLastError()); closesocket(data_socket); return 0; } if(control_message[0] == CONTROL_MESSAGE_PARTITION_STATUS) { memset(partition.packet_stats, 0, MAX_PARTITION_DIVISIONS+1); memcpy(partition.packet_stats, &control_message[2], MAX_PARTITION_DIVISIONS); break; } } if(tries >= CONTROL_MESSAGE_RECV_RETRIES) { printf("No CONTROL_MESSAGE_PARTITION_STATUS from %s\n", inet_ntoa(descr->address.sin_addr)); closesocket(data_socket); return 0; } } packet.partition_id++; } fclose(fp); memset(control_message, 0, sizeof(MAX_INPUT_LENGTH)); control_message[0] = CONTROL_MESSAGE_ALL_DATA_SENT; return_code = send(descr->socket, control_message, (int)strlen(control_message)+1, 0); if(return_code == SOCKET_ERROR) { printf("failed to send command: %d\n", WSAGetLastError()); closesocket(data_socket); return 1; } closesocket(data_socket); return 1; }
int main(int argc, char **argv) { char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l; int c; u_char *buf; int packet_len = 0; struct ip *IP; struct udphdr *UDP; u_int32_t src = 0, dst = 0; banner(); if (argc < 3) usage(argv[0]); if ((l = libnet_init(LIBNET_RAW4, NULL, errbuf)) == NULL) { fprintf(stderr, "[!] libnet_init() failed: %s", errbuf); exit(-1); } if ((src = libnet_name2addr4(l, argv[1], LIBNET_RESOLVE)) == -1) { fprintf(stderr, "[!] Unresolved source address.\n"); exit(-1); } if ((dst = libnet_name2addr4(l, argv[2], LIBNET_RESOLVE)) == -1) { fprintf(stderr, "[!] Unresolved destination address.\n"); exit(-1); } if ((buf = malloc(IP_MAXPACKET)) == NULL) { perror("malloc"); exit(-1); } UDP = (struct udphdr *)(buf + LIBNET_IPV4_H); packet_len = LIBNET_IPV4_H + LIBNET_UDP_H + sizeof(pwnage) - 1; srand(time(NULL)); IP = (struct ip *) buf; IP->ip_v = 4; /* version 4 */ IP->ip_hl = 5; /* header length */ IP->ip_tos = 0; /* IP tos */ IP->ip_len = htons(packet_len); /* total length */ IP->ip_id = rand(); /* IP ID */ IP->ip_off = htons(0); /* fragmentation flags */ IP->ip_ttl = 64; /* time to live */ IP->ip_p = IPPROTO_UDP; /* transport protocol */ IP->ip_sum = 0; IP->ip_src.s_addr = src; IP->ip_dst.s_addr = dst; UDP->uh_sport = rand(); UDP->uh_dport = (argc > 3) ? htons((u_short)atoi(argv[3])) : htons(161); UDP->uh_ulen = htons(LIBNET_UDP_H + sizeof(pwnage) - 1); UDP->uh_sum = 0; memcpy(buf + LIBNET_IPV4_H + LIBNET_UDP_H, pwnage, sizeof(pwnage) - 1); libnet_do_checksum(l, (u_int8_t *)buf, IPPROTO_UDP, packet_len - LIBNET_IPV4_H); if ((c = libnet_write_raw_ipv4(l, buf, packet_len)) == -1) { fprintf(stderr, "[!] Write error: %s\n", libnet_geterror(l)); exit(-1); } printf("[+] Packet sent.\n"); libnet_destroy(l); free(buf); return (0); }
/** * Sets up a non-blocking socket */ static int socket_setup(struct server *s, struct server_cfg **servers) { int servers_num = 0; int i = 0; int ports_num = 0; // stat server conf num while (servers[servers_num++] != NULL); servers_num--; // stat distinct listen port num int *servers_port = (int *)malloc(sizeof(int) * servers_num); for(i = 0; i < servers_num; i++) { int listen_port = servers[i]->listen; if(in_int_array(servers_port, listen_port, ports_num) == -1) { servers_port[ports_num++] = listen_port; } } for(i = 0; i < ports_num; i++) { int reuse = 1; struct sockaddr_in addr; int fd, ret; memset(&addr, 0, sizeof(addr)); #if defined __BSD__ addr.sin_len = sizeof(struct sockaddr_in); #endif addr.sin_family = AF_INET; addr.sin_port = htons(servers_port[i]); addr.sin_addr.s_addr = INADDR_ANY; /* create socket */ fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (-1 == fd) { slog(s, LOG_ERROR, strerror(errno), 0); free(servers_port); return -1; } /* reuse address if we've bound to it before. */ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { slog(s, LOG_ERROR, strerror(errno), 0); free(servers_port); return -1; } /* set socket as non-blocking. */ ret = fcntl(fd, F_SETFD, O_NONBLOCK); if (0 != ret) { slog(s, LOG_ERROR, strerror(errno), 0); free(servers_port); return -1; } /* bind */ ret = bind(fd, (struct sockaddr*) &addr, sizeof(addr)); if (0 != ret) { slog(s, LOG_ERROR, "bind", 4); slog(s, LOG_ERROR, strerror(errno), 0); free(servers_port); return -1; } /* listen */ ret = listen(fd, SOMAXCONN); if (0 != ret) { slog(s, LOG_ERROR, strerror(errno), 0); free(servers_port); return -1; } /* set keepalive socket option to do with half connection */ int keep_alive = 1; setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *) &keep_alive, sizeof(keep_alive)); /* start http server */ struct event *ev = event_new(s->base, fd, EV_READ | EV_PERSIST, server_can_accept, (void*) s); ret = event_add(ev, NULL); if (ret < 0) { slog(s, LOG_ERROR, "Error calling event_add on socket", 0); free(servers_port); return -1; } } free(servers_port); return 0; }
static int parse_ipv6(struct ofpbuf *packet, struct flow *flow) { const struct ip6_hdr *nh; ovs_be32 tc_flow; int nexthdr; nh = ofpbuf_try_pull(packet, sizeof *nh); if (!nh) { return EINVAL; } nexthdr = nh->ip6_nxt; flow->ipv6_src = nh->ip6_src; flow->ipv6_dst = nh->ip6_dst; tc_flow = get_unaligned_be32(&nh->ip6_flow); flow->nw_tos = ntohl(tc_flow) >> 20; flow->ipv6_label = tc_flow & htonl(IPV6_LABEL_MASK); flow->nw_ttl = nh->ip6_hlim; flow->nw_proto = IPPROTO_NONE; while (1) { if ((nexthdr != IPPROTO_HOPOPTS) && (nexthdr != IPPROTO_ROUTING) && (nexthdr != IPPROTO_DSTOPTS) && (nexthdr != IPPROTO_AH) && (nexthdr != IPPROTO_FRAGMENT)) { /* It's either a terminal header (e.g., TCP, UDP) or one we * don't understand. In either case, we're done with the * packet, so use it to fill in 'nw_proto'. */ break; } /* We only verify that at least 8 bytes of the next header are * available, but many of these headers are longer. Ensure that * accesses within the extension header are within those first 8 * bytes. All extension headers are required to be at least 8 * bytes. */ if (packet->size < 8) { return EINVAL; } if ((nexthdr == IPPROTO_HOPOPTS) || (nexthdr == IPPROTO_ROUTING) || (nexthdr == IPPROTO_DSTOPTS)) { /* These headers, while different, have the fields we care about * in the same location and with the same interpretation. */ const struct ip6_ext *ext_hdr = packet->data; nexthdr = ext_hdr->ip6e_nxt; if (!ofpbuf_try_pull(packet, (ext_hdr->ip6e_len + 1) * 8)) { return EINVAL; } } else if (nexthdr == IPPROTO_AH) { /* A standard AH definition isn't available, but the fields * we care about are in the same location as the generic * option header--only the header length is calculated * differently. */ const struct ip6_ext *ext_hdr = packet->data; nexthdr = ext_hdr->ip6e_nxt; if (!ofpbuf_try_pull(packet, (ext_hdr->ip6e_len + 2) * 4)) { return EINVAL; } } else if (nexthdr == IPPROTO_FRAGMENT) { const struct ip6_frag *frag_hdr = packet->data; nexthdr = frag_hdr->ip6f_nxt; if (!ofpbuf_try_pull(packet, sizeof *frag_hdr)) { return EINVAL; } /* We only process the first fragment. */ if (frag_hdr->ip6f_offlg != htons(0)) { if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) == htons(0)) { flow->nw_frag = FLOW_NW_FRAG_ANY; } else { flow->nw_frag |= FLOW_NW_FRAG_LATER; nexthdr = IPPROTO_FRAGMENT; break; } } } } flow->nw_proto = nexthdr; return 0; }
/* * Receive a file. */ void tftp_recvfile(int fd, const char *name, const char *mode) { struct tftphdr *ap; struct tftphdr *dp; int n; volatile u_short block; volatile int size, firsttrip; volatile unsigned long amount; union sock_addr from; socklen_t fromlen; FILE *file; volatile int convert; /* true if converting crlf -> lf */ u_short dp_opcode, dp_block; startclock(); dp = w_init(); ap = (struct tftphdr *)ackbuf; convert = !strcmp(mode, "netascii"); file = fdopen(fd, convert ? "wt" : "wb"); block = 1; firsttrip = 1; amount = 0; bsd_signal(SIGALRM, timer); do { if (firsttrip) { size = makerequest(RRQ, name, ap, mode); firsttrip = 0; } else { ap->th_opcode = htons((u_short) ACK); ap->th_block = htons((u_short) block); size = 4; block++; } timeout = 0; (void)sigsetjmp(timeoutbuf, 1); send_ack: if (trace) tpacket("sent", ap, size); if (sendto(f, ackbuf, size, 0, &peeraddr.sa, SOCKLEN(&peeraddr)) != size) { alarm(0); perror("tftp: sendto"); goto abort; } write_behind(file, convert); for (;;) { alarm(rexmtval); do { fromlen = sizeof(from); n = recvfrom(f, dp, PKTSIZE, 0, &from.sa, &fromlen); } while (n <= 0); alarm(0); if (n < 0) { perror("tftp: recvfrom"); goto abort; } sa_set_port(&peeraddr, SOCKPORT(&from)); /* added */ if (trace) tpacket("received", dp, n); /* should verify client address */ dp_opcode = ntohs((u_short) dp->th_opcode); dp_block = ntohs((u_short) dp->th_block); if (dp_opcode == ERROR) { printf("Error code %d: %s\n", dp_block, dp->th_msg); goto abort; } if (dp_opcode == DATA) { int j; if (dp_block == block) { break; /* have next packet */ } /* On an error, try to synchronize * both sides. */ j = synchnet(f); if (j && trace) { printf("discarded %d packets\n", j); } if (dp_block == (block - 1)) { goto send_ack; /* resend ack */ } } } /* size = write(fd, dp->th_data, n - 4); */ size = writeit(file, &dp, n - 4, convert); if (size < 0) { nak(errno + 100, NULL); break; } amount += size; } while (size == SEGSIZE); abort: /* ok to ack, since user */ ap->th_opcode = htons((u_short) ACK); /* has seen err msg */ ap->th_block = htons((u_short) block); (void)sendto(f, ackbuf, 4, 0, (struct sockaddr *)&peeraddr, SOCKLEN(&peeraddr)); write_behind(file, convert); /* flush last buffer */ fclose(file); stopclock(); if (amount > 0) printstats("Received", amount); }
/* * Send the requested file. */ void tftp_sendfile(int fd, const char *name, const char *mode) { struct tftphdr *ap; /* data and ack packets */ struct tftphdr *dp; int n; volatile int is_request; volatile u_short block; volatile int size, convert; volatile off_t amount; union sock_addr from; socklen_t fromlen; FILE *file; u_short ap_opcode, ap_block; startclock(); /* start stat's clock */ dp = r_init(); /* reset fillbuf/read-ahead code */ ap = (struct tftphdr *)ackbuf; convert = !strcmp(mode, "netascii"); file = fdopen(fd, convert ? "rt" : "rb"); block = 0; is_request = 1; /* First packet is the actual WRQ */ amount = 0; bsd_signal(SIGALRM, timer); do { if (is_request) { size = makerequest(WRQ, name, dp, mode) - 4; } else { /* size = read(fd, dp->th_data, SEGSIZE); */ size = readit(file, &dp, convert); if (size < 0) { nak(errno + 100, NULL); break; } dp->th_opcode = htons((u_short) DATA); dp->th_block = htons((u_short) block); } timeout = 0; (void)sigsetjmp(timeoutbuf, 1); if (trace) tpacket("sent", dp, size + 4); n = sendto(f, dp, size + 4, 0, &peeraddr.sa, SOCKLEN(&peeraddr)); if (n != size + 4) { perror("tftp: sendto"); goto abort; } read_ahead(file, convert); for (;;) { alarm(rexmtval); do { fromlen = sizeof(from); n = recvfrom(f, ackbuf, sizeof(ackbuf), 0, &from.sa, &fromlen); } while (n <= 0); alarm(0); if (n < 0) { perror("tftp: recvfrom"); goto abort; } sa_set_port(&peeraddr, SOCKPORT(&from)); /* added */ if (trace) tpacket("received", ap, n); /* should verify packet came from server */ ap_opcode = ntohs((u_short) ap->th_opcode); ap_block = ntohs((u_short) ap->th_block); if (ap_opcode == ERROR) { printf("Error code %d: %s\n", ap_block, ap->th_msg); goto abort; } if (ap_opcode == ACK) { int j; if (ap_block == block) { break; } /* On an error, try to synchronize * both sides. */ j = synchnet(f); if (j && trace) { printf("discarded %d packets\n", j); } /* * RFC1129/RFC1350: We MUST NOT re-send the DATA * packet in response to an invalid ACK. Doing so * would cause the Sorcerer's Apprentice bug. */ } } if (!is_request) amount += size; is_request = 0; block++; } while (size == SEGSIZE || block == 1); abort: fclose(file); stopclock(); if (amount > 0) printstats("Sent", amount); }
// Start building up a packet to send to the remote host specific in ip and port // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port int UIPUDP::beginPacket(IPAddress ip, uint16_t port) { UIPEthernet.tick(); if (ip && port) { uip_ipaddr_t ripaddr; uip_ip_addr(&ripaddr, ip); #ifdef UIPETHERNET_DEBUG_UDP Serial.print("udp beginPacket, "); #endif if (_uip_udp_conn) { _uip_udp_conn->rport = htons(port); uip_ipaddr_copy(_uip_udp_conn->ripaddr, &ripaddr); } else { _uip_udp_conn = uip_udp_new(&ripaddr,htons(port)); if (_uip_udp_conn) { #ifdef UIPETHERNET_DEBUG_UDP Serial.print("new connection, "); #endif _uip_udp_conn->appstate.user = &appdata; } else { #ifdef UIPETHERNET_DEBUG_UDP Serial.println("failed to allocate new connection"); #endif return 0; } } #ifdef UIPETHERNET_DEBUG_UDP Serial.print("rip: "); Serial.print(ip); Serial.print(", port: "); Serial.println(port); #endif } if (_uip_udp_conn) { if (appdata.packet_out == NOBLOCK) { appdata.packet_out = UIPEthernet.network.allocBlock(UIP_UDP_MAXPACKETSIZE); appdata.out_pos = UIP_UDP_PHYH_LEN; if (appdata.packet_out != NOBLOCK) return 1; #ifdef UIPETHERNET_DEBUG_UDP else Serial.println("failed to allocate memory for packet"); #endif } #ifdef UIPETHERNET_DEBUG_UDP else Serial.println("previous packet on that connection not sent yet"); #endif } return 0; }
long tcp_connect(bmdnet_handler_ptr handler,char*host,long port) { long status; #ifndef _WIN32 char aux[256]; struct sockaddr_in serv_addr; struct hostent hostinfo_buf; struct hostent *hostinfo=&hostinfo_buf; long one = 1; int si_temp; /* to musi byc int - nie zmieniac !!!! */ #else struct addrinfo *result = NULL, hints; char * portstr=NULL; #endif if (host == NULL || port == 0 || port > 65535) { return(-1); } handler->s = (long)socket(AF_INET, SOCK_STREAM,IPPROTO_TCP); if (handler->s <= 0) return -1; #ifndef WIN32 if (setsockopt(handler->s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { return ERR(ERR_net, "Cannot set SO_REUSEADDR flag on socket", "LK"); } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons((short)port); if( gethostbyname_r(host, &hostinfo_buf, aux, sizeof(aux), &hostinfo, &si_temp) != 0 ) { PRINT_ERROR("gethostbyname_r failed.\n"); return(-1); } if (hostinfo==NULL) { PRINT_ERROR("Hostname not found.\n"); return(-1); } serv_addr.sin_addr=*(struct in_addr *)hostinfo->h_addr; status = connect(handler->s, (const struct sockaddr *)&serv_addr,sizeof(serv_addr)); if (status) { PRINT_ERROR("Cannot connect to host.\n"); return(-1); } #else ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; portstr = calloc(6,sizeof(char)); _itoa_s(port, portstr, 6,10); status = getaddrinfo(host, portstr, &hints, &result); if( status == WSAHOST_NOT_FOUND ) { BMD_FOK(BMD_ERR_NET_RESOLV); } else if( status != 0 ) { BMD_FOK(BMD_ERR_OP_FAILED); } if (result == NULL) { BMD_FOK(BMD_ERR_OP_FAILED); } status = connect(handler->s, result->ai_addr,(long)result->ai_addrlen); if (status) { PRINT_ERROR("Cannot connect to host.\n"); return(-1); } #endif return BMD_OK; };
long tcp_connect_socks_proxy(bmdnet_handler_ptr handler,char *host,long port) { long status; if( handler == NULL ) { BMD_FOK(BMD_ERR_PARAM1);}; if( host == NULL ) { BMD_FOK(BMD_ERR_PARAM2);}; status=tcp_connect(handler,handler->proxy_adr,handler->proxy_port); if( status != BMD_OK ) { PRINT_ERROR("Failed to connect with proxy at %s:%li\n",handler->proxy_adr,handler->proxy_port); BMD_FOK(BMD_ERR_NET_CONNECT); } if( handler->proxy_type == BMDNET_PROXY_SOCKS4 ) { socks4_request_t request_header; char complete_request[1024]; char *buffer=NULL; long response_code = 0; long length = 0; long request_header_size = 0; memset(complete_request,0,256); request_header.version=4; request_header.command=1; request_header.destport=htons((u_short)port); request_header.destaddr=inet_addr(host); request_header_size=sizeof(request_header); memmove(complete_request,(char *)(&request_header),request_header_size); if(handler->proxy_user) { length=(long)strlen((char *)handler->proxy_user); memmove(complete_request+request_header_size,(char *)handler->proxy_user,length); bmdnet_send(handler, complete_request,length+request_header_size+1); } else { bmdnet_send(handler,complete_request,request_header_size+1); } buffer=(char *)malloc(10000); memset(buffer,0,10000); bmdnet_recv(handler,buffer,1024); if((long)buffer[0]==0) { response_code=(long)buffer[1]; switch(response_code) { case 90: return 0; case 91: return -1; case 92: return -2; case 93: return -3; } } else { return -1; } } else if( handler->proxy_type == BMDNET_PROXY_SOCKS4A ) { socks4a_request_t request_header; char complete_request[1024]; char *buffer=NULL; long response_code = 0; long length = 0; long request_header_size = 0; memset(complete_request,0,256); request_header.version=4; request_header.command=1; request_header.destport=htons((u_short)port); request_header.destaddr=inet_addr("0.0.0.1"); request_header_size=sizeof(request_header); memmove(complete_request,(char *)(&request_header),request_header_size); if(handler->proxy_user) { length=(long)strlen((char *)handler->proxy_user); memmove(complete_request+request_header_size,(char *)handler->proxy_user,length); memmove(complete_request+request_header_size+length+1,host,strlen(host)); bmdnet_send(handler, complete_request,length+request_header_size+(long)strlen(host)+2); } else { memmove(complete_request+request_header_size+1,host,strlen(host)); bmdnet_send(handler,complete_request,request_header_size+(long)strlen(host)+2); } buffer=(char *)malloc(10000); memset(buffer,0,10000); bmdnet_recv(handler,buffer,1024); if((long)buffer[0]==0) { response_code=(long)buffer[1]; switch(response_code) { case 90: return 0; case 91: return -1; case 92: return -2; case 93: return -3; } } else { return -1; } } else if( handler->proxy_type == BMDNET_PROXY_SOCKS5 ) { long i; long ip_flag = 1; char *buffer = NULL; socks5_init_request_t init_request_header; socks5_request_t request_header; char complete_request[1024]; char initial_request[1024]; __int32 tmp1; __int16 tmp2; /* wysylanie inicjalnego requesta z deklaracja metod */ memset(initial_request,0,1024);init_request_header.version=0x05;init_request_header.nmethod=1; memmove(initial_request,(char *)(&init_request_header),sizeof(init_request_header)); if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC ) { initial_request[sizeof(init_request_header)]=0x02; } BMD_FOK_CHG(bmdnet_send(handler,initial_request,sizeof(init_request_header)+1), -1); buffer=(char *)malloc(1024); memset(buffer,0,1024); BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1); if( ((unsigned char)buffer[1]) == 0xFF) /* zadna metoda autoryzacji nie jest wspierana - patrz RFC */ { BMD_FOK(-1); } free(buffer);buffer=NULL; /* faza autoryzacji user/password */ if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC ) { buffer=(char *)malloc(1024); memset(buffer,0,1024); buffer[0]=0x01;buffer[1]=(char)strlen((char *)handler->proxy_user); memmove(buffer+2,handler->proxy_user,strlen(handler->proxy_user)); buffer[2+strlen(handler->proxy_user)]=(char)strlen((char *)handler->proxy_pass); memmove(buffer+3+strlen((char *)handler->proxy_user),(char *)handler->proxy_pass, strlen((char *)handler->proxy_pass)); BMD_FOK_CHG(bmdnet_send(handler,buffer,(long)strlen(buffer)),-1); memset(buffer,0,1024); BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1); if(buffer[1]!=0x00) { BMD_FOK(-1); } } memset(complete_request,0,256); request_header.ver=0x05;request_header.cmd=1;request_header.rsv=0x00; for(i=0;i<(long)strlen(host);i++) { if(isalpha(host[i])) /* jesli wystapi jakas litera uznaje ze to adres domenowy */ { ip_flag=0; break; } } if(ip_flag==1) { request_header.atyp=0x01; /* to jest IP */ } else { request_header.atyp=0x03; /* to jest domena */ } memmove(complete_request,(char *)(&request_header),sizeof(request_header)); if(ip_flag==1) { tmp1=inet_addr(host); } tmp2=htons((u_short)port); if(ip_flag==1) { memmove(complete_request+sizeof(request_header),&tmp1,4); memmove(complete_request+sizeof(request_header)+4,&tmp2,2); status=bmdnet_send(handler,complete_request,sizeof(request_header)+6); if( status < 0 ) { return -1; } } else { char *tmp=NULL; tmp=(char *)malloc(strlen(host)+3); tmp[0]=(char)strlen(host); memmove(tmp+1,host,strlen(host)); memmove(complete_request+sizeof(request_header),tmp,strlen(host)+1); memmove(complete_request+sizeof(request_header)+strlen(host)+1,&tmp2,2); BMD_FOK_CHG(bmdnet_send(handler,complete_request,sizeof(request_header)+ (long)strlen(host)+3),-1); free(tmp);tmp=NULL; } buffer=(char *)malloc(1024); memset(buffer,0,1024); BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1); if(buffer[1]==0x00) /* OK*/ return 0; /* jakis blad - nie interesuje nas jaki */ return -1; } else { PRINT_ERROR("Unsupported proxy_type\n"); BMD_FOK(BMD_ERR_UNIMPLEMENTED); } return BMD_OK; }
int main( int argc, char ** argv ) { if ( argc == 2 && strcmp(argv[1],"help\0") == 0) { fprintf( stderr, "%s", usage ); exit( -1 ); } else if(argc == 2 && (defaultPORT = isNumericAndValid(argv[1])) == -1) { fprintf( stderr, "%s", badInput ); exit( -1 ); } struct sigaction signalAction; signalAction.sa_handler = child; // Set the IP address and port for this server struct sockaddr_in serverIPAddress; memset( &serverIPAddress, 0, sizeof(serverIPAddress) ); serverIPAddress.sin_family = AF_INET; serverIPAddress.sin_addr.s_addr = INADDR_ANY; serverIPAddress.sin_port = htons((u_short) defaultPORT); // Allocate a socket int masterSocket = socket(PF_INET, SOCK_STREAM, 0); if( masterSocket < 0) { perror("socket"); exit( -1 ); } // Set socket options to reuse port. Otherwise we will // have to wait about 2 minutes before reusing the sae port number int optval = 1; int err = setsockopt(masterSocket, SOL_SOCKET, SO_REUSEADDR,(char *) &optval, sizeof( int ) ); // Bind the socket to the IP address and port int error = bind( masterSocket,(struct sockaddr *)&serverIPAddress,sizeof(serverIPAddress) ); if( error ) { perror("bind"); exit( -1 ); } // Put socket in listening mode and set the // size of the queue of unprocessed connections error = listen( masterSocket, QueueLength); if( error ) { perror("listen"); exit( -1 ); } //Enter into infinate loop, wait till death. createThreadForEachRequest( masterSocket ); }
static bool parse_icmpv6(struct ofpbuf *b, struct flow *flow) { const struct icmp6_hdr *icmp = pull_icmpv6(b); if (!icmp) { return false; } /* The ICMPv6 type and code fields use the 16-bit transport port * fields, so we need to store them in 16-bit network byte order. */ flow->tp_src = htons(icmp->icmp6_type); flow->tp_dst = htons(icmp->icmp6_code); if (icmp->icmp6_code == 0 && (icmp->icmp6_type == ND_NEIGHBOR_SOLICIT || icmp->icmp6_type == ND_NEIGHBOR_ADVERT)) { const struct in6_addr *nd_target; nd_target = ofpbuf_try_pull(b, sizeof *nd_target); if (!nd_target) { return false; } flow->nd_target = *nd_target; while (b->size >= 8) { /* The minimum size of an option is 8 bytes, which also is * the size of Ethernet link-layer options. */ const struct nd_opt_hdr *nd_opt = b->data; int opt_len = nd_opt->nd_opt_len * 8; if (!opt_len || opt_len > b->size) { goto invalid; } /* Store the link layer address if the appropriate option is * provided. It is considered an error if the same link * layer option is specified twice. */ if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LINKADDR && opt_len == 8) { if (eth_addr_is_zero(flow->arp_sha)) { memcpy(flow->arp_sha, nd_opt + 1, ETH_ADDR_LEN); } else { goto invalid; } } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LINKADDR && opt_len == 8) { if (eth_addr_is_zero(flow->arp_tha)) { memcpy(flow->arp_tha, nd_opt + 1, ETH_ADDR_LEN); } else { goto invalid; } } if (!ofpbuf_try_pull(b, opt_len)) { goto invalid; } } } return true; invalid: memset(&flow->nd_target, 0, sizeof(flow->nd_target)); memset(flow->arp_sha, 0, sizeof(flow->arp_sha)); memset(flow->arp_tha, 0, sizeof(flow->arp_tha)); return false; }
int main(int argc, char *const *argv) { struct sockaddr_in bindaddr; socklen_t addrlen; const char *isDA; const char *proxyReg; int connfd; int lfd; const int on = 1; detachfromtty(); openlog("slpd", LOG_PID, LOG_DAEMON); do_args(argc, argv); /* If slpd has been configured to run as a DA, start it and exit */ isDA = SLPGetProperty("net.slp.isDA"); proxyReg = SLPGetProperty("net.slp.serializedRegURL"); if ((isDA && (strcasecmp(isDA, "true") == 0)) || proxyReg) { run_slpd(); return (1); } if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { syslog(LOG_ERR, "socket failed: %s", strerror(errno)); cleanup_and_exit(1); } (void) setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)); (void) memset((void *)&bindaddr, 0, sizeof (bindaddr)); bindaddr.sin_family = AF_INET; bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); bindaddr.sin_port = htons(427); if (bind(lfd, (const struct sockaddr *)&bindaddr, sizeof (bindaddr)) < 0) { syslog(LOG_ERR, "bind failed: %s", strerror(errno)); cleanup_and_exit(1); } if (listen(lfd, 1) < 0) { syslog(LOG_ERR, "listen failed: %s", strerror(errno)); cleanup_and_exit(1); } addrlen = sizeof (bindaddr); if ((connfd = accept(lfd, (struct sockaddr *)&bindaddr, &addrlen)) < 0) { syslog(LOG_ERR, "accept failed: %s", strerror(errno)); cleanup_and_exit(1); } (void) close(lfd); (void) dup2(connfd, 0); (void) close(connfd); (void) dup2(0, 1); (void) dup2(0, 2); run_slpd(); return (1); }
/* Initializes l3 and higher 'flow' members from 'packet' * * This should be called by or after flow_extract() * * Initializes 'packet' header pointers as follows: * * - packet->l4 to just past the IPv4 header, if one is present and has a * correct length, and otherwise NULL. * * - packet->l7 to just past the TCP or UDP or ICMP header, if one is * present and has a correct length, and otherwise NULL. */ void flow_extract_l3_onwards(struct ofpbuf *packet, struct flow *flow, ovs_be16 dl_type) { struct ofpbuf b; ofpbuf_use_const(&b, packet->l3, packet->size - (size_t)((char *)packet->l3 - (char *)packet->l2)); /* Network layer. */ if (dl_type == htons(ETH_TYPE_IP)) { const struct ip_header *nh = pull_ip(&b); if (nh) { packet->l4 = b.data; flow->nw_src = get_unaligned_be32(&nh->ip_src); flow->nw_dst = get_unaligned_be32(&nh->ip_dst); flow->nw_proto = nh->ip_proto; flow->nw_tos = nh->ip_tos; if (IP_IS_FRAGMENT(nh->ip_frag_off)) { flow->nw_frag = FLOW_NW_FRAG_ANY; if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) { flow->nw_frag |= FLOW_NW_FRAG_LATER; } } flow->nw_ttl = nh->ip_ttl; if (!(nh->ip_frag_off & htons(IP_FRAG_OFF_MASK))) { if (flow->nw_proto == IPPROTO_TCP) { parse_tcp(packet, &b, flow); } else if (flow->nw_proto == IPPROTO_UDP) { parse_udp(packet, &b, flow); } else if (flow->nw_proto == IPPROTO_ICMP) { const struct icmp_header *icmp = pull_icmp(&b); if (icmp) { flow->tp_src = htons(icmp->icmp_type); flow->tp_dst = htons(icmp->icmp_code); packet->l7 = b.data; } } } } } else if (dl_type == htons(ETH_TYPE_IPV6)) { if (parse_ipv6(&b, flow)) { return; } packet->l4 = b.data; if (flow->nw_proto == IPPROTO_TCP) { parse_tcp(packet, &b, flow); } else if (flow->nw_proto == IPPROTO_UDP) { parse_udp(packet, &b, flow); } else if (flow->nw_proto == IPPROTO_ICMPV6) { if (parse_icmpv6(&b, flow)) { packet->l7 = b.data; } } } else if (dl_type == htons(ETH_TYPE_ARP) || dl_type == htons(ETH_TYPE_RARP)) { const struct arp_eth_header *arp = pull_arp(&b); if (arp && arp->ar_hrd == htons(1) && arp->ar_pro == htons(ETH_TYPE_IP) && arp->ar_hln == ETH_ADDR_LEN && arp->ar_pln == 4) { /* We only match on the lower 8 bits of the opcode. */ if (ntohs(arp->ar_op) <= 0xff) { flow->nw_proto = ntohs(arp->ar_op); } flow->nw_src = arp->ar_spa; flow->nw_dst = arp->ar_tpa; memcpy(flow->arp_sha, arp->ar_sha, ETH_ADDR_LEN); memcpy(flow->arp_tha, arp->ar_tha, ETH_ADDR_LEN); } } }
status_t usb_disk_operation(device_lun *lun, uint8 operation, uint8 opLength, uint32 logicalBlockAddress, uint16 transferLength, void *data, size_t *dataLength, bool directionIn, err_act *_action) { TRACE("operation: lun: %u; op: %u; oplen: %u; lba: %" B_PRIu32 "; tlen: %u; data: %p; dlen: %p (%lu); in: %c\n", lun->logical_unit_number, operation, opLength, logicalBlockAddress, transferLength, data, dataLength, dataLength ? *dataLength : 0, directionIn ? 'y' : 'n'); disk_device *device = lun->device; command_block_wrapper command; command.signature = CBW_SIGNATURE; command.tag = device->current_tag++; command.data_transfer_length = (dataLength != NULL ? *dataLength : 0); command.flags = (directionIn ? CBW_DATA_INPUT : CBW_DATA_OUTPUT); command.lun = lun->logical_unit_number; command.command_block_length = device->is_atapi ? ATAPI_COMMAND_LENGTH : opLength; memset(command.command_block, 0, sizeof(command.command_block)); switch (opLength) { case 6: { scsi_command_6 *commandBlock = (scsi_command_6 *)command.command_block; commandBlock->operation = operation; commandBlock->lun = lun->logical_unit_number << 5; commandBlock->allocation_length = (uint8)transferLength; if (operation == SCSI_MODE_SENSE_6) { // we hijack the lba argument to transport the desired page commandBlock->reserved[1] = (uint8)logicalBlockAddress; } break; } case 10: { scsi_command_10 *commandBlock = (scsi_command_10 *)command.command_block; commandBlock->operation = operation; commandBlock->lun_flags = lun->logical_unit_number << 5; commandBlock->logical_block_address = htonl(logicalBlockAddress); commandBlock->transfer_length = htons(transferLength); break; } default: TRACE_ALWAYS("unsupported operation length %d\n", opLength); return B_BAD_VALUE; } status_t result = usb_disk_transfer_data(device, false, &command, sizeof(command_block_wrapper)); if (result != B_OK) return result; if (device->status != B_OK || device->actual_length != sizeof(command_block_wrapper)) { // sending the command block wrapper failed TRACE_ALWAYS("sending the command block wrapper failed: %s\n", strerror(device->status)); usb_disk_reset_recovery(device); return B_ERROR; } size_t transferedData = 0; if (data != NULL && dataLength != NULL && *dataLength > 0) { // we have data to transfer in a data stage result = usb_disk_transfer_data(device, directionIn, data, *dataLength); if (result != B_OK) return result; transferedData = device->actual_length; if (device->status != B_OK || transferedData != *dataLength) { // sending or receiving of the data failed if (device->status == B_DEV_STALLED) { TRACE("stall while transfering data\n"); gUSBModule->clear_feature(directionIn ? device->bulk_in : device->bulk_out, USB_FEATURE_ENDPOINT_HALT); } else { TRACE_ALWAYS("sending or receiving of the data failed: %s\n", strerror(device->status)); usb_disk_reset_recovery(device); return B_ERROR; } } } command_status_wrapper status; result = usb_disk_receive_csw(device, &status); if (result != B_OK) { // in case of a stall or error clear the stall and try again gUSBModule->clear_feature(device->bulk_in, USB_FEATURE_ENDPOINT_HALT); result = usb_disk_receive_csw(device, &status); } if (result != B_OK) { TRACE_ALWAYS("receiving the command status wrapper failed: %s\n", strerror(result)); usb_disk_reset_recovery(device); return result; } if (status.signature != CSW_SIGNATURE || status.tag != command.tag) { // the command status wrapper is not valid TRACE_ALWAYS("command status wrapper is not valid: %#" B_PRIx32 "\n", status.signature); usb_disk_reset_recovery(device); return B_ERROR; } switch (status.status) { case CSW_STATUS_COMMAND_PASSED: case CSW_STATUS_COMMAND_FAILED: { // The residue from "status.data_residue" is not maintained // correctly by some devices, so calculate it instead. uint32 residue = command.data_transfer_length - transferedData; if (dataLength != NULL) { *dataLength -= residue; if (transferedData < *dataLength) { TRACE_ALWAYS("less data transfered than indicated: %" B_PRIuSIZE " vs. %" B_PRIuSIZE "\n", transferedData, *dataLength); *dataLength = transferedData; } } if (status.status == CSW_STATUS_COMMAND_PASSED) { // the operation is complete and has succeeded return B_OK; } else { if (operation == SCSI_REQUEST_SENSE_6) return B_ERROR; // the operation is complete but has failed at the SCSI level if (operation != SCSI_TEST_UNIT_READY_6) { TRACE_ALWAYS("operation %#" B_PRIx8 " failed at the SCSI level\n", operation); } result = usb_disk_request_sense(lun, _action); return result == B_OK ? B_ERROR : result; } } case CSW_STATUS_PHASE_ERROR: { // a protocol or device error occured TRACE_ALWAYS("phase error in operation %#" B_PRIx8 "\n", operation); usb_disk_reset_recovery(device); return B_ERROR; } default: { // command status wrapper is not meaningful TRACE_ALWAYS("command status wrapper has invalid status\n"); usb_disk_reset_recovery(device); return B_ERROR; } } }
/* Puts into 'b' a packet that flow_extract() would parse as having the given * 'flow'. * * (This is useful only for testing, obviously, and the packet isn't really * valid. It hasn't got some checksums filled in, for one, and lots of fields * are just zeroed.) */ void flow_compose(struct ofpbuf *b, const struct flow *flow) { eth_compose(b, flow->dl_dst, flow->dl_src, ntohs(flow->dl_type), 0); if (flow->dl_type == htons(FLOW_DL_TYPE_NONE)) { struct eth_header *eth = b->l2; eth->eth_type = htons(b->size); return; } if (flow->vlan_tci & htons(VLAN_CFI)) { eth_push_vlan(b, flow->vlan_tci); } if (flow->dl_type == htons(ETH_TYPE_IP)) { struct ip_header *ip; b->l3 = ip = ofpbuf_put_zeros(b, sizeof *ip); ip->ip_ihl_ver = IP_IHL_VER(5, 4); ip->ip_tos = flow->nw_tos; ip->ip_ttl = flow->nw_ttl; ip->ip_proto = flow->nw_proto; ip->ip_src = flow->nw_src; ip->ip_dst = flow->nw_dst; if (flow->nw_frag & FLOW_NW_FRAG_ANY) { ip->ip_frag_off |= htons(IP_MORE_FRAGMENTS); if (flow->nw_frag & FLOW_NW_FRAG_LATER) { ip->ip_frag_off |= htons(100); } } if (!(flow->nw_frag & FLOW_NW_FRAG_ANY) || !(flow->nw_frag & FLOW_NW_FRAG_LATER)) { if (flow->nw_proto == IPPROTO_TCP) { struct tcp_header *tcp; b->l4 = tcp = ofpbuf_put_zeros(b, sizeof *tcp); tcp->tcp_src = flow->tp_src; tcp->tcp_dst = flow->tp_dst; tcp->tcp_ctl = TCP_CTL(0, 5); } else if (flow->nw_proto == IPPROTO_UDP) { struct udp_header *udp; b->l4 = udp = ofpbuf_put_zeros(b, sizeof *udp); udp->udp_src = flow->tp_src; udp->udp_dst = flow->tp_dst; } else if (flow->nw_proto == IPPROTO_ICMP) { struct icmp_header *icmp; b->l4 = icmp = ofpbuf_put_zeros(b, sizeof *icmp); icmp->icmp_type = ntohs(flow->tp_src); icmp->icmp_code = ntohs(flow->tp_dst); icmp->icmp_csum = csum(icmp, ICMP_HEADER_LEN); } } ip = b->l3; ip->ip_tot_len = htons((uint8_t *) b->data + b->size - (uint8_t *) b->l3); ip->ip_csum = csum(ip, sizeof *ip); } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) { /* XXX */ } else if (flow->dl_type == htons(ETH_TYPE_ARP) || flow->dl_type == htons(ETH_TYPE_RARP)) { struct arp_eth_header *arp; b->l3 = arp = ofpbuf_put_zeros(b, sizeof *arp); arp->ar_hrd = htons(1); arp->ar_pro = htons(ETH_TYPE_IP); arp->ar_hln = ETH_ADDR_LEN; arp->ar_pln = 4; arp->ar_op = htons(flow->nw_proto); if (flow->nw_proto == ARP_OP_REQUEST || flow->nw_proto == ARP_OP_REPLY) { arp->ar_spa = flow->nw_src; arp->ar_tpa = flow->nw_dst; memcpy(arp->ar_sha, flow->arp_sha, ETH_ADDR_LEN); memcpy(arp->ar_tha, flow->arp_tha, ETH_ADDR_LEN); } } }
int main(int argc, char *argv[]) { /* Make sure we received two arguments, a hostname and a port number. */ if (argc < 2) { printf("Simple TCP/IP uptime server.\n"); printf("Usage: %s <port>\n", argv[0]); return 1; } port = atoi(argv[1]); /* Create the listener socket. This socket will queue incoming connections. */ listener = socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if (listener < 0) { printf("Unable to create a listener socket: %s\n", strerror(errno)); return 1; } /* Now bind the listener to a local address. This uses the same sockaddr_in structure as connect. */ sa_len = sizeof(sa); memset(&sa, 0, sa_len); sa.sin_family = AF_INET; sa.sin_port = htons(port); sa.sin_addr.s_addr = htonl(INADDR_ANY); /* Listen on all interfaces. */ if (bind(listener, &sa, sa_len) < 0) { printf("Unable to bind to port %i: %s\n", port, strerror(errno)); return 1; } /* Let the networking system know we're accepting connections on this socket. Ask for a connection queue of five clients. (If more than five clients try to connect before we call accept, some will be denied.) */ if (listen(listener, 5) < 0) { printf("Unable to listen: %s\n", strerror(errno)); return 1; } /* Ready! Now accept connections until the user presses Control-C. */ signal(SIGINT, signal_handler); for (;;) { char sendbuf[1024]; int sent, length; FILE *uptime; client = accept(listener, &sa, &sa_len); if (client < 0) { printf("Unable to accept: %s\n", strerror(errno)); close(listener); return 1; } /* We now have a live client. Print information about it and then send something over the wire. */ inet_ntop(AF_INET, &sa.sin_addr, dotted_ip, 15); printf("Received connection from %s.\n", dotted_ip); /* Use popen to retrieve the output of the uptime command. This is a bit of a hack, but it's portable and it works fairly well. popen opens a pipe to a program (that is, it executes the program and redirects its I/O to a file handle). */ uptime = popen("/usr/bin/uptime", "r"); if (uptime == NULL) { strcpy(sendbuf, "Unable to read system's uptime.\n"); } else { sendbuf[0] = '\0'; fgets(sendbuf, 1023, uptime); pclose(uptime); } /* Figure out how much data we need to send. */ length = strlen(sendbuf); sent = 0; /* Repeatedly call write until the entire buffer is sent. */ while (sent < length) { int amt; amt = write(client, sendbuf+sent, length-sent); if (amt <= 0) { /* Zero-byte writes are OK if they are caused by signals (EINTR). Otherwise they mean the socket has been closed. */ if (errno == EINTR) continue; else { printf("Send error: %s\n", strerror(errno)); break; } } /* Update our position by the number of bytes that were sent. */ sent += amt; } close(client); } return 0; }
int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, struct ipv6_txoptions *opt) { struct net *net = sock_net(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; int tclass = 0; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (skb2 == NULL) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } kfree_skb(skb); skb = skb2; skb_set_owner_w(skb, sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) { tclass = np->tclass; hlimit = np->hop_limit; } if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); *(__be32 *)hdr = htonl(0x60000000 | (tclass << 20)) | fl6->flowlabel; hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; ipv6_addr_copy(&hdr->saddr, &fl6->saddr); ipv6_addr_copy(&hdr->daddr, first_hop); skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); } if (net_ratelimit()) printk(KERN_DEBUG "IPv6: sending pkt_too_big to self\n"); skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; }
tango_connection_t *tango_create(const char *share, const char* username, const char *password) { static unsigned short next_mid = 0; tango_connection_t *tango_connection_ptr = malloc(sizeof(tango_connection_t)); if (tango_connection_ptr == NULL) { _tango_set_error(tango_connection_ptr, kTangoErrorGeneralSystemError, "tango_create(): Unable to malloc mem.\n"); error("tango_create(): Unable to malloc mem.\n"); return NULL; } // Null it memset(tango_connection_ptr, 0, sizeof(tango_connection_t)); // Create a socket int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock < 0) { _tango_set_error(tango_connection_ptr, kTangoErrorGeneralSystemError, "tango_create(): Failed to create socket().\n"); debug("tango_create(): Failed to create socket().\n"); goto bailout; } tango_connection_ptr->socket = sock; struct sockaddr_in sock_addr; // Parse share-string if (strncmp(share, "\\\\", 2) != 0 || strlen(share) < 3) { _tango_set_error(tango_connection_ptr, kTangoErrorParameterInvalid, "tango_create(): Passed parameter not a valid share.\n"); debug("tango_create(): Passed parameter not a valid share.\n"); goto bailout; } const char *begin_ptr = share + 2; char *end_ptr = strchr(begin_ptr, '\\'); // Form: \\hostname\share char hostname[64]; assert(strlen(begin_ptr) < 64 && "Hostname longer than 64 bytes"); strncpy(hostname, begin_ptr, end_ptr - begin_ptr); hostname[end_ptr - begin_ptr] = '\0'; sock_addr.sin_addr = address_for_host(hostname); int sin_addr_set = sock_addr.sin_addr.s_addr != INADDR_NONE; if (!sin_addr_set) { _tango_set_error(tango_connection_ptr, kTangoErrorParameterInvalid, "tango_create(): Invalid share.\n"); error("tango_create(): Passed parameter not a valid share or contains no valid hostname/IP.\n"); goto bailout; } char *slash_ptr = strchr(share + 2, '\\'); slash_ptr = strchr(slash_ptr + 1, '\\'); if (slash_ptr != NULL) { // Format: \\hostname\share\subfolder unsigned int slash_idx = slash_ptr - share; strncpy(tango_connection_ptr->share, share, slash_idx); tango_connection_ptr->share[slash_idx + 1] = '\0'; } else { // Format: \\hostname\share slash_ptr = strchr(share + 2, '\\'); strcpy(tango_connection_ptr->share, slash_ptr+1); } // Configure port and connection-type sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(445); // Default-port for SMB over TCP/IP without NetBios tango_connection_ptr->sock_addr = sock_addr; // Set our Ids tango_connection_ptr->pid = 0x1234; tango_connection_ptr->mid = next_mid++; // Store username and password strcpy(tango_connection_ptr->user_name, username); strcpy(tango_connection_ptr->user_password, password); return tango_connection_ptr; bailout: free(tango_connection_ptr); return NULL; }
int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info*)skb_dst(skb); struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; __be32 frag_id = 0; int ptr, offset = 0, err=0; u8 *prevhdr, nexthdr = 0; struct net *net = dev_net(skb_dst(skb)->dev); hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (!skb->local_df && skb->len > mtu) { skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } mtu -= hlen + sizeof(struct frag_hdr); if (skb_has_frag_list(skb)) { int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb)) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < hlen) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); return -ENOMEM; } __skb_pull(skb, hlen); fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); ipv6_select_ident(fh, &rt->rt6i_dst.addr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); frag_id = fh->identification; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next != NULL) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(skb); if(!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); dst_release(&rt->dst); return 0; } while (frag) { skb = frag->next; kfree_skb(frag); frag = skb; } IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); dst_release(&rt->dst); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ *prevhdr = NEXTHDR_FRAGMENT; /* * Keep copying data until we run out. */ while(left > 0) { len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* * Allocate buffer. */ if ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) { NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n"); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev)); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; if (!frag_id) { ipv6_select_ident(fh, &rt->rt6i_dst.addr); frag_id = fh->identification; } else fh->identification = frag_id; /* * Copy a block of the IP datagram. */ if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len)) BUG(); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); kfree_skb(skb); return err; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; }
/* main -- dnsproxy main function */ int main(int argc, char *argv[]) { int ch; struct passwd *pw = NULL; struct sockaddr_in addr; struct event evq, eva; const char *config = "/etc/dnsproxy.conf"; int daemonize = 0; /* Process commandline arguments */ while ((ch = getopt(argc, argv, "c:dhV")) != -1) { switch (ch) { case 'c': config = optarg; break; case 'd': daemonize = 1; break; case 'V': fprintf(stderr, PACKAGE_STRING "\n"); exit(0); /* FALLTHROUGH */ case 'h': default: fprintf(stderr, "usage: dnsproxy [-c file] [-dhV]\n" \ "\t-c file Read configuration from file\n" \ "\t-d Detach and run as a daemon\n" \ "\t-h This help text\n" \ "\t-V Show version information\n"); exit(1); } } /* Parse configuration and check required parameters */ if (!parse(config)) fatal("unable to parse configuration"); if (!authoritative || !recursive) fatal("No authoritative or recursive server defined"); if (!listenat) listenat = strdup("0.0.0.0"); /* Create and bind query socket */ if ((sock_query = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal("unable to create socket: %s", strerror(errno)); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_addr.s_addr = inet_addr(listenat); addr.sin_port = htons(port); addr.sin_family = AF_INET; if (bind(sock_query, (struct sockaddr *)&addr, sizeof(addr)) != 0) fatal("unable to bind socket: %s", strerror(errno)); /* Create and bind answer socket */ if ((sock_answer = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal("unable to create socket: %s", strerror(errno)); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; if (bind(sock_answer, (struct sockaddr *)&addr, sizeof(addr)) != 0) fatal("unable to bind socket: %s", strerror(errno)); /* Fill sockaddr_in structs for both servers */ memset(&authoritative_addr, 0, sizeof(struct sockaddr_in)); authoritative_addr.sin_addr.s_addr = inet_addr(authoritative); authoritative_addr.sin_port = htons(authoritative_port); authoritative_addr.sin_family = AF_INET; memset(&recursive_addr, 0, sizeof(struct sockaddr_in)); recursive_addr.sin_addr.s_addr = inet_addr(recursive); recursive_addr.sin_port = htons(recursive_port); recursive_addr.sin_family = AF_INET; /* Daemonize if requested and switch to syslog */ if (daemonize) { if (daemon(0, 0) == -1) fatal("unable to daemonize"); log_syslog("dnsproxy"); } /* Find less privileged user */ if (user) { pw = getpwnam(user); if (!pw) fatal("unable to find user %s", user); } /* Do a chroot if requested */ if (chrootdir) { if (chdir(chrootdir) || chroot(chrootdir)) fatal("unable to chroot to %s", chrootdir); chdir("/"); } /* Drop privileges */ if (user) { if (setgroups(1, &pw->pw_gid) < 0) fatal("setgroups: %s", strerror(errno)); #if defined(HAVE_SETRESGID) if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) < 0) fatal("setresgid: %s", strerror(errno)); #elif defined(HAVE_SETREGID) if (setregid(pw->pw_gid, pw->pw_gid) < 0) fatal("setregid: %s", strerror(errno)); #else if (setegid(pw->pw_gid) < 0) fatal("setegid: %s", strerror(errno)); if (setgid(pw->pw_gid) < 0) fatal("setgid: %s", strerror(errno)); #endif #if defined(HAVE_SETRESUID) if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) < 0) fatal("setresuid: %s", strerror(errno)); #elif defined(HAVE_SETREUID) if (setreuid(pw->pw_uid, pw->pw_uid) < 0) fatal("setreuid: %s", strerror(errno)); #else if (seteuid(pw->pw_uid) < 0) fatal("seteuid: %s", strerror(errno)); if (setuid(pw->pw_uid) < 0) fatal("setuid: %s", strerror(errno)); #endif } /* Init event handling */ event_init(); event_set(&evq, sock_query, EV_READ, do_query, &evq); event_add(&evq, NULL); event_set(&eva, sock_answer, EV_READ, do_answer, &eva); event_add(&eva, NULL); /* Zero counters and start statistics timer */ statistics_start(); /* Take care of signals */ if (signal(SIGINT, signal_handler) == SIG_ERR) fatal("unable to mask signal SIGINT: %s", strerror(errno)); if (signal(SIGTERM, signal_handler) == SIG_ERR) fatal("unable to mask signal SIGTERM: %s", strerror(errno)); if (signal(SIGHUP, SIG_IGN) == SIG_ERR) fatal("unable to mask signal SIGHUP: %s", strerror(errno)); event_sigcb = signal_event; /* Start libevent main loop */ event_dispatch(); return 0; }
static int ip6_finish_output2(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; int res; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) && ((mroute6_socket(dev_net(dev), skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, ip6_dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST, skb->len); } rcu_read_lock(); if (dst->hh) { res = neigh_hh_output(dst->hh, skb); rcu_read_unlock(); return res; } else { neigh = dst_get_neighbour(dst); if (neigh) { res = neigh->output(skb); rcu_read_unlock(); return res; } rcu_read_unlock(); } IP6_INC_STATS_BH(dev_net(dst->dev), ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; }
// ./server_PFS <port number> <private key> <certificate of server> <CA sert> int main(int argc, char const *argv[]) { int i, j; // ssl setup SSL_CTX *ctx; SSL *ssl[MAX]; SSL_METHOD *meth; // Load encryption & hashing algorithms for the SSL program SSL_library_init(); // Load the error strings for SSL & CRYPTO APIs SSL_load_error_strings(); // Create a SSL_METHOD structure (choose a SSL/TLS protocol version) meth = SSLv3_method(); // Create a SSL_CTX structure ctx = SSL_CTX_new(meth); if(!ctx) { ERR_print_errors_fp(stderr); exit(1); } // Load the server certificate into the SSL_CTX structure if(SSL_CTX_use_certificate_file(ctx, argv[3], SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(1); } // Load the private-key corresponding to the server certificate if(SSL_CTX_use_PrivateKey_file(ctx, argv[2], SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(1); } // Check if the server certificate and private-key matches if(!SSL_CTX_check_private_key(ctx)) { printf("Private key does not match the certificate public key\n"); exit(1); } // Load the RSA CA certificate into the SSL_CTX structure if(!SSL_CTX_load_verify_locations(ctx, argv[4], NULL)) { ERR_print_errors_fp(stderr); exit(1); } // Set to require peer (client) certificate verification SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); // Set the verification depth to 1 SSL_CTX_set_verify_depth(ctx, 1); struct sockaddr_in servAddr; int servSock; // for listening int connectSocks[MAX]; // for connection NameList clients; clients.num = 0; // init connectSocks for(i = 0; i < MAX; i++){ connectSocks[i] = -1; } // setup sockaddr bzero(&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = INADDR_ANY; servAddr.sin_port = htons(atoi(argv[1])); // create socket servSock = socket(AF_INET, SOCK_STREAM, 0); if(servSock < 0){ perror("socket creation"); exit(1); } // bind socket with server port if(bind(servSock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0){ perror("bind socket"); exit(1); } // set to non-block mode if(fcntl(servSock, F_SETFL, O_NDELAY) < 0){ perror("set non-block"); exit(1); } // listen on the port if(listen(servSock, MAX) < 0){ perror("listen on the port"); exit(1); } int nbytes; int flag; Packet sendFlieListPacket, sendCmdPacket; Packet recvPacket; sendCmdPacket.type = 0; recvPacket.type = 100; strcpy(sendCmdPacket.cmd, "Client existed"); sendFlieListPacket.type = 1; sendFlieListPacket.fileList.num = 0; while(1) { // accept the client connection and set non-block for(i = 0; i < MAX; i++) { if(connectSocks[i] == -1) { connectSocks[i] = accept(servSock, NULL, sizeof(struct sockaddr_in)); if(connectSocks[i] > 0) { printf("Client connected via TCP\n"); ssl[i] = SSL_new(ctx); // Assign the socket into the SSL structure SSL_set_fd(ssl[i], connectSocks[i]); // Perform SSL Handshake on the SSL server nbytes = SSL_accept(ssl[i]); // printf("%d\n", nbytes); if(nbytes == 1) { printf("Client connected via SSL\n"); } if(nbytes <= 0) { SSL_get_error(ssl[i], nbytes); } // set connectSock to non-block if(fcntl(connectSocks[i], F_SETFL, O_NDELAY) < 0) { perror("Cannot set connect sock non-block"); } } } } // recv file list or command from client, recv type 0 for command, 1 for file list for(i = 0; i < MAX; i++) { if(connectSocks[i] > 0) { nbytes = SSL_read(ssl[i], &recvPacket, sizeof(Packet)); if(nbytes > 0) { // if recv new file list if(recvPacket.type == 1) { // check if already client name already existed flag = isExisted(&clients, recvPacket.fileList.owner); // new client if(flag == 0) { printf("Receive new file list from client %s\n", recvPacket.fileList.owner); mergeFileList(&sendFlieListPacket.fileList, &recvPacket.fileList); for(j = 0; j < MAX; j++) { if(connectSocks[j] > 0) { nbytes = SSL_write(ssl[j], &sendFlieListPacket, sizeof(Packet)); if(nbytes < 0) { perror("Push updated file list"); } if(nbytes > 0) { printf("Push master file list\n"); } } } } // client already existed if(flag == 1) { nbytes = SSL_write(ssl[i], &sendCmdPacket, sizeof(Packet)); if(nbytes < 0) { perror("Send command"); } } } // if receive command from client if(recvPacket.type == 0) { printf("Client: %s\n", recvPacket.cmd); // ls command if(strcmp(recvPacket.cmd, "ls") == 0) { nbytes = SSL_write(ssl[i], &sendFlieListPacket, sizeof(Packet)); if(nbytes < 0) { perror("Response to ls command"); } } // exit command if(strcmp(recvPacket.cmd, "exit") == 0) { // deregister client and push the updated file list deregisterClient(&clients, &sendFlieListPacket.fileList, recvPacket.fileList.owner); // close this socket SSL_shutdown(ssl[i]); close(connectSocks[i]); SSL_free(ssl[i]); connectSocks[i] = -1; for(j = 0; j < MAX; j++) { if(connectSocks[j] > 0) { nbytes = SSL_write(ssl[j], &sendFlieListPacket, sizeof(Packet)); if(nbytes < 0) { perror("Push updated file list"); } if(nbytes > 0) { printf("Push the updated file list after one client exit\n"); } } } } } } } } } return 0; }
/* static uint32 de32(uint8 *morp) { return(morp[0]|(morp[1]<<8)|(morp[2]<<16)|(morp[3]<<24)); } */ int FCEUD_NetworkConnect(void) { struct sockaddr_in sockin; /* I want to play with fighting robots. */ struct hostent *phostentb; unsigned long hadr; int TSocket; int netdivisor; if(!netplayhost) return(0); if( (TSocket=socket(AF_INET,SOCK_STREAM,0))==-1) { puts("Error creating stream socket."); FCEUD_NetworkClose(); return(0); } int tcpopt = 1; if(setsockopt(TSocket, SOL_TCP, TCP_NODELAY, &tcpopt, sizeof(int))) puts("Nodelay fail"); memset(&sockin,0,sizeof(sockin)); sockin.sin_family=AF_INET; hadr=inet_addr(netplayhost); if(hadr!=INADDR_NONE) sockin.sin_addr.s_addr=hadr; else { puts("*** Looking up host name..."); if(!(phostentb=gethostbyname((const char *)netplayhost))) { puts("Error getting host network information."); close(TSocket); FCEUD_NetworkClose(); return(0); } memcpy(&sockin.sin_addr,phostentb->h_addr,phostentb->h_length); } sockin.sin_port=htons(tport); puts("*** Connecting to remote host..."); if(connect(TSocket,(struct sockaddr *)&sockin,sizeof(sockin))==-1) { puts("Error connecting to remote host."); close(TSocket); FCEUD_NetworkClose(); return(0); } Socket=TSocket; puts("*** Sending initialization data to server..."); { uint8 *sendbuf; uint8 buf[5]; uint32 sblen; sblen = 4 + 16 + 16 + 64 + 1 + (netplaynick?strlen(netplaynick):0); sendbuf = malloc(sblen); memset(sendbuf, 0, sblen); en32(sendbuf, sblen - 4); if(netgamekey) { struct md5_context md5; uint8 md5out[16]; md5_starts(&md5); md5_update(&md5, CurGame->MD5, 16); md5_update(&md5, netgamekey, strlen(netgamekey)); md5_finish(&md5, md5out); memcpy(sendbuf + 4, md5out, 16); } else memcpy(sendbuf + 4, CurGame->MD5, 16); if(netpassword) { struct md5_context md5; uint8 md5out[16]; md5_starts(&md5); md5_update(&md5, netpassword, strlen(netpassword)); md5_finish(&md5, md5out); memcpy(sendbuf + 4 + 16, md5out, 16); } memset(sendbuf + 4 + 16 + 16, 0, 64); sendbuf[4 + 16 + 16 + 64] = netlocalplayers; if(netplaynick) memcpy(sendbuf + 4 + 16 + 16 + 64 + 1,netplaynick,strlen(netplaynick)); send(Socket, sendbuf, sblen, 0); free(sendbuf); recv(Socket, buf, 1, MSG_WAITALL); netdivisor = buf[0]; } puts("*** Connection established."); FCEUDnetplay = 1; FCEUI_NetplayStart(netlocalplayers, netdivisor); return(1); }
int ip_main(int argc, char *argv[]) { struct ip_hdr *ip; struct addr addr; u_char *p, buf[IP_LEN_MAX]; /* XXX */ char *name, *value; int c, len; srand(time(NULL)); ip = (struct ip_hdr *)buf; ip->ip_hl = 5; ip->ip_v = 4; ip->ip_tos = 0; ip->ip_id = rand() & 0xffff; ip->ip_off = 0; ip->ip_ttl = IP_TTL_MAX; ip->ip_p = rand() & 0xff; ip->ip_sum = 0; ip->ip_src = rand(); ip->ip_dst = rand(); for (c = 1; c + 1 < argc; c += 2) { name = argv[c]; value = argv[c + 1]; if (strcmp(name, "tos") == 0) ip->ip_tos = atoi(value); else if (strcmp(name, "id") == 0) ip->ip_id = ntohs(atoi(value)); else if (strcmp(name, "off") == 0) { if (off_aton(value, &ip->ip_off) < 0) ip_usage(); } else if (strcmp(name, "ttl") == 0) ip->ip_ttl = atoi(value); else if (strcmp(name, "proto") == 0) { if (proto_aton(value, &ip->ip_p) < 0) ip_usage(); } else if (strcmp(name, "src") == 0) { if (addr_aton(value, &addr) < 0) ip_usage(); ip->ip_src = addr.addr_ip; } else if (strcmp(name, "dst") == 0) { if (addr_aton(value, &addr) < 0) ip_usage(); ip->ip_dst = addr.addr_ip; } else ip_usage(); } argc -= c; argv += c; if (argc != 0) ip_usage(); if (isatty(STDIN_FILENO)) errx(1, "can't read IP payload from tty"); p = buf + IP_HDR_LEN; len = sizeof(buf) - (p - buf); while ((c = read(STDIN_FILENO, p, len)) > 0) { p += c; len -= c; } len = p - buf; ip->ip_len = htons(len); ip_checksum(buf, len); if (write(STDOUT_FILENO, buf, len) != len) err(1, "write"); return (0); }
int main(int argc, char **argv) { int force = 0, lsock, csock, one = 0, jeden = 1, local_port; int detach = 1, sa_len, conn_limit = 0, optc; char *username = NULL, *bind_host = NULL; struct sockaddr *sa; struct sockaddr_in laddr, caddr; struct sockaddr_in6 laddr6; unsigned int caddrlen = sizeof(caddr); struct passwd *pw = NULL; while ((optc = getopt(argc, argv, "1dv46fHs:l:I:i:hu:m:L:A:p:")) != -1) { switch (optc) { case '1': one = 1; break; case 'd': detach = 0; break; case 'v': verbose = 1; break; case '4': break; case '6': remote_hint = AF_INET; local_hint = AF_INET6; break; case 's': source_host = xstrdup(optarg); break; case 'l': bind_host = xstrdup(optarg); break; case 'r': force = 1; break; case 'i': ircpass = xstrdup(optarg); clear_argv(argv[optind - 1]); break; case 'I': ircsendpass = xstrdup(optarg); clear_argv(argv[optind - 1]); break; case 'h': hexdump = 1; break; case 'u': username = xstrdup(optarg); break; case 'm': map_file = xstrdup(optarg); break; case 'L': conn_limit = atoi(optarg); break; case 'p': pid_file = xstrdup(optarg); break; case 'H': hint_optional = 1; break; default: return 1; } } if (hexdump) verbose = 1; if (verbose) detach = 0; if (detach) verbose = 0; if (argc - optind < 2) { usage(argv[0]); exit(1); } if (username && !(pw = getpwnam(username))) { fprintf(stderr, "%s: unknown user %s\n", argv[0], username); exit(1); } if (map_file) map_read(); local_port = atoi(argv[optind++]); remote_host = argv[optind++]; remote_port = (argc == optind) ? local_port : atoi(argv[optind]); debug("resolving %s\n", remote_host); if (!(sa = resolve_host(remote_host, remote_hint)) && !force) { fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host); exit(1); } free(sa); sa = NULL; if (bind_host) { debug("resolving %s\n", bind_host); if (!(sa = resolve_host(bind_host, local_hint))) { fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host); exit(1); } } debug("local: %s,%d; ", (bind_host) ? bind_host : "default", local_port); debug("remote: %s,%d; ", remote_host, remote_port); if (map_file) debug("source: mapped\n"); else debug("source: %s\n", (source_host) ? source_host : "default"); if (local_hint == AF_INET) { lsock = socket(PF_INET, SOCK_STREAM, 0); memset(&laddr, 0, (sa_len = sizeof(laddr))); laddr.sin_family = AF_INET; laddr.sin_port = htons(local_port); if (sa) { memcpy(&laddr.sin_addr, &((struct sockaddr_in*) sa)->sin_addr, sizeof(struct in_addr)); free(sa); } sa = (struct sockaddr*) &laddr; } else { lsock = socket(PF_INET6, SOCK_STREAM, 0); memset(&laddr6, 0, (sa_len = sizeof(laddr6))); laddr6.sin6_family = AF_INET6; laddr6.sin6_port = htons(local_port); if (sa) { memcpy(&laddr6.sin6_addr, &((struct sockaddr_in6*) sa)->sin6_addr, sizeof(struct in6_addr)); free(sa); } sa = (struct sockaddr*) &laddr6; } if (setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &jeden, sizeof(jeden)) == -1) { perror("setsockopt"); exit(1); } if (bind(lsock, sa, sa_len)) { perror("bind"); exit(1); } if (listen(lsock, 100)) { perror("listen"); exit(1); } if (detach) { int i, ret; signal(SIGHUP, sighup); for (i = 0; i < 3; i++) close(i); ret = fork(); if (ret == -1) { perror("fork"); exit(1); } if (ret) exit(0); } if (pid_file) { FILE *f = fopen(pid_file, "w"); if (!f) debug("warning: cannot write to pidfile (%s)\n", strerror(errno)); else { fprintf(f, "%d", getpid()); fclose(f); } } if (username && ((setgid(pw->pw_gid) == -1) || (setuid(pw->pw_uid) == -1))) { perror("setuid/setgid"); exit(1); } setsid(); signal(SIGCHLD, sigchld); signal(SIGTERM, sigterm); signal(SIGINT, sigterm); signal(SIGHUP, sighup); for (;;) { int ret; fd_set rds; FD_ZERO(&rds); FD_SET(lsock, &rds); if (select(lsock + 1, &rds, NULL, NULL, NULL) == -1) { if (errno == EINTR) continue; perror("select"); break; } if ((csock = accept(lsock, (struct sockaddr*) &caddr, &caddrlen)) == -1) { perror("accept"); break; } inet_ntop(caddr.sin_family, (caddr.sin_family == AF_INET) ? &caddr.sin_addr : (void*) &(((struct sockaddr_in6*)&caddr)->sin6_addr), remote, sizeof(remote)); debug("<%d> connection from %s,%d", csock, remote, ntohs(caddr.sin_port)); if (conn_limit && (conn_count >= conn_limit)) { debug(" -- rejected due to limit.\n"); shutdown(csock, 2); close(csock); continue; } if (conn_limit) { conn_count++; debug(" (no. %d)", conn_count); } fflush(stdout); if ((ret = fork()) == -1) { debug(" -- fork() failed.\n"); shutdown(csock, 2); close(csock); continue; } if (!ret) { signal(SIGHUP, SIG_IGN); close(lsock); debug("\n"); make_tunnel(csock, remote); debug("<%d> connection closed\n", csock); exit(0); } close(csock); if (one) { shutdown(lsock, 2); close(lsock); exit(0); } } close(lsock); exit(1); }