void IpqLoop() { int status; struct pcap_pkthdr PHdr; unsigned char buf[PKT_BUFSIZE]; static ipq_packet_msg_t *m; #ifdef DEBUG_GIDS printf("Reading Packets from ipq handle \n"); #endif while(1) { ResetIV(); status = ipq_read(ipqh, buf, PKT_BUFSIZE, 1000000); if (status < 0) { ipq_perror("IpqLoop: "); } /* man ipq_read tells us that when a timeout is specified * ipq_read will return 0 when it is interupted. */ else if(status == 0) { /* Do the signal check. If we don't do this we will * evaluate the signal only when we receive an actual * packet. We don't want to depend on this. */ sig_check(); } else { switch(ipq_message_type(buf)) { case NLMSG_ERROR: fprintf(stderr, "Received error message %d\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: m = ipq_get_packet(buf); g_m = m; #ifdef DEBUG_INLINE printf("%02X:%02X:%02X:%02X:%02X:%02X\n", m->hw_addr[0], m->hw_addr[1], m->hw_addr[2], m->hw_addr[3], m->hw_addr[4], m->hw_addr[5]); #endif TranslateToPcap(m, &PHdr); PcapProcessPacket(NULL, &PHdr, (u_char *)m->payload); HandlePacket(m); break; } /* switch */ } /* if - else */ } /* while() */ }
void IpqLoop() { int status; struct pcap_pkthdr PHdr; unsigned char buf[PKT_BUFSIZE]; static ipq_packet_msg_t *m; #ifdef DEBUG_GIDS printf("Reading Packets from ipq handle \n"); #endif while(1) { ResetIV(); status = ipq_read(ipqh, buf, PKT_BUFSIZE, 0); if (status < 0) { ipq_perror("IpqLoop: "); } else { switch(ipq_message_type(buf)) { case NLMSG_ERROR: fprintf(stderr, "Received error message %d\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: m = ipq_get_packet(buf); g_m = m; #ifdef DEBUG_INLINE printf("%02X:%02X:%02X:%02X:%02X:%02X\n", m->hw_addr[0], m->hw_addr[1], m->hw_addr[2], m->hw_addr[3], m->hw_addr[4], m->hw_addr[5]); #endif TranslateToPcap(m, &PHdr); PcapProcessPacket(NULL, &PHdr, (u_char *)m->payload); HandlePacket(m); break; } /* switch */ } /* if - else */ } /* while() */ }
int main(int argc, char **argv) { int status; unsigned char buf[BUFSIZE]; struct ipq_handle *h; h = ipq_create_handle(0, PF_INET); if (!h) die(h); status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE); if (status < 0) die(h); do { status = ipq_read(h, buf, BUFSIZE, 0); if (status < 0) die(h); switch (ipq_message_type(buf)) { case NLMSG_ERROR: fprintf(stderr, "Received error message %d\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: ipq_packet_msg_t *m = ipq_get_packet(buf); struct iphdr *ip = (struct iphdr*) m->payload; struct tcphdr *tcp = (struct tcphdr*) (m->payload + (4 * ip->ihl)); int port = htons(tcp->dest); status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); if (status < 0) die(h); break; default: fprintf(stderr, "Unknown message type!\n"); break; } } while (1); ipq_destroy_handle(h); return 0; }
int main(void) { int status; unsigned char buf[BUFSIZE]; packet_list_t *element; ipq_packet_msg_t *pmsg; delay_init(); pthread_t thread; pthread_create(&thread, NULL, _pkg_reinject, NULL); do { /* read packets from buffer */ status = ipq_read(h, buf, BUFSIZE, 0); if (status > 0) { switch (ipq_message_type(buf)) { case NLMSG_ERROR: printf("Received error message %d\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: { /* adding packet to pool */ ipq_packet_msg_t *m = ipq_get_packet(buf); pmsg = (ipq_packet_msg_t*)malloc(sizeof(ipq_packet_msg_t) + m->data_len); memcpy(pmsg, m, sizeof(ipq_packet_msg_t) + m->data_len); element = (packet_list_t *)malloc(sizeof(packet_list_t)); element->pmsg = pmsg; list_add_tail(&(element->list), &pkg_list); count_packet++; break; } default: printf("Unknown message type!\n"); break; } } else printf("ipq_read error return: %s\n",ipq_errstr()); } while (1); return 0; }
static int ipq_daq_acquire ( void* handle, int cnt, DAQ_Analysis_Func_t callback, void* user) { IpqImpl* impl = (IpqImpl*)handle; int n = 0; DAQ_PktHdr_t hdr; // If cnt is <= 0, don't limit the packets acquired. However, // impl->count = 0 has a special meaning, so interpret accordingly. impl->count = (cnt == 0) ? -1 : cnt; hdr.device_index = 0; hdr.flags = 0; while ( impl->count < 0 || n < impl->count ) { int ipqt, status = ipq_read( impl->ipqh, impl->buf, MSG_BUF_SIZE, impl->timeout); if ( status <= 0 ) { if ( status < 0 ) { DPE(impl->error, "%s: ipq_read=%d error %s", __FUNCTION__, status, ipq_errstr()); return DAQ_ERROR; } return 0; } ipqt = ipq_message_type(impl->buf); if ( ipqt == IPQM_PACKET ) { DAQ_Verdict verdict; ipq_packet_msg_t* ipqm = ipq_get_packet(impl->buf); SetPktHdr(impl, ipqm, &hdr); impl->stats.hw_packets_received++; if ( impl->fcode.bf_insns && sfbpf_filter(impl->fcode.bf_insns, ipqm->payload, hdr.caplen, hdr.caplen) == 0 ) { verdict = DAQ_VERDICT_PASS; impl->stats.packets_filtered++; } else { verdict = callback(user, &hdr, (uint8_t*)ipqm->payload); impl->stats.verdicts[verdict]++; impl->stats.packets_received++; } if ( impl->passive ) verdict = DAQ_VERDICT_PASS; switch ( verdict ) { case DAQ_VERDICT_BLOCK: case DAQ_VERDICT_BLACKLIST: status = ipq_set_verdict( impl->ipqh, ipqm->packet_id, NF_DROP, 0, NULL); break; case DAQ_VERDICT_REPLACE: status = ipq_set_verdict( impl->ipqh, ipqm->packet_id, NF_ACCEPT, hdr.pktlen, ipqm->payload); break; case DAQ_VERDICT_PASS: case DAQ_VERDICT_WHITELIST: case DAQ_VERDICT_IGNORE: default: status = ipq_set_verdict( impl->ipqh, ipqm->packet_id, NF_ACCEPT, 0, NULL); break; } if ( status < 0 ) { DPE(impl->error, "%s: ipq_set_verdict=%d error %s", __FUNCTION__, status, ipq_errstr()); return DAQ_ERROR; } n++; } else { // NLMSG_ERROR is supposed to be the only other valid type status = ipq_get_msgerr(impl->buf); DPE(impl->error, "%s: ipq_message_type=%d error=%d %s", __FUNCTION__, ipqt, status, ipq_errstr()); // ipq_message_type=2 error=1 Timeout // keep looping upon timeout or other errors } } return 0; }
int main(int argc, const char ** argv) { static u8 buf[LTP_MAX_BUF_SIZE]; struct ipq_handle *h = ipq_create_handle(0, NFPROTO_IPV4); if (!h) { LTP_ERROR_LOG("ipq_create_handle failed\n"); goto error1; } int ret = ipq_set_mode(h, IPQ_COPY_PACKET, LTP_MAX_BUF_SIZE); if (-1 == ret) { LTP_ERROR_LOG("ipq_set_mode failed\n"); goto error2; } register_exit_signal_handler(); while (!g_ltp_daemon_exit) { ret = ipq_read(h, buf, LTP_MAX_BUF_SIZE, 0); if (ret < 0) { LTP_ERROR_LOG("ipq_read failed\n"); goto error2; } ret = ipq_message_type(buf); if (likely(IPQM_PACKET == ret)) { LTP_DEBUG_LOG("Get one packet\n"); ipq_packet_msg_t *pkt = ipq_get_packet(buf); if (likely(pkt)) { if (LTP_OK != ltp_ipq_rcv(pkt)) { // Need not the error handler LTP_ERROR_LOG("ltp_ipq_rcv failed\n"); } ret = ipq_set_verdict(h, pkt->packet_id, NF_DROP, pkt->data_len, pkt->payload); if (-1 == ret) { LTP_ERROR_LOG("ipq_set_verdict failed\n"); goto error2; } } else { LTP_ERROR_LOG("ipq_get_packet failed\n"); goto error2; } } else if (NLMSG_ERROR == ret) { LTP_ERROR_LOG("Recevie error msg(%d)\n", ipq_get_msgerr(buf)); goto error2; } else { LTP_ERROR_LOG("Unknown type\n"); goto error2; } } ipq_destroy_handle(h); return LTP_OK; error2: ipq_destroy_handle(h); h = NULL; error1: return LTP_ERR; }
void *processing(void *t){ packet_ctx *ctx; int status; do{ /********************************************* * process쓰레드 들이 동시에 큐에 달라 붙어서 같은 자료를 처리 할수 있다. * 이 경우 어느 한쪽에서 메시지를 처리하고 메모리를 해제하면 나머지 쪽에서 문제가 생길수 있다. * 그래서 큐에서 하나의 쓰레드에만 값을 넘겨 줘야 한다. **************************************************/ pthread_mutex_lock(&queueLock);/*{{{*/ if(ReadyQueue.currentSize>0){ ctx = safe_dequeue(&ReadyQueue); pthread_mutex_unlock(&queueLock); } else{ pthread_mutex_unlock(&queueLock); continue; } /*}}}*/ //에러 처리 if(ctx==NULL) continue;/*{{{*/ dlog(0,"processing\n"); if (status < 0){ die(ctx->h); } /*}}}*/ switch (ipq_message_type(ctx->buf)) { //에러 처리 case NLMSG_ERROR: dlog(0, "Received error message %d\n", ipq_get_msgerr(ctx->buf)); break; case IPQM_PACKET: { /********************** *초기 변수 설정 * *************************/ ipq_packet_msg_t *m = ipq_get_packet(ctx->buf);/*{{{*/ struct tcphdr *tcp=NULL; struct iphdr *ip=NULL; unsigned char *packet = NULL; unsigned char *tcpPayload=NULL; module_prototype module= NULL; int result=0; GListInfo *moduleList; sin_packet_info *packetInfo = malloc(sizeof(sin_packet_info)); memset(packetInfo,0,sizeof(sin_packet_info)); dump_ipq(m);/*}}}*/ if(m->data_len > sizeof(struct iphdr)){ packet = (unsigned char *)m + sizeof(ipq_packet_msg_t);//sizeof(*m) } ip =(struct iphdr *) packet; if(ip->protocol != 6){ //6 is TCP protocol number ipq_set_verdict(ctx->h,m->packet_id,NF_ACCEPT,0,NULL); } tcp =(struct tcphdr *) packet + sizeof(struct iphdr); dump_ip((struct iphdr *)packet); dump((char *)tcp,240); /*********************************** packetInfo 설정 ***********************************/ if(strcmp(m->outdev_name,"eth0")==0){ packetInfo->direction = C2OUT; }else if(strcmp(m->indev_name,"eth0")==0){ packetInfo->direction = OUT2C; } packetInfo->verdicted = 0; packetInfo->modified=0; packetInfo->action =SIN_ACCEPT; /************************ 분류기 ************************/ /* while(0){ char bound=-1; gpointer n; if(bound==C2O){//만일 패킷이 클라이언트에서 외부로 나가는 경우이면 n = tree_find(&BWList, ip->daddr, NULL); if(n != NULL){ cond *data = (cond *)n; if(data->type==DENY){ if(data->action == CONNECTION_CLOSE){ sessionManager(ctx->h,m->packet_id,CONNECTION_CLOSE); continue;// 다음 패킷 처리 } } if(data->type==ALLOW){ if(data->action == CONNECTION_ALLOW){ sessionManager(ctx->h,m->packet_id,CONNECTION_ALLOW); continue;// 다음 패킷 처리 } } } } } */ /********************** * run modules ************************/ glist_rewind(&ModuleList); while((module=(module_prototype)glist_next(&ModuleList))!=NULL){ result = (*module)(ctx->h,m,(const char*)tcp,240); /********** *허용이 아닌 경우 중단으로 해야 한다. *이유는 ACCEPT이지만 다른 종류의 메시지를 보내야 하는 경우도 있기 때문이다. *다만 이 경우에 어떻게 하는게 좋을지 아직 모르겠다. ***********/ if(result == NF_DROP) break; } /********************* * 위에서 처리 한 결과대로 처리한다. * verdict는 한번만 호출되어야 하는것 같다. ***********************/ /******************** 윈도우 사이즈 조절 *******************/ if(result==NF_ACCEPT && ip->protocol == 6){ uint16_t win; #if __BYTE_ORDER == __LITTLE_ENDIAN win = ntohs(tcp->window); if(win>MAXIMUM_WINDOW_SIZE){ tcp->window =htons(MAXIMUM_WINDOW_SIZE); packetInfo->modified=1; //패킷을 수정 했으니 이것을 verdict 하도록 수정해야한다. } #elif __BYTE_ORDER == __BIG_ENDIAN if(win>MAXIMUM_WINDOW_SIZE) { tcp->window = MAXIMUM_WINDOW_SIZE; packetInfo->modified=1; //패킷을 수정 했으니 이것을 verdict 하도록 수정해야한다. #endif } if( packetInfo->modified == 0){ status = ipq_set_verdict(ctx->h, m->packet_id,result, 0, NULL); }else{ /******************* 패킷 수정됐으니 체크섬 재계산-_- *******************/ status = ipq_set_verdict(ctx->h, m->packet_id,result, 0,NULL); } if (status < 0) die(ctx->h); break; } default: fprintf(stderr, "Unknown message type!\n"); break; } } while (1); ipq_destroy_handle(ctx->h); return 0; }
int main(int argc, char **argv) { int status; char str[100]; char input[2]; long interval = 0; int i = 0; struct tw_pkt* tmp = NULL; pthread_t p; h = ipq_create_handle(0, PF_INET); status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE); if(status < 0){ die(); } memset(str, 0, 100); memset(input, 0, 2); pre.tv_sec = now.tv_sec = 0; pre.tv_usec = now.tv_usec = 0; my_pkt_head.count = 0; my_pkt_head.head = my_pkt_head.end = NULL; printf("input a string\n"); fgets(str, 100, stdin); // memcpy(str, argv[1], 100); encode(str, 100); input[0] = 1; connect_to_kernel(input); printf("start to send information...\n"); do{ struct tw_pkt* tmp = malloc(sizeof(struct tw_pkt)); memset(tmp->buf, 0, BUFSIZE); tmp->pre = tmp->next = NULL; status = ipq_read(h, tmp->buf, BUFSIZE, 0); if(status < 0){ die(); } switch (ipq_message_type(tmp->buf)) { case NLMSG_ERROR:{ fprintf(stderr, "Received error message %d ", ipq_get_msgerr(tmp->buf)); break; } case IPQM_PACKET:{ ipq_packet_msg_t *m = ipq_get_packet(tmp->buf); printf("%ld packet_id rcv \n", m->packet_id); enqueue(tmp); i++; if(i == 2){ pthread_create(&p, NULL, tw_send, NULL); } break; } default:{ fprintf(stderr, "Unknown message type! "); break; } } } while (1); input[0] = 2; connect_to_kernel(input); ipq_destroy_handle(h); return 0; }
ip_noise_arbitrator_packet_logic_t * main_init_module( ip_noise_arbitrator_iface_t * * iface_ptr ) #endif { #ifndef __KERNEL__ int status; unsigned char message[IP_NOISE_MESSAGE_BUFSIZE]; struct ipq_handle * h; ip_noise_messages_queue_t * packets_to_arbitrate_queue; #endif int terminate = 0; ip_noise_decide_what_to_do_with_packets_thread_context_t * arbitrator_context; #ifndef __KERNEL__ pthread_t decide_what_to_with_packets_thread; #endif ip_noise_release_packets_thread_context_t * release_packets_context; #ifndef __KERNEL__ pthread_t release_packets_thread; #endif #ifndef __KERNEL__ int check; #endif ip_noise_delayer_t * delayer; ip_noise_arbitrator_data_t * data, * * data_ptr; ip_noise_flags_t flags; ip_noise_arbitrator_iface_t * arb_iface; #ifndef __KERNEL__ pthread_t arb_iface_thread; #endif ip_noise_arbitrator_switcher_t * arb_switcher; #ifndef __KERNEL__ pthread_t arb_switcher_thread; #endif #ifdef __KERNEL__ ip_noise_arbitrator_packet_logic_t * packet_logic; #endif printf("IP-Noise Simulator\n"); printf("Written by Shlomi Fish & Roy Glasberg and supervised by Lavy Libman\n"); printf("The Technion - Israel Institute of Technolgy\n"); printf("(c) 2001\n"); #ifndef __KERNEL__ h = ipq_create_handle(0, PF_INET); if (h == NULL) { die(h); } status = ipq_set_mode(h, IPQ_COPY_PACKET, sizeof(message)); if (status < 0) { die(h); } #endif #ifndef __KERNEL__ packets_to_arbitrate_queue = ip_noise_messages_queue_alloc(); #endif delayer = ip_noise_delayer_alloc( ip_noise_delayer_release_function, #ifndef __KERNEL__ (void *)h #else NULL #endif ); release_packets_context = malloc(sizeof(ip_noise_release_packets_thread_context_t)); release_packets_context->delayer = delayer; release_packets_context->terminate = &terminate; #ifndef __KERNEL__ check = pthread_create( &release_packets_thread, NULL, release_packets_thread_func, (void *)release_packets_context ); if (check != 0) { fprintf(stderr, "Could not create the release packets thread!\n"); exit(-1); } #endif data = ip_noise_arbitrator_data_alloc(); data_ptr = malloc(sizeof(*data_ptr)); *data_ptr = data; flags.reinit_switcher = 1; arb_switcher = ip_noise_arbitrator_switcher_alloc(data_ptr, &flags, &terminate); #ifndef __KERNEL__ check = pthread_create( &arb_switcher_thread, NULL, arb_switcher_thread_func, (void *)arb_switcher ); if (check != 0) { fprintf(stderr, "Could not create the arbitrator switcher thread!\n"); exit(-1); } #endif arb_iface = ip_noise_arbitrator_iface_alloc(data_ptr, arb_switcher, &flags); #ifdef __KERNEL__ /* * We assign arb_iface to iface_ptr so it can later be de-allocated * inside the module ip_queue.c. * * */ *iface_ptr = arb_iface; #endif #ifndef __KERNEL__ check = pthread_create( &arb_iface_thread, NULL, arb_iface_thread_func, (void *)arb_iface ); if (check != 0) { fprintf(stderr, "Could not create the arbitrator interface thread!\n"); exit(-1); } #endif arbitrator_context = malloc(sizeof(ip_noise_decide_what_to_do_with_packets_thread_context_t)); #ifndef __KERNEL__ arbitrator_context->queue = packets_to_arbitrate_queue ; arbitrator_context->h = h; #endif arbitrator_context->terminate = &terminate; arbitrator_context->delayer = delayer; arbitrator_context->data = data_ptr; arbitrator_context->flags = &flags; #ifndef __KERNEL__ check = pthread_create( &decide_what_to_with_packets_thread, NULL, ip_noise_decide_what_to_do_with_packets_thread_func, (void *)arbitrator_context ); if (check != 0) { fprintf(stderr, "Could not create the arbitrator thread!\n"); exit(-1); } #else packet_logic = ip_noise_arbitrator_packet_logic_alloc(data_ptr, &flags); return packet_logic; #endif #ifndef __KERNEL__ do { status = ipq_read(h, message, sizeof(message), 0); if (status < 0) { /* die(h); */ } switch(ipq_message_type(message)) { case NLMSG_ERROR: fprintf( stderr, "Received error message %d\n", ipq_get_msgerr(message) ); break; case IPQM_PACKET: { ip_noise_message_t * msg_with_time; struct timezone tz; #if 0 static int num = 0; #endif msg_with_time = malloc(sizeof(ip_noise_message_t)); /* We are copying the entire buffer, because otherwise we get * errors, since ipq_get_packet still relies on this buffer * for reference */ memcpy(msg_with_time->message, message, sizeof(msg_with_time->message)); msg_with_time->m = ipq_get_packet(msg_with_time->message); gettimeofday(&(msg_with_time->tv), &tz); ip_noise_messages_queue_enqueue( packets_to_arbitrate_queue, msg_with_time ); #if 0 printf("Received a message! (%i)\n", num++); #endif #if 0 status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); if (status < 0) { die(h); } #endif break; } default: fprintf(stderr, "Unknown message type!\n"); break; } } while (1); #endif ipq_destroy_handle(h); return 0; }
int main(int argc, char **argv) { int status, i; unsigned int payload_len, payload_offset; unsigned char buf[BUFSIZE], listtype[8]; struct ipq_handle *h; unsigned char *match, *folder, *url; PURL current; strcpy (listtype, argv[1]); get_url_info(); h = ipq_create_handle(0, PF_INET); if (!h) { die(h); } status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE); if (status < 0) { die(h); } do { memset(buf, 0, sizeof(buf)); status = ipq_read(h, buf, BUFSIZE, 0); if (status < 0) { die(h); } switch (ipq_message_type(buf)) { case NLMSG_ERROR: { fprintf(stderr, "Received error message %d\n", ipq_get_msgerr(buf)); break; } case IPQM_PACKET: { ipq_packet_msg_t *m = ipq_get_packet(buf); char decision = 'n'; struct iphdr *iph = ((struct iphdr *)m->payload); struct tcphdr *tcp = (struct tcphdr *)(m->payload + (iph->ihl<<2)); match = folder = url = NULL; payload_offset = ((iph->ihl)<<2) + (tcp->doff<<2); payload_len = (unsigned int)ntohs(iph->tot_len) - ((iph->ihl)<<2) + (tcp->doff<<2); match = (char *)(m->payload + payload_offset); if(strstr(match, "GET ") == NULL && strstr(match, "POST ") == NULL && strstr(match, "HEAD ") == NULL) { status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); //printf("****NO HTTP INFORMATION!!!\n"); if (status < 0) { die(h); } break; } for (current = purl; current != NULL; current = current->next) { if (current->folder[0] != '\0') { folder = strstr(match, current->folder); } //printf("####payload = %s\n\n", match); if ( (url = strstr(match, current->website)) != NULL ) { if (strcmp(listtype, "Exclude") == 0) { if ( (folder != NULL) || (current->folder[0] == '\0') ) { status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL); //printf("####This page is blocked by Exclude list!"); decision = 'y'; } else { status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); //printf("###Website hits but folder no hit in Exclude list! packets pass\n"); decision = 'y'; } if (status < 0) { die(h); } break; } else { if ( (folder != NULL) || (current->folder[0] == '\0') ) { status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); //printf("####This page is accepted by Include list!"); decision = 'y'; } else { status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL); //printf("####Website hits but folder no hit in Include list!, packets drop\n"); decision = 'y'; } if (status < 0) { die(h); } break; } } } if (url == NULL) { if (strcmp(listtype, "Exclude") == 0) { status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); //printf("~~~~No Url hits!! This page is accepted by Exclude list!\n"); decision = 'y'; } else { status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL); //printf("~~~~No Url hits!! This page is blocked by Include list!\n"); decision = 'y'; } if (status < 0) { die(h); } } if (decision == 'n') { ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL); //printf("~~~None of rules can be applied!! Traffic is allowed!!\n"); } break; } default: { fprintf(stderr, "Unknown message type!\n"); break; } } } while (1); ipq_destroy_handle(h); return 0; }
// Main entry point to application int main(int argc, char *argv[]) { BYTE MsgBuff[MAXIPQMSG]; struct sigaction SigAction; int i; // Read config & parameters if(!ReadConfig(argc, argv)) return EXIT_FAILURE; // If we should act as neither a master nor a client (config error) if(!(Config.Flags & CONFIGFLAGS_MASTER) && !(Config.Flags & CONFIGFLAGS_CLIENT)){ printf(APPTITLE": not configured to run as a master nor client\n"); return EXIT_FAILURE; } // If we're to be a client, check we have an IP if(Config.Flags & CONFIGFLAGS_CLIENT && Config.MasterIp[0] == 0x00){ printf(APPTITLE": Can not run as a client, no master IP specified 0x%02X\n", Config.Flags); return EXIT_FAILURE; } // Let the user know we're thinking of them if(Config.Flags & CONFIGFLAGS_MASTER) Log(LOG_NOTICE, "Acting as a master on port %d", Config.MasterPort); if(Config.Flags & CONFIGFLAGS_SELFCLIENT) Log(LOG_NOTICE, "Acting as a self-client with %d packet queues", Config.Queue); if(Config.Flags & CONFIGFLAGS_CLIENT) Log(LOG_NOTICE, "Acting as a client to %s:%d with %d packet queues", Config.MasterIp, Config.MasterPort, Config.Queue); else Log(LOG_NOTICE, "Acting stupid"); // If we should daemonise if(Config.Flags & CONFIGFLAGS_DAEMON) // Daemonise Daemon(); // If we should act as a master if(Config.Flags & CONFIGFLAGS_MASTER){ // If we should act as _only_ a master if(!(Config.Flags & CONFIGFLAGS_CLIENT) && !(Config.Flags & CONFIGFLAGS_SELFCLIENT)){ // Jump to main function in master.c which will perform this function MasterRun(NULL); return EXIT_SUCCESS; } // If we should act as a client as well else{ // Start main thread in master.c which will perform this function pthread_create(&idMasterThread, NULL, &MasterRun, NULL); } } // Create an IPQ handle hIpq = ipq_create_handle(0, PF_INET); if(hIpq == NULL){ // If we're running a master thread if(idMasterThread){ // Set flag & wait for master thread to exit ExitMasterThread = 1; pthread_join(idMasterThread, NULL); } // Log it Log(LOG_ERR, "Failed to initialise IPQ (%s)", ipq_errstr()); return EXIT_FAILURE; } // Set mode. Note: We set to packet mode so that we get to see the // number of bytes in the payload, the payload itself is ignored if (ipq_set_mode(hIpq, IPQ_COPY_PACKET, 0) == -1){ // If we're running a master thread if(idMasterThread){ // Set flag & wait for master thread to exit ExitMasterThread = 1; pthread_join(idMasterThread, NULL); } // Release IPQ ipq_destroy_handle(hIpq); // Tell the user Log(LOG_ERR, "Failed to configure IPQ (%s)", ipq_errstr()); return EXIT_FAILURE; } // Allocate Packet queue memory for(i = 0; i < PacketQueues; i++) PacketQueue[i] = malloc(Config.Queue * sizeof(struct ipq_packet_msg)); // Check allocations worked if(!PacketQueue){ // Free anything that was allocated if(PacketQueue) free(PacketQueue); // If we're running a master thread if(idMasterThread){ // Set flag & wait for master thread to exit ExitMasterThread = 1; pthread_join(idMasterThread, NULL); } // Release IPQ ipq_destroy_handle(hIpq); // Tell the user Log(LOG_ERR, "Failed to allocate sufficant memory"); return EXIT_FAILURE; } // Inititalise the PacketQueue mutex pthread_mutex_init(&PacketQueueMutex, NULL); // If we're acting as a normal client if(Config.Flags & CONFIGFLAGS_CLIENT) // Start control thread pthread_create(&idControlThread, NULL, &ControlRun, NULL); // Install SIGTERM/etc handler to get out of 'while(!ExitMain)' memset(&SigAction, 0, sizeof(SigAction)); SigAction.sa_handler = SignalHandler; sigaction(SIGINT, &SigAction, NULL); sigaction(SIGQUIT, &SigAction, NULL); sigaction(SIGTERM, &SigAction, NULL); // Install SIGHUP handler to reread config sigaction(SIGHUP, &SigAction, NULL); // Tell user Log(LOG_INFO, "Client up and running"); // Enter main loop while(!ExitMain){ // Wait up to 100mS to recieve a message int MsgSize = ipq_read(hIpq, MsgBuff, MAXIPQMSG, 100); // Error getting message if(MsgSize == -1){ // TODO: This has started to happen occasionally. Don't know why. // ipq_errstr() = "Failed to receive netlink message" // Tell the user Log(LOG_ERR, "Error reading message from IPQ (%s)", ipq_errstr()); } // Timeout getting message else if(MsgSize == 0){ // Do background processing BackgroundProcessing(); } // Got a message else{ // Switch on message type switch (ipq_message_type(MsgBuff)){ case NLMSG_ERROR: // Apparently we should call this (to clear the error?) ipq_get_msgerr(MsgBuff); // Tell the user Log(LOG_ERR, "Error reading message type from IPQ (%s)", ipq_errstr()); break; case IPQM_PACKET: // Call a function to process the packet ProcessPacketMessage(ipq_get_packet(MsgBuff)); // Do background processing BackgroundProcessing(); break; default: // Tell the user Log(LOG_WARNING, "Undefined message type from IPQ"); break; } } } // If we're running a control thread if(idControlThread){ // Set flag & wait for control thread to exit ExitControlThread = 1; pthread_join(idControlThread, NULL); } // If we're running a master thread if(idMasterThread){ // Set flag & wait for master thread to exit ExitMasterThread = 1; pthread_join(idMasterThread, NULL); } // Release IPQ ipq_destroy_handle(hIpq); // Release Packet queue memory for(i = 0; i < PacketQueues; i++) free(PacketQueue[i]); // Let the user know we're thinking of them Log(LOG_INFO, "Exited cleanly"); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int status; unsigned char buf[BUFSIZE]; struct ipq_handle *h; struct iphdr *iphead; h = ipq_create_handle(0, PF_INET); if (!h) die(h); status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE); if (status < 0) die(h); do{ status = ipq_read(h, buf, BUFSIZE, 0); if (status < 0) die(h); switch (ipq_message_type(buf)) { case NLMSG_ERROR: fprintf(stderr, "Received error message %d\\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: { ipq_packet_msg_t *m = ipq_get_packet(buf); char *dest = NULL; struct in_addr daddr; iphead = (struct iphdr *)m->payload; if(iphead->daddr == inet_addr(TO)) { status = ipq_set_verdict(h,m->packet_id, NF_ACCEPT,0,NULL); if(status < 0) die(h); break; } else { status = ipq_set_verdict(h,m->packet_id, NF_DROP,0,NULL); if(status < 0) die(h); break; } // status = ipq_set_verdict(h, m->packet_id, // NF_ACCEPT, 0, NULL); // if (status < 0) // die(h); // break; } default: fprintf(stderr, "Unknown message type!\\n"); break; } } while (1); ipq_destroy_handle(h); return 0; }
int main(int argc, char **argv) { int verdict; unsigned char buf[BUFSIZE]; struct ipq_handle *h; int cfd; int daemonize = 1; if (argc > 1) { if (!strcmp(argv[1], "-nd")) { daemonize = 0; } } srand(0); cfd = make_ipc(); if ( cfd < 0 ) exit(1); printhelp(); h = make_ipq(); if (daemonize) { FILE *logfile = 0; int pid; logfile = fopen(LOGFILE, "a"); if (!logfile) { perror("Failed to open " LOGFILE); exit(1); } if ( daemon(0, 0) < 0 ) { perror("Failed to daemonize"); exit(1); } if ( dup2(fileno(logfile), STDERR_FILENO) < 0 ) abort(); fclose(logfile); pid = writepid(); if (pid < 0) return -1; /* disable low water mark check for io pages */ if (setpriority(PRIO_PROCESS, pid, PRIO_SPECIAL_IO)) { perror("Unable to prioritize tapdisk proc"); exit(1); } TRACE("Start pfilter PID %d\n", pid); } do { ssize_t status; int type; status = ipq_read(h, buf, BUFSIZE, 0); if (status < 0) fail_retry(&h); type = ipq_message_type(buf); switch (type) { case NLMSG_ERROR: TRACE("pfilter: Received error message %d\n", ipq_get_msgerr(buf)); break; case IPQM_PACKET: { ipq_packet_msg_t *m = ipq_get_packet(buf); verdict = filter(); status = ipq_set_verdict(h, m->packet_id, verdict, 0, NULL); if (status < 0) fail_retry(&h); trace_data(verdict); break; } default: TRACE("pfilter: Unknown message type: %d\n", type); break; } } while (1); ipq_destroy_handle(h); return 0; }