/* * main: * Drive the sucker. There are two main modes -- either we store * the seek pointers, if the table is to be sorted or randomized, * or we write the pointer directly to the file, if we are to stay * in file order. If the former, we allocate and re-allocate in * CHUNKSIZE blocks; if the latter, we just write each pointer, * and then seek back to the beginning to write in the table. */ int main(int ac, char *av[]) { bool first; char *sp, dc; FILE *inf, *outf; int32_t last_off, length, pos; int32_t *p; int cnt; char *nsp; STR *fp; static char string[257]; if (pledge("stdio rpath wpath cpath", NULL) == -1) err(1, "pledge"); getargs(ac, av); /* evalute arguments */ dc = Delimch; if ((inf = fopen(Infile, "r")) == NULL) err(1, "%s", Infile); if ((outf = fopen(Outfile, "w")) == NULL) err(1, "%s", Outfile); if (pledge("stdio", NULL) == -1) err(1, "pledge"); if (!STORING_PTRS) (void) fseek(outf, sizeof Tbl, SEEK_SET); /* * Write the strings onto the file */ Tbl.str_longlen = 0; Tbl.str_shortlen = (unsigned int) 0xffffffff; Tbl.str_delim = dc; Tbl.str_version = VERSION; first = Oflag; add_offset(outf, ftell(inf)); last_off = 0; do { sp = fgets(string, sizeof(string), inf); if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) { pos = ftell(inf); length = pos - last_off - (sp ? strlen(sp) : 0); last_off = pos; if (!length) continue; add_offset(outf, pos); if (Tbl.str_longlen < (u_int32_t)length) Tbl.str_longlen = length; if (Tbl.str_shortlen > (u_int32_t)length) Tbl.str_shortlen = length; first = Oflag; } else if (first) { for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++) continue; ALLOC(Firstch, Num_pts); fp = &Firstch[Num_pts - 1]; if (Iflag && isupper((unsigned char)*nsp)) fp->first = tolower((unsigned char)*nsp); else fp->first = *nsp; fp->pos = Seekpts[Num_pts - 1]; first = false; } } while (sp != NULL); /* * write the tables in */ (void) fclose(inf); Tbl.str_numstr = Num_pts - 1; if (Tbl.str_numstr == 0) Tbl.str_shortlen = 0; if (Oflag) do_order(); else if (Rflag) randomize(); if (Xflag) Tbl.str_flags |= STR_ROTATED; if (!Sflag) { printf("\"%s\" created\n", Outfile); if (Tbl.str_numstr == 1) puts("There was 1 string"); else printf("There were %u strings\n", Tbl.str_numstr); printf("Longest string: %lu byte%s\n", (unsigned long) Tbl.str_longlen, Tbl.str_longlen == 1 ? "" : "s"); printf("Shortest string: %lu byte%s\n", (unsigned long) Tbl.str_shortlen, Tbl.str_shortlen == 1 ? "" : "s"); } (void) fseek(outf, 0, SEEK_SET); Tbl.str_version = htonl(Tbl.str_version); Tbl.str_numstr = htonl(Tbl.str_numstr); Tbl.str_longlen = htonl(Tbl.str_longlen); Tbl.str_shortlen = htonl(Tbl.str_shortlen); Tbl.str_flags = htonl(Tbl.str_flags); (void) fwrite(&Tbl.str_version, sizeof(Tbl.str_version), 1, outf); (void) fwrite(&Tbl.str_numstr, sizeof(Tbl.str_numstr), 1, outf); (void) fwrite(&Tbl.str_longlen, sizeof(Tbl.str_longlen), 1, outf); (void) fwrite(&Tbl.str_shortlen, sizeof(Tbl.str_shortlen), 1, outf); (void) fwrite(&Tbl.str_flags, sizeof(Tbl.str_flags), 1, outf); (void) fwrite( Tbl.stuff, sizeof(Tbl.stuff), 1, outf); if (STORING_PTRS) { for (p = Seekpts, cnt = Num_pts; cnt--; ++p) { *p = htonl(*p); (void) fwrite(p, sizeof(*p), 1, outf); } } if (fclose(outf)) err(1, "fclose `%s'", Outfile); return 0; }
int main(int argc, char **argv) { const char *root = "/Users/mdhender/Software/Xcode/jr/data"; if (chdir(root) < 0) { perror(root); exit(3); } /* port to listen on */ int portno = 8765; /* check command line args */ /* if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); } else if (argc == 2) { portno = atoi(argv[1]); } */ /* open socket descriptor for parent socket */ int fdServer = socket(AF_INET, SOCK_STREAM, 0); if (fdServer < 0) { perror("ERROR opening socket"); exit(1); } else { /* flag value for setsockopt allows us to restart server immediately */ int optval = 1; setsockopt(fdServer, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)); } /* bind port to socket */ struct sockaddr_in serveraddr; memset(&serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)portno); if (bind(fdServer, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { perror("ERROR on binding"); exit(1); } /* get us ready to accept connection requests */ if (listen(fdServer, 5) < 0) { /* allow 5 requests to queue up */ perror("ERROR on listen"); exit(1); } /* * main loop: wait for a connection request, parse HTTP, * serve requested content, close connection. */ int maxLoops = 5; while (1 && maxLoops--) { /* wait for a connection request on a socket */ struct sockaddr_in clientaddr; socklen_t clientlen = sizeof(clientaddr); int fdClient = accept(fdServer, (struct sockaddr *)&clientaddr, &clientlen); if (fdClient < 0) { jr_log(ERROR, "error on accept"); } /* client host info tells us who sent the message */ struct hostent *hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); if (!hostp) { jr_log(ERROR, "error on gethostbyaddr"); } /* dotted decimal host addr string */ char *hostaddrp = inet_ntoa(clientaddr.sin_addr); if (!hostaddrp) { jr_log(ERROR, "error on inet_ntoa"); } /* open the child socket descriptor as a stream */ FILE *stream = fdopen(fdClient, "r+"); if (!stream) { jr_log(ERROR, "error on fdopen"); } jr_service_request(fdServer, fdClient, stream); fclose(stream); close(fdClient); } close(fdServer); return 0; }
int main(int argc,char *argv[]) { int flag, num_seats = 20; int connfd = 0; struct sockaddr_in serv_addr; char send_buffer[BUFSIZE]; listenfd = 0; int server_port = 8080; if (argc > 1) { num_seats = atoi(argv[1]); } if (server_port < 1500) { fprintf(stderr,"INVALID PORT NUMBER: %d; can't be < 1500\n",server_port); exit(-1); } if (signal(SIGINT, shutdown_server) == SIG_ERR) printf("Issue registering SIGINT handler"); listenfd = socket(AF_INET, SOCK_STREAM, 0); if ( listenfd < 0 ){ perror("Socket"); exit(errno); } printf("Established Socket: %d\n", listenfd); flag = 1; setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag) ); // initialize the threadpool // Set the number of threads to be 20 and size of the queue to be 100 threadpool = pool_create(100, 20); // Load the seats; load_seats(num_seats); //TODO read from argv // set server address memset(&serv_addr, '0', sizeof(serv_addr)); memset(send_buffer, '0', sizeof(send_buffer)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(server_port); // bind to socket if ( bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) != 0) { perror("socket--bind"); exit(errno); } // listen for incoming requests listen(listenfd, 10); // handle connections loop (forever) while(1) { connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); //add each task to the queue pool_add_task(threadpool, (void *)&handle_connection,(void *)connfd); } }
int main( int argc , char *argv[]) { signal(SIGINT, ctrlHandler); n_linhas = linhas("localdns.txt"); #ifdef DEBUG printf("Verificacao dos ficheiros presentes.\n"); #endif if(verifica_ficheiros("localdns.txt") == 0) { printf("Ficheiro localdns.txt inexistente!\n"); exit(1); } if(verifica_ficheiros("config.txt") == 0) { printf("Ficheiro config.txt inexistente!\n"); exit(1); } #ifdef DEBUG printf("Inicializacoes.\n"); #endif unsigned char buf[65536], *reader, *reader2, qname; int sockfd, stop; struct DNS_HEADER *dns = NULL; struct stats stat; struct sockaddr_in servaddr, dest; socklen_t len; int i, np, r; cfg_process = 1; stats_process = 1; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); #ifdef DEBUG printf("Criacao das Filas Normal e Prioridade e da lista de Domains locais.\n"); #endif Fila fila_normal = cria_fila(); Fila fila_prioridade = cria_fila(); Local l_domains = cria_lista(); // Hora de arranque do Servidor time_t clk = time(NULL); strcpy(stat.data_hora_arranque, ctime(&clk)); // Inicializaco Memoria Partilhada init_shm(); ptr_config->flag = 0; printf("[PAI - MAIN] PID Main = %d PID DO MEU PAI = %d\n", getpid(), getppid()); char* data; #ifdef DEBUG printf("Criacao processo de configuracoes.\n"); #endif if ((cfg_process = fork()) == 0) { signal(SIGUSR1, handler_CFG); #ifdef DEBUG printf("RELEASE CFG.\n"); printf("Mapeamento de localdns.txt.\n"); #endif mapear("localdns.txt"); #ifdef DEBUG printf("Leitura de config.txt para estrutura em memoria partilhada.\n"); #endif file2memory("config.txt"); if(signal(SIGALRM, SIG_IGN) == SIG_ERR) { perror("SIGALRM Ignore error"); exit(1); } } else { usleep(200000); if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("Signal ignore error"); exit(1); } #ifdef DEBUG printf("RELEASE MAIN.\n"); #endif #ifdef DEBUG printf("Extrair enderecos e ip's locais do mmap\n"); #endif token_mmap(l_domains, ptr_config->data); // Check arguments if(argc <= 1) { printf("Usage: %s <port>\n", argv[0]); exit(1); } // Get server UDP port number int port = atoi(argv[1]); if(port <= 0) { printf("Usage: %s <port>\n", argv[0]); exit(1); } // **************************************** // Create socket & bind // **************************************** // Create UDP socket sockfd = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries if (sockfd < 0) { printf("ERROR opening socket.\n"); exit(1); } // Prepare UDP to bind port bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); // **************************************** // Receive questions // **************************************** // Bind application to UDP port int res = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if(res < 0) { printf("Error binding to port %d.\n", servaddr.sin_port); if(servaddr.sin_port <= 1024) { printf("To use ports below 1024 you may need additional permitions. Try to use a port higher than 1024.\n"); } else { printf("Please make sure this UDP port is not being used.\n"); } exit(1); } #ifdef DEBUG printf("Criacao named pipe para as estatisticas\n."); #endif char* n_pipe = ptr_config->Named_pipe; if(verifica_ficheiros(n_pipe) == 1) { printf("Named pipe ja existente! A eliminar...\n"); unlink(n_pipe); } if(((np = mkfifo(n_pipe, O_CREAT|O_EXCL|0600)<0)) && (errno != EEXIST)) { perror("mkfifo"); exit(1); } if (np != 0) { fprintf(stderr, "Impossivel criar fifo %s\n", n_pipe); return 1; } if((np = open(n_pipe, O_RDWR)) < 0) { perror("Opening Named Pipe"); exit(1); } } #ifdef DEBUG printf("A sair = %d\n", getpid()); #endif #ifdef DEBUG printf("Criacao Processo de estatisticas\n"); #endif if(cfg_process != 0) { stats_process = fork(); if(stats_process == 0) { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("Signal ignore error"); exit(1); } #ifdef DEBUG printf("RELEASE STATS.\n"); #endif } else { usleep(200000); if(signal(SIGALRM, SIG_IGN) == SIG_ERR) { perror("SIGALRM Ignore error"); exit(1); } } } #ifdef DEBUG printf("Quem chega primeiro = %d\n", getpid()); #endif if(cfg_process != 0 && stats_process != 0) { #ifdef DEBUG printf("A preencher struct para argumento da funcao do thread.\n"); #endif struct thread_data t_data; t_data.normal = fila_normal; t_data.prioridade = fila_prioridade; t_data.domains = l_domains; int N_THREADS = ptr_config->N_threads; p_threads = malloc(sizeof(*p_threads) * N_THREADS); #ifdef DEBUG printf("A criar a pool de threads.\n"); #endif for(i=0;i < N_THREADS;i++) { pthread_create(p_threads+i, NULL, requester, (void*)&t_data); } usleep(50000); printf("\n\n-- Waiting for DNS message --\n\n"); } while(1) { if((cfg_process == 0) && (ptr_config->saida == 1)) { // MODO MANUNTENCAO file2memory("config.txt"); ptr_config->saida = 0; usleep(100000); printf("\n-- Waiting for DNS message --\n"); } if(cfg_process != 0 && stats_process != 0) { // GESTOR PEDIDOS usleep(200000); len = sizeof(dest); // Thread blocking! if(recvfrom (sockfd, (unsigned char*)buf, 65536 , 0 , (struct sockaddr*)&dest , &len) < 0) { perror("Error in recvfrom"); exit(1); } printf("DNS message received\n"); // Process received message dns = (struct DNS_HEADER*) buf; qname = (unsigned char)buf[sizeof(struct DNS_HEADER)]; reader = &buf[sizeof(struct DNS_HEADER)]; // We only need to process the questions // We only process DNS messages with one question // Get the query fields according to the RFC specification struct QUERY query; if(ntohs(dns->q_count) == 1) { // Get NAME query.name = convertRFC2Name(reader,buf,&stop); reader = reader + stop; // Get QUESTION structure query.ques = (struct QUESTION*)(reader); reader = reader + sizeof(struct QUESTION); // Check question type. We only need to process A records. if(ntohs(query.ques->qtype) == 1) { printf("A record request.\n\n"); } else { printf("NOT A record request!! Ignoring DNS message!\n"); continue; } } else { printf("\n\nDNS message must contain one question!! Ignoring DNS message!\n\n"); continue; } #ifdef DEBUG printf("ID PEDIDO = %d\n", dns->id); #endif /***** VALIDAR PEDIDO *****/ valido = 0; // 1. Verificar se e' localDomain (Se for, vai para a lista prioritaria) // TRABALHO DOS THREADS... if(strstr(query.name, ptr_config->localDomain) != NULL) { valido = 1; stat.pedidos_local += 1; insere_pedido(fila_prioridade, receber_info(query.name, &dest, dns->id, sockfd)); } else if(ptr_config->flag % 2 == 0) { // 2. Verificar se é um dos dominios autorizados (ptr_config->domains[]) for(i=0; i < ptr_config->n_domains; i++) { if(strstr(query.name, ptr_config->domains[i]) != NULL) { valido = 1; stat.pedidos_externos += 1; insere_pedido(fila_normal, receber_info(query.name, &dest, dns->id, sockfd)); break; } } } #ifdef DEBUG imprimir_fila(fila_normal); imprimir_fila(fila_prioridade); #endif if(valido == 1) { #ifdef DEBUG printf("A ENVIAR SINAL PARA A THREAD...\n"); #endif pthread_cond_signal(&cond); } else { if(ptr_config->flag % 2 != 0) { printf("Durante o modo de manuntencao apenas pedidos locais sao aceites!\n"); printf("A enviar 0.0.0.0...\n"); } else { printf("Pedido negado!\nDe momento os dominios aceites sao:\n"); for(i=0;i<ptr_config->n_domains;i++) { printf("-> Dominio %d = %s\n",i,ptr_config->domains[i]); } } sendReply(dns->id, query.name, inet_addr("0.0.0.0"), sockfd, dest); printf("\n\n-- Waiting for DNS message --\n\n"); } if(valido == 0) { stat.pedidos_negados += 1; } stat.total_pedidos += 1; // Enviar dados das ESTATISTICAS para o named pipe aqui #ifdef DEBUG printf("A escrever estatisticas para o named pipe\n."); #endif write(np, &stat, sizeof(struct stats)); } if (stats_process == 0 && cfg_process != 0) { // STATS Process signal(SIGALRM, handler_alarm); Config* ptr; if ((ptr = shmat(shmID, NULL, 0)) == (Config *) -1) { perror("error in shmat"); exit(1); } struct stats st; char* n_pipe = ptr_config->Named_pipe; if((r = open(n_pipe, O_RDONLY)) < 0) { perror("Child open Named pipe"); exit(1); } read(r, &st, sizeof(struct stats)); linha(st.data_hora_arranque); time_t clk2 = time(NULL); strcpy(st.data_info, ctime(&clk2)); linha(st.data_info); t_p = st.total_pedidos; p_n = st.pedidos_negados; p_l = st.pedidos_local; p_e = st.pedidos_externos; strcpy(d_a, st.data_hora_arranque); strcpy(u_i, st.data_info); alarm(FREQ); } } return 0; }
#endif #include <err.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include "talk.h" #include "talk_ctl.h" void get_addrs(const char *my_machine_name __unused, const char *his_machine_name) { struct hostent *hp; struct servent *sp; msg.pid = htonl(getpid()); hp = gethostbyname(his_machine_name); if (hp == NULL) errx(1, "%s: %s", his_machine_name, hstrerror(h_errno)); bcopy(hp->h_addr, (char *) &his_machine_addr, hp->h_length); if (get_iface(&his_machine_addr, &my_machine_addr) == -1) err(1, "failed to find my interface address"); /* find the server's port */ sp = getservbyname("ntalk", "udp"); if (sp == 0) errx(1, "ntalk/udp: service is not registered"); daemon_port = sp->s_port; }
// I read some comments one a indicating that doing an integer add // here would be faster than a bitwise or. For now, the or has // programmer clarity, since the intended outcome matches the // operation. U64 ll_htonll(U64 hostlonglong) { return ((U64)(htonl((U32)((hostlonglong >> 32) & 0xFFFFFFFF))) | ((U64)(htonl((U32)(hostlonglong & 0xFFFFFFFF))) << 32)); }
static inline bool mroute_is_mcast (const in_addr_t addr) { return ((addr & htonl(IP_MCAST_SUBNET_MASK)) == htonl(IP_MCAST_NETWORK)); }
float htonf(float x) { int *p = (int *)&x; *p = htonl(*p); return x; }
/* * function: format0 * * export flows in cflowd format */ int format0(struct ftio *ftio, struct options *opt) { struct fts3rec_offsets fo; struct ftver ftv; struct fttime ftt; char *rec; uint32_t ui32, index, sysUpTime, unix_secs, unix_nsecs, First, Last; uint16_t ui16; uint8_t ui8; ftio_get_ver(ftio, &ftv); fts3rec_compute_offsets(&fo, &ftv); switch (ftv.d_version) { case 1: opt->cflowd_mask &= CF_INDEX_V1_MASK; break; case 5: opt->cflowd_mask &= CF_INDEX_V5_MASK; break; case 6: opt->cflowd_mask &= CF_INDEX_V6_MASK; break; case 7: opt->cflowd_mask &= CF_INDEX_V7_MASK; break; case 1005: opt->cflowd_mask &= CF_INDEX_V5_MASK; break; case 8: switch (ftv.agg_method) { case 1: opt->cflowd_mask &= CF_INDEX_V8_1_MASK; break; case 2: opt->cflowd_mask &= CF_INDEX_V8_2_MASK; break; case 3: opt->cflowd_mask &= CF_INDEX_V8_3_MASK; break; case 4: opt->cflowd_mask &= CF_INDEX_V8_4_MASK; break; case 5: opt->cflowd_mask &= CF_INDEX_V8_5_MASK; break; case 6: opt->cflowd_mask &= CF_INDEX_V8_6_MASK; break; case 7: opt->cflowd_mask &= CF_INDEX_V8_7_MASK; break; case 8: opt->cflowd_mask &= CF_INDEX_V8_8_MASK; break; case 9: opt->cflowd_mask &= CF_INDEX_V8_9_MASK; break; case 10: opt->cflowd_mask &= CF_INDEX_V8_10_MASK; break; case 11: opt->cflowd_mask &= CF_INDEX_V8_11_MASK; break; case 12: opt->cflowd_mask &= CF_INDEX_V8_12_MASK; break; case 13: opt->cflowd_mask &= CF_INDEX_V8_13_MASK; break; case 14: opt->cflowd_mask &= CF_INDEX_V8_14_MASK; break; default: fterr_warnx("Unsupported export version"); return -1; } /* switch */ break; default: fterr_warnx("Unsupported export version"); return -1; } /* switch */ /* index */ index = opt->cflowd_mask; index = htonl(index); while ((rec = ftio_read(ftio))) { fwrite(&index, sizeof (index), 1, stdout); if (opt->cflowd_mask & CF_ROUTERMASK) { ui32 = *((uint32_t*)(rec+fo.exaddr)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_SRCIPADDRMASK) { ui32 = *((uint32_t*)(rec+fo.srcaddr)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_DSTIPADDRMASK) { ui32 = *((uint32_t*)(rec+fo.dstaddr)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_INPUTIFINDEXMASK) { ui16 = *((uint16_t*)(rec+fo.input)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_OUTPUTIFINDEXMASK) { ui16 = *((uint16_t*)(rec+fo.output)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_SRCPORTMASK) { ui16 = *((uint16_t*)(rec+fo.srcport)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_DSTPORTMASK) { ui16 = *((uint16_t*)(rec+fo.dstport)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_PKTSMASK) { ui32 = *((uint32_t*)(rec+fo.dPkts)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_BYTESMASK) { ui32 = *((uint32_t*)(rec+fo.dOctets)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_IPNEXTHOPMASK) { ui32 = *((uint32_t*)(rec+fo.nexthop)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_STARTTIMEMASK) { sysUpTime = *((uint32_t*)(rec+fo.sysUpTime)); unix_secs = *((uint32_t*)(rec+fo.unix_secs)); unix_nsecs = *((uint32_t*)(rec+fo.unix_nsecs)); First = *((uint32_t*)(rec+fo.First)); ftt = ftltime(sysUpTime, unix_secs, unix_nsecs, First); ui32 = htonl(ftt.secs); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_ENDTIMEMASK) { sysUpTime = *((uint32_t*)(rec+fo.sysUpTime)); unix_secs = *((uint32_t*)(rec+fo.unix_secs)); unix_nsecs = *((uint32_t*)(rec+fo.unix_nsecs)); Last = *((uint32_t*)(rec+fo.Last)); ftt = ftltime(sysUpTime, unix_secs, unix_nsecs, Last); ui32 = htonl(ftt.secs); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_PROTOCOLMASK) { ui8 = *((uint8_t*)(rec+fo.prot)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_TOSMASK) { ui8 = *((uint8_t*)(rec+fo.tos)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_SRCASMASK) { ui16 = *((uint16_t*)(rec+fo.src_as)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_DSTASMASK) { ui16 = *((uint16_t*)(rec+fo.dst_as)); ui16 = htons(ui16); fwrite(&ui16, sizeof (ui16), 1, stdout); } if (opt->cflowd_mask & CF_SRCMASKLENMASK) { ui8 = *((uint8_t*)(rec+fo.src_mask)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_DSTMASKLENMASK) { ui8 = *((uint8_t*)(rec+fo.dst_mask)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_TCPFLAGSMASK) { ui8 = *((uint8_t*)(rec+fo.tcp_flags)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_INPUTENCAPMASK) { ui8 = *((uint8_t*)(rec+fo.in_encaps)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_OUTPUTENCAPMASK) { ui8 = *((uint8_t*)(rec+fo.out_encaps)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_PEERNEXTHOPMASK) { ui32 = *((uint32_t*)(rec+fo.peer_nexthop)); ui32 = htonl(ui32); fwrite(&ui32, sizeof (ui32), 1, stdout); } if (opt->cflowd_mask & CF_ENGINETYPEMASK) { ui8 = *((uint8_t*)(rec+fo.engine_type)); fwrite(&ui8, sizeof (ui8), 1, stdout); } if (opt->cflowd_mask & CF_ENGINEIDMASK) { ui8 = *((uint8_t*)(rec+fo.engine_id)); fwrite(&ui8, sizeof (ui8), 1, stdout); } ++opt->records; } /* while */ return 0; } /* format 0 */
/* ----------------------------------------------------------------------------- MEDUSA DSP HOST TO NETWORK 32BITS ---------------------------------------------------------------------------*/ uint32_t medusa_dsp_hton32( uint32_t input ){ return htonl(input); }
ofl_err ofl_structs_group_stats_unpack(struct ofp_group_stats *src, size_t *len, struct ofl_group_stats **dst) { struct ofl_group_stats *s; struct ofp_bucket_counter *c; ofl_err error; size_t slen; size_t i; if (*len < sizeof(struct ofp_group_stats)) { OFL_LOG_WARN(LOG_MODULE, "Received group desc stats reply is too short (%zu).", *len); return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN); } if (*len < ntohs(src->length)) { OFL_LOG_WARN(LOG_MODULE, "Received group stats reply has invalid length (set to %u, but only %zu received).", ntohs(src->length), *len); return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN); } if (ntohl(src->group_id) > OFPG_MAX) { if (OFL_LOG_IS_WARN_ENABLED(LOG_MODULE)) { char *gs = ofl_group_to_string(ntohl(src->group_id)); OFL_LOG_WARN(LOG_MODULE, "Received group stats has invalid group_id (%s).", gs); free(gs); } return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN); } slen = ntohs(src->length) - sizeof(struct ofp_group_stats); s = (struct ofl_group_stats *)malloc(sizeof(struct ofl_group_stats)); s->group_id = ntohl(src->group_id); s->ref_count = ntohl(src->ref_count); s->packet_count = ntoh64(src->packet_count); s->byte_count = ntoh64(src->byte_count); s->duration_sec = htonl(src->duration_sec); s->duration_nsec = htonl(src->duration_nsec); error = ofl_utils_count_ofp_bucket_counters(src->bucket_stats, slen, &s->counters_num); if (error) { free(s); return error; } s->counters = (struct ofl_bucket_counter **)malloc(s->counters_num * sizeof(struct ofl_bucket_counter *)); c = src->bucket_stats; for (i = 0; i < s->counters_num; i++) { error = ofl_structs_bucket_counter_unpack(c, &slen, &(s->counters[i])); if (error) { OFL_UTILS_FREE_ARR(s->counters, i); free(s); return error; } c = (struct ofp_bucket_counter *)((uint8_t *)c + sizeof(struct ofp_bucket_counter)); } if (slen != 0) { *len = *len - ntohs(src->length) + slen; OFL_LOG_WARN(LOG_MODULE, "The received group stats contained extra bytes (%zu).", slen); ofl_structs_free_group_stats(s); return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN); } *len -= ntohs(src->length); *dst = s; return 0; }
/* * Set the date in the machines controlled by timedaemons by communicating the * new date to the local timedaemon. If the timedaemon is in the master state, * it performs the correction on all slaves. If it is in the slave state, it * notifies the master that a correction is needed. * Returns 0 on success. Returns > 0 on failure, setting retval to 2; */ int netsettime(time_t tval) { struct timeval tout; struct servent *sp; struct tsp msg; struct sockaddr_in lsin, dest, from; fd_set ready; long waittime; int s, port, timed_ack, found, lerr; socklen_t length; char hostname[MAXHOSTNAMELEN]; if ((sp = getservbyname("timed", "udp")) == NULL) { warnx("timed/udp: unknown service"); return (retval = 2); } dest.sin_port = sp->s_port; dest.sin_family = AF_INET; dest.sin_addr.s_addr = htonl((u_long)INADDR_ANY); s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { if (errno != EAFNOSUPPORT) warn("timed"); return (retval = 2); } memset(&lsin, 0, sizeof(lsin)); lsin.sin_family = AF_INET; for (port = IPPORT_RESERVED - 1; port > IPPORT_RESERVED / 2; port--) { lsin.sin_port = htons((u_short)port); if (bind(s, (struct sockaddr *)&lsin, sizeof(lsin)) >= 0) break; if (errno == EADDRINUSE) continue; if (errno != EADDRNOTAVAIL) warn("bind"); goto bad; } if (port == IPPORT_RESERVED / 2) { warnx("all ports in use"); goto bad; } memset(&msg, 0, sizeof(msg)); msg.tsp_type = TSP_SETDATE; msg.tsp_vers = TSPVERSION; if (gethostname(hostname, sizeof(hostname))) { warn("gethostname"); goto bad; } (void)strlcpy(msg.tsp_name, hostname, sizeof(msg.tsp_name)); msg.tsp_seq = htons((u_short)0); msg.tsp_time.tv_sec = htonl((u_long)tval); msg.tsp_time.tv_usec = htonl((u_long)0); length = sizeof(struct sockaddr_in); if (connect(s, (struct sockaddr *)&dest, length) < 0) { warn("connect"); goto bad; } if (send(s, (char *)&msg, sizeof(struct tsp), 0) < 0) { if (errno != ECONNREFUSED) warn("send"); goto bad; } timed_ack = -1; waittime = WAITACK; loop: tout.tv_sec = waittime; tout.tv_usec = 0; FD_ZERO(&ready); FD_SET(s, &ready); found = select(FD_SETSIZE, &ready, (fd_set *)0, (fd_set *)0, &tout); length = sizeof(lerr); if (!getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&lerr, &length) && lerr) { if (lerr != ECONNREFUSED) warnc(lerr, "send (delayed error)"); goto bad; } if (found > 0 && FD_ISSET(s, &ready)) { length = sizeof(struct sockaddr_in); if (recvfrom(s, &msg, sizeof(struct tsp), 0, (struct sockaddr *)&from, &length) < 0) { if (errno != ECONNREFUSED) warn("recvfrom"); goto bad; } msg.tsp_seq = ntohs(msg.tsp_seq); msg.tsp_time.tv_sec = ntohl(msg.tsp_time.tv_sec); msg.tsp_time.tv_usec = ntohl(msg.tsp_time.tv_usec); switch (msg.tsp_type) { case TSP_ACK: timed_ack = TSP_ACK; waittime = WAITDATEACK; goto loop; case TSP_DATEACK: (void)close(s); return (0); default: warnx("wrong ack received from timed: %s", tsptype[msg.tsp_type]); timed_ack = -1; break; } } if (timed_ack == -1) warnx("can't reach time daemon, time set locally"); bad: (void)close(s); return (retval = 2); }
int udpclo(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) { #else int main(int argc, char *argv[]) { #endif unsigned char *buffer; VOutduct *vduct; PsmAddress vductElt; Sdr sdr; Outduct outduct; ClProtocol protocol; Outflow outflows[3]; int i; char *hostName; unsigned short portNbr; unsigned int hostNbr; struct sockaddr socketName; struct sockaddr_in *inetName; Object bundleZco; BpExtendedCOS extendedCOS; char destDuctName[MAX_CL_DUCT_NAME_LEN + 1]; unsigned int bundleLength; int ductSocket = -1; int bytesSent; if (bpAttach() < 0) { putErrmsg("udpclo can't attach to BP.", NULL); return -1; } buffer = MTAKE(UDPCLA_BUFSZ); if (buffer == NULL) { putErrmsg("No memory for UDP buffer in udpclo.", NULL); return -1; } findOutduct("udp", "*", &vduct, &vductElt); if (vductElt == 0) { putErrmsg("No such udp duct.", "*"); MRELEASE(buffer); return -1; } if (vduct->cloPid > 0 && vduct->cloPid != sm_TaskIdSelf()) { putErrmsg("CLO task is already started for this duct.", itoa(vduct->cloPid)); MRELEASE(buffer); return -1; } /* All command-line arguments are now validated. */ sdr = getIonsdr(); sdr_read(sdr, (char *) &outduct, sdr_list_data(sdr, vduct->outductElt), sizeof(Outduct)); sdr_read(sdr, (char *) &protocol, outduct.protocol, sizeof(ClProtocol)); if (protocol.nominalRate <= 0) { vduct->xmitThrottle.nominalRate = DEFAULT_UDP_RATE; } else { vduct->xmitThrottle.nominalRate = protocol.nominalRate; } memset((char *) outflows, 0, sizeof outflows); outflows[0].outboundBundles = outduct.bulkQueue; outflows[1].outboundBundles = outduct.stdQueue; outflows[2].outboundBundles = outduct.urgentQueue; for (i = 0; i < 3; i++) { outflows[i].svcFactor = 1 << i; } /* Set up signal handling. SIGTERM is shutdown signal. */ oK(udpcloSemaphore(&(vduct->semaphore))); isignal(SIGTERM, shutDownClo); /* Can now begin transmitting to remote duct. */ writeMemo("[i] udpclo is running."); while (!(sm_SemEnded(vduct->semaphore))) { if (bpDequeue(vduct, outflows, &bundleZco, &extendedCOS, destDuctName) < 0) { sm_SemEnd(udpcloSemaphore(NULL));/* Stop. */ continue; } if (bundleZco == 0) /* Interrupted. */ { continue; } hostName = destDuctName; parseSocketSpec(destDuctName, &portNbr, &hostNbr); if (portNbr == 0) { portNbr = BpUdpDefaultPortNbr; } portNbr = htons(portNbr); if (hostNbr == 0) { writeMemoNote("[?] Can't get IP address for host", hostName); } hostNbr = htonl(hostNbr); memset((char *) &socketName, 0, sizeof socketName); inetName = (struct sockaddr_in *) &socketName; inetName->sin_family = AF_INET; inetName->sin_port = portNbr; memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &hostNbr, 4); bundleLength = zco_length(sdr, bundleZco); bytesSent = sendBundleByUDP(&socketName, &ductSocket, bundleLength, bundleZco, buffer); if (bytesSent < bundleLength) { sm_SemEnd(udpcloSemaphore(NULL));/* Stop. */ continue; } /* Make sure other tasks have a chance to run. */ sm_TaskYield(); } if (ductSocket != -1) { close(ductSocket); } writeErrmsgMemos(); writeMemo("[i] udpclo duct has ended."); MRELEASE(buffer); ionDetach(); return 0; }
nsresult nsProfileLock::LockWithSymlink(const nsACString& lockFilePath, bool aHaveFcntlLock) { nsresult rv; struct in_addr inaddr; inaddr.s_addr = htonl(INADDR_LOOPBACK); char hostname[256]; PRStatus status = PR_GetSystemInfo(PR_SI_HOSTNAME, hostname, sizeof hostname); if (status == PR_SUCCESS) { char netdbbuf[PR_NETDB_BUF_SIZE]; PRHostEnt hostent; status = PR_GetHostByName(hostname, netdbbuf, sizeof netdbbuf, &hostent); if (status == PR_SUCCESS) memcpy(&inaddr, hostent.h_addr, sizeof inaddr); } char *signature = PR_smprintf("%s:%s%lu", inet_ntoa(inaddr), aHaveFcntlLock ? "+" : "", (unsigned long)getpid()); const nsPromiseFlatCString& flat = PromiseFlatCString(lockFilePath); const char *fileName = flat.get(); int symlink_rv, symlink_errno = 0, tries = 0; // use ns4.x-compatible symlinks if the FS supports them while ((symlink_rv = symlink(signature, fileName)) < 0) { symlink_errno = errno; if (symlink_errno != EEXIST) break; if (!IsSymlinkStaleLock(&inaddr, fileName, aHaveFcntlLock)) break; // Lock seems to be bogus: try to claim it. Give up after a large // number of attempts (100 comes from the 4.x codebase). (void) unlink(fileName); if (++tries > 100) break; } PR_smprintf_free(signature); signature = nsnull; if (symlink_rv == 0) { // We exclusively created the symlink: record its name for eventual // unlock-via-unlink. rv = NS_OK; mHaveLock = PR_TRUE; mPidLockFileName = strdup(fileName); if (mPidLockFileName) { PR_APPEND_LINK(this, &mPidLockList); if (!setupPidLockCleanup++) { // Clean up on normal termination. // This instanciates a dummy class, and will trigger the class // destructor when libxul is unloaded. This is equivalent to atexit(), // but gracefully handles dlclose(). static RemovePidLockFilesExiting r; // Clean up on abnormal termination, using POSIX sigaction. // Don't arm a handler if the signal is being ignored, e.g., // because mozilla is run via nohup. if (!sDisableSignalHandling) { struct sigaction act, oldact; #ifdef SA_SIGINFO act.sa_sigaction = FatalSignalHandler; act.sa_flags = SA_SIGINFO; #else act.sa_handler = FatalSignalHandler; #endif sigfillset(&act.sa_mask); #define CATCH_SIGNAL(signame) \ PR_BEGIN_MACRO \ if (sigaction(signame, NULL, &oldact) == 0 && \ oldact.sa_handler != SIG_IGN) \ { \ sigaction(signame, &act, &signame##_oldact); \ } \ PR_END_MACRO CATCH_SIGNAL(SIGHUP); CATCH_SIGNAL(SIGINT); CATCH_SIGNAL(SIGQUIT); CATCH_SIGNAL(SIGILL); CATCH_SIGNAL(SIGABRT); CATCH_SIGNAL(SIGSEGV); CATCH_SIGNAL(SIGTERM); #undef CATCH_SIGNAL } } } } else if (symlink_errno == EEXIST) rv = NS_ERROR_FILE_ACCESS_DENIED; else { #ifdef DEBUG printf("symlink() failed. errno = %d\n", errno); #endif rv = NS_ERROR_FAILURE; } return rv; }
//uint32_t转换为ip字符串 void uint32_t_to_ip(uint32_t ip_num,char *ip){ struct in_addr inaddr; inaddr.s_addr = htonl(ip_num); strcpy(ip,inet_ntoa(inaddr)); }
int main(int argc, char **argv) { int listenfd, connfd, nfds; struct sockaddr_in servaddr; char buff[MAXLINE]; time_t ticks; struct epoll_event ev; struct epoll_event events[MAXEPOLLSIZE]; if((listenfd = Socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("create socket."); exit(1); } printf("socket 创建成功.\n"); SetNonBlocking(listenfd); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(1025); /* daytime server */ if(bind(listenfd, (struct sockaddr_in *) &servaddr, sizeof(servaddr)) == -1) { perror("bind"); exit(1); } printf("ip地址和端口绑定成功.\n"); epfd = epoll_create(MAXEPOLLSIZE); ev.events = EPOLLIN | EPOLLOUT | EPOLLET; ev.data.fd = listenfd; if(epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev) < 0) { fprintf(stderr, "epoll set insertion error: fd=%d\n", listenfd); return -1; } printf("监听socket加入epoll成功.\n"); listen(listenfd, LISTENQ); while(1) { nfds = epoll_wait(epfd, events, 10000, -1); if(nfds<0 && errno != EINTR) { perror("epoll_wait"); break; } else if(nfds > 0) { /*处理所有事件*/ for(i=0; i < nfds; i++) { if(events[i].data.fd == listenfd) { while(1) { if((connfd = accept(listenfd, (sockaddr_in *) NULL, NULL)) == -1) { perror("accept"); break; } ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); if(write(connfd, buff, strlen(buff)) == -1) { perror("write"); break; } } } } } close(connfd); } }
// virtual S32 LLSDBinaryFormatter::format(const LLSD& data, std::ostream& ostr, U32 options) const { S32 format_count = 1; switch(data.type()) { case LLSD::TypeMap: { ostr.put('{'); U32 size_nbo = htonl(data.size()); ostr.write((const char*)(&size_nbo), sizeof(U32)); LLSD::map_const_iterator iter = data.beginMap(); LLSD::map_const_iterator end = data.endMap(); for(; iter != end; ++iter) { ostr.put('k'); formatString((*iter).first, ostr); format_count += format((*iter).second, ostr); } ostr.put('}'); break; } case LLSD::TypeArray: { ostr.put('['); U32 size_nbo = htonl(data.size()); ostr.write((const char*)(&size_nbo), sizeof(U32)); LLSD::array_const_iterator iter = data.beginArray(); LLSD::array_const_iterator end = data.endArray(); for(; iter != end; ++iter) { format_count += format(*iter, ostr); } ostr.put(']'); break; } case LLSD::TypeUndefined: ostr.put('!'); break; case LLSD::TypeBoolean: if(data.asBoolean()) ostr.put(BINARY_TRUE_SERIAL); else ostr.put(BINARY_FALSE_SERIAL); break; case LLSD::TypeInteger: { ostr.put('i'); U32 value_nbo = htonl(data.asInteger()); ostr.write((const char*)(&value_nbo), sizeof(U32)); break; } case LLSD::TypeReal: { ostr.put('r'); F64 value_nbo = ll_htond(data.asReal()); ostr.write((const char*)(&value_nbo), sizeof(F64)); break; } case LLSD::TypeUUID: { ostr.put('u'); LLUUID temp = data.asUUID(); ostr.write((const char*)(&(temp.mData)), UUID_BYTES); break; } case LLSD::TypeString: ostr.put('s'); formatString(data.asStringRef(), ostr); break; case LLSD::TypeDate: { ostr.put('d'); F64 value = data.asReal(); ostr.write((const char*)(&value), sizeof(F64)); break; } case LLSD::TypeURI: ostr.put('l'); formatString(data.asString(), ostr); break; case LLSD::TypeBinary: { ostr.put('b'); const std::vector<U8>& buffer = data.asBinary(); U32 size_nbo = htonl(buffer.size()); ostr.write((const char*)(&size_nbo), sizeof(U32)); if(buffer.size()) ostr.write((const char*)&buffer[0], buffer.size()); break; } default: // *NOTE: This should never happen. ostr.put('!'); break; } return format_count; }
int preprocess_newclient(int conn_s, int udpsock0, int *version, double *capacityup, double *capacitydown, struct sockaddr_in *from, char *tracefile, FILE *fp, const char *filename) { int ret = 0; pheader hdr; pnewclientack pnewack; pcapestack pcapack; pnewclientpacket pnewclient; int szhdr = sizeof(struct _header); while(1) { ret = readwrapper(conn_s, (char *)&hdr, szhdr); if(ret == -1) { fprintf(stderr, "SERV: error reading from client: %d\n", conn_s); close(conn_s); return -1; } switch(hdr.ptype) { case P_NEWCLIENT: ret = readwrapper(conn_s, (char *)&pnewclient + szhdr, sizeof(struct _newclientpkt) - szhdr); if(ret == -1) { fprintf(stderr, "SERV: error reading from client: %d\n", conn_s); close(conn_s); unlink(filename); return -1; } //TB_RATE_AVG_INTERVAL = pnewclient.delta; *version = ntohl(pnewclient.version); pnewack.compatibilityFlag = (ntohl(pnewclient.version) >= VERSION /*|| ntohl(pnewclient.version) == 1*/) ? 1 : 0; pnewack.header.ptype = P_NEWCLIENT_ACK; pnewack.header.length = 0; ret = writewrapper(conn_s, (char *)&pnewack, sizeof(struct _newclientack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", conn_s); close(conn_s); unlink(filename); return -1; } fprintf(fp, "Client version: %d\n", ntohl(pnewclient.version)); if(pnewack.compatibilityFlag == 0) { close(conn_s); return -1; } break; case P_CAPEST_START: pcapack.header.ptype = P_CAP_ACK; pcapack.header.length = 0; pcapack.capacity = pcapack.finalflag = 0; pcapack.trainlength = htonl(TRAIN_LENGTH); ret = writewrapper(conn_s, (char *)&pcapack, sizeof(struct _capestack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", conn_s); close(conn_s); return -1; } *capacityup = capacityEstimation(conn_s, udpsock0, from, fp); *capacitydown = estimateCapacity(conn_s, udpsock0, from); return 0; break; default: fprintf(stderr, "unknown packet type!\n"); close(conn_s); unlink(filename); return -1; break; } } return 0; }
void main() { int ret; int i, j, k, maxfd, listenfd, connfd; // int sockfd[LISTENQ]; int reuse = 1; fd_set rset, wset; char buf[WAN_MSG_MAX_SIZE]; char cmd_buf[WAN_MSG_MAX_SIZE]; char tmp_buf[WAN_MSG_MAX_SIZE]; char * tmp_buf_pointer; char * endptr; char opt[64]; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; uint16_t csum; uint16_t msg_size_net; uint16_t msg_size; signal(SIGPIPE, sig_pipe_handler); listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd < 0) { perror("socket"); exit(1); } if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { perror("setsockopet"); exit(1); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(WAN_PORT); if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind"); exit(1); } listen(listenfd, LISTENQ); maxfd = listenfd; /* initialize */ do { clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); socket_alive = 1; while(socket_alive) { FD_ZERO(&rset); FD_SET(connfd, &rset); maxfd = connfd; switch(select(maxfd+1, &rset, NULL, NULL, NULL)) { case -1: socket_alive = 0; close(connfd); break; case 0: break; default: #ifdef WANP if(recv(connfd, buf, WAN_HEADER_SIZE, MSG_WAITALL) != WAN_HEADER_SIZE) { perror("recv"); close(connfd); break; } Wan_GetSize(buf, &msg_size); if(recv(connfd, buf + WAN_HEADER_SIZE, msg_size - WAN_HEADER_SIZE, MSG_WAITALL) != msg_size - WAN_HEADER_SIZE) { perror("recv"); close(connfd); break; } if(Wan_CheckMsg(buf, msg_size) < 0) { perror("wan message check error"); close(connfd); break; } #else for(i = 0; i < WAN_MSG_MAX_SIZE; i++) { if(recv(connfd, buf+i, 1, 0) != 1) { perror("recv"); close(connfd); break; } if('\n' == buf[i]) { msg_size = i + 1; break; } } #endif buf[msg_size] = '\0'; GetCmd(buf, cmd_buf); // printf("cmd: %s\n", cmd_buf); // printf("cmd(buf): %s\n", buf); *tmp_buf = '\0'; if(strcmp(cmd_buf, Hello.Name) == 0) { ret = DoHello(buf); if(0 == ret) { RespOK(buf, cmd_buf, NULL); } else if(HELP_HELLO == ret) { tmp_buf_pointer = tmp_buf; tmp_buf_pointer += sprintf(tmp_buf_pointer, "hello: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " a test message to confirm connection.\r\n"); RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "hello err"); } } else if(strcmp(cmd_buf, Burn.Name) == 0) { ret = DoBurn(buf, kernel_name, addr, kernel_size, crc); if(ret == 0) { if('0' == addr[0] && ('x' == addr[1] || 'X' == addr[1])) { i_addr = strtol((const char *)addr, &endptr, 16); } else { i_addr = atoi((const char *)addr); } if('0' == kernel_size[0] && ('x' == kernel_size[1] || 'X' == kernel_size[1])) { i_kernel_size = strtol((const char *)kernel_size, &endptr, 16); } else { i_kernel_size = atoi((const char *)kernel_size); } if('0' == crc[0] && ('x' == crc[1] || 'X' == crc[1])) { i_crc = strtol((const char *)crc, &endptr, 16); } else { i_crc = atoi((const char *)crc); } // i_addr = atoi(addr); // i_kernel_size = atoi(kernel_size); // i_crc = atoi(crc); // printf("i_addr: %d\n", i_addr); // printf("i_kernel_size: %d\n", i_kernel_size); // printf("i_crc: %d\n", i_crc); printf("u_addr:u_kernel_size:u_crc=%08x:%08x:%08x\r\n", i_addr, i_kernel_size, i_crc); RespOK(buf, cmd_buf, NULL); } else if(HELP_BURN == ret) { tmp_buf_pointer = tmp_buf; tmp_buf_pointer += sprintf(tmp_buf_pointer, "burn: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " burn kernel to specific address.\r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " -f\r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " -a\r\n"); RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "paramter err"); } } else if(strcmp(cmd_buf, Startos.Name) == 0) { ret = DoStartos(buf); if(0 == ret) { RespOK(buf, cmd_buf, NULL); } else if(HELP_STARTOS == ret) { tmp_buf_pointer = tmp_buf; // j = sprintf(tmp_buf_pointer, "startos: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, "startos: \r\n"); // tmp_buf_pointer += j; tmp_buf_pointer += sprintf(tmp_buf_pointer, " launch the OS kernel.\r\n"); *tmp_buf_pointer = '\0'; RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "startos err"); } } else { RespErr(buf, cmd_buf, "Command not found"); } if((msg_size = SealPacket(buf)) < 0) { printf("SealPacket error\r\n"); break; } printf("send: "); for(i = 0; i < msg_size; i++) { printf("%c", buf[i]); } printf("###\n"); if(send(connfd, buf, msg_size, 0) < 0) { perror("send"); close(connfd); break; } printf("\n"); } } }while(1); }
double capacityEstimation_pairs(int tcpsock) { extern int udpsock0; char buf[2000]; int ret1 = 0, ret2 = 0; struct timeval t1, t2, tout; double gap = 0; double cap = -1, mindcap = -1; pcapestack pcapack; pcapack.header.ptype = P_CAP_ACK; pcapack.header.length = 4; int ret = 0; int niters = 0, nfound = 0; double mindelay1 = INT_MAX; double mindelay2 = INT_MAX; double mindelaysum = INT_MAX; double owd1 = 0, owd2 = 0; int mindflag1, mindflag2, mindsumflag; fd_set readset; int maxfd = (udpsock0 > tcpsock) ? udpsock0+1 : tcpsock+1; while(1) { niters++; mindflag1 = mindflag2 = mindsumflag = 0; cap = ret1 = ret2 = -1; FD_ZERO(&readset); FD_SET(udpsock0, &readset); tout.tv_sec = 1; tout.tv_usec = 0; ret = select(maxfd, &readset, NULL, NULL, &tout); if(ret < 0) { fprintf(stderr, "select error\n"); return -1; } else if(ret == 0) { goto noudp; } if(FD_ISSET(udpsock0, &readset)) { ret1 = recv(udpsock0, buf, 2000, 0); if(ret1 == -1) { fprintf(stderr, "recv error on UDP\n"); return -1; } #ifndef OSX if (ioctl(udpsock0, SIOCGSTAMP, &t1) < 0) { perror("ioctl-SIOCGSTAMP"); gettimeofday(&t1,NULL); } #else gettimeofday(&t1, NULL); #endif owd1 = fabs(-1e3*(*(double *)buf - (t1.tv_sec + t1.tv_usec/1.0e6))); mindflag1 = (mindelay1 > owd1) ? 1 : 0; mindelay1 = (mindelay1 > owd1) ? owd1 : mindelay1; } FD_ZERO(&readset); FD_SET(udpsock0, &readset); tout.tv_sec = 10; tout.tv_usec = 0; ret = select(maxfd, &readset, NULL, NULL, &tout); if(ret < 0) { fprintf(stderr, "select error\n"); return -1; } else if(ret == 0) { goto noudp; } if(FD_ISSET(udpsock0, &readset)) { ret2 = recv(udpsock0, buf, 2000, 0); if(ret2 == -1) { fprintf(stderr, "recv error on UDP\n"); return -1; } #ifndef OSX if (ioctl(udpsock0, SIOCGSTAMP, &t2) < 0) { perror("ioctl-SIOCGSTAMP"); gettimeofday(&t2,NULL); } #else gettimeofday(&t2,NULL); #endif owd2 = fabs(-1e3*(*(double *)buf - (t2.tv_sec + t2.tv_usec/1.0e6))); mindflag2 = (mindelay2 > owd2) ? 1 : 0; mindelay2 = (mindelay2 > owd2) ? owd2 : mindelay2; } if(ret1 != ret2 || ret1 == -1 || ret2 == -1) { fprintf(stderr, "sizes %d %d not same OR timeout\n", ret1, ret2); } else { //mindsumflag = (mindelaysum > owd1+owd2) ? 1 : 0; mindelaysum = (mindelaysum > owd1+owd2) ? owd1+owd2 : mindelaysum; mindsumflag = (fabs(owd1+owd2 - (mindelay1+mindelay2)) < 0.01/*0.01*(owd1+owd2)*/) ? 1 : 0; //TODO gap = timeval_diff(t2, t1); //s cap = 1.0e-3*ret1*8.0/gap; //Kbps if(mindsumflag) { mindcap = cap; printf("FOUND!\n"); nfound++; } printf("cap: %.2f Kbps d1:%f d2:%f sum:%f diff:%f\n", cap, owd1, owd2, mindelaysum,fabs(owd1+owd2 - (mindelay1+mindelay2))); } noudp: pcapack.capacity = htonl(cap); pcapack.finalflag = 0; if(niters % 100 == 0 && nfound > 1) { pcapack.finalflag = htonl(1); pcapack.capacity = htonl(mindcap); } ret = writewrapper(tcpsock, (char *)&pcapack, sizeof(struct _capestack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", tcpsock); close(tcpsock); return -1; } pcapack.finalflag = ntonl(pcapack.finalflag); if(pcapack.finalflag == 1) break; if(niters > 1000) break; } return mindcap; }
/** * Implement the SSL server logic. */ static void do_server(int argc, char *argv[]) { int i = 2; uint16_t port = 4433; uint32_t options = SSL_DISPLAY_CERTS; int client_fd; SSL_CTX *ssl_ctx; int server_fd, res = 0; socklen_t client_len; #ifndef CONFIG_SSL_SKELETON_MODE char *private_key_file = NULL; const char *password = NULL; char **cert; int cert_index = 0; int cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); #endif #ifdef WIN32 char yes = 1; #else int yes = 1; #endif struct sockaddr_in serv_addr; struct sockaddr_in client_addr; int quiet = 0; #ifdef CONFIG_SSL_CERT_VERIFICATION int ca_cert_index = 0; int ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); char **ca_cert = (char **)calloc(1, sizeof(char *)*ca_cert_size); #endif fd_set read_set; #ifndef CONFIG_SSL_SKELETON_MODE cert = (char **)calloc(1, sizeof(char *)*cert_size); #endif while (i < argc) { if (strcmp(argv[i], "-accept") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } port = atoi(argv[++i]); } #ifndef CONFIG_SSL_SKELETON_MODE else if (strcmp(argv[i], "-cert") == 0) { if (i >= argc - 1 || cert_index >= cert_size) { print_server_options(argv[i]); } cert[cert_index++] = argv[++i]; } else if (strcmp(argv[i], "-key") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } private_key_file = argv[++i]; options |= SSL_NO_DEFAULT_KEY; } else if (strcmp(argv[i], "-pass") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } password = argv[++i]; } #endif else if (strcmp(argv[i], "-quiet") == 0) { quiet = 1; options &= ~SSL_DISPLAY_CERTS; } #ifdef CONFIG_SSL_CERT_VERIFICATION else if (strcmp(argv[i], "-verify") == 0) { options |= SSL_CLIENT_AUTHENTICATION; } else if (strcmp(argv[i], "-CAfile") == 0) { if (i >= argc - 1 || ca_cert_index >= ca_cert_size) { print_server_options(argv[i]); } ca_cert[ca_cert_index++] = argv[++i]; } #endif #ifdef CONFIG_SSL_FULL_MODE else if (strcmp(argv[i], "-debug") == 0) { options |= SSL_DISPLAY_BYTES; } else if (strcmp(argv[i], "-state") == 0) { options |= SSL_DISPLAY_STATES; } else if (strcmp(argv[i], "-show-rsa") == 0) { options |= SSL_DISPLAY_RSA; } #endif else { /* don't know what this is */ print_server_options(argv[i]); } i++; } if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_SVR_SESS)) == NULL) { fprintf(stderr, "Error: Server context is invalid\n"); exit(1); } #ifndef CONFIG_SSL_SKELETON_MODE if (private_key_file) { int obj_type = SSL_OBJ_RSA_KEY; /* auto-detect the key type from the file extension */ if (strstr(private_key_file, ".p8")) { obj_type = SSL_OBJ_PKCS8; } else if (strstr(private_key_file, ".p12")) { obj_type = SSL_OBJ_PKCS12; } if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)) { fprintf(stderr, "Error: Private key '%s' is undefined.\n", private_key_file); exit(1); } } for (i = 0; i < cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", cert[i]); exit(1); } } #endif #ifdef CONFIG_SSL_CERT_VERIFICATION for (i = 0; i < ca_cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, ca_cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", ca_cert[i]); exit(1); } } free(ca_cert); #endif #ifndef CONFIG_SSL_SKELETON_MODE free(cert); #endif /* Create socket for incoming connections */ if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return; } setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); /* Construct local address structure */ memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */ serv_addr.sin_family = AF_INET; /* Internet address family */ serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ serv_addr.sin_port = htons(port); /* Local port */ /* Bind to the local address */ if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { perror("bind"); exit(1); } if (listen(server_fd, 5) < 0) { perror("listen"); exit(1); } client_len = sizeof(client_addr); /************************************************************************* * This is where the interesting stuff happens. Up until now we've * just been setting up sockets etc. Now we do the SSL handshake. *************************************************************************/ for (;;) { SSL *ssl; int reconnected = 0; if (!quiet) { printf("ACCEPT\n"); TTY_FLUSH(); } if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len)) < 0) { break; } ssl = ssl_server_new(ssl_ctx, client_fd); /* now read (and display) whatever the client sends us */ for (;;) { /* allow parallel reading of client and standard input */ FD_ZERO(&read_set); FD_SET(client_fd, &read_set); #ifndef WIN32 /* win32 doesn't like mixing up stdin and sockets */ if (isatty(STDIN_FILENO)) { /* but only if we are in an active shell */ FD_SET(STDIN_FILENO, &read_set); } if ((res = select(client_fd + 1, &read_set, NULL, NULL, NULL)) > 0) { uint8_t buf[1024]; /* read standard input? */ if (FD_ISSET(STDIN_FILENO, &read_set)) { if (fgets((char *)buf, sizeof(buf), stdin) == NULL) { res = SSL_ERROR_CONN_LOST; } else { /* small hack to check renegotiation */ if (buf[0] == 'r' && (buf[1] == '\n' || buf[1] == '\r')) { res = ssl_renegotiate(ssl); } else { /* write our ramblings to the client */ res = ssl_write(ssl, buf, strlen((char *)buf) + 1); } } } else /* a socket read */ #endif { /* keep reading until we get something interesting */ uint8_t *read_buf; if ((res = ssl_read(ssl, &read_buf)) == SSL_OK) { /* are we in the middle of doing a handshake? */ if (ssl_handshake_status(ssl) != SSL_OK) { reconnected = 0; } else if (!reconnected) { /* we are connected/reconnected */ if (!quiet) { display_session_id(ssl); display_cipher(ssl); } reconnected = 1; } } if (res > SSL_OK) { /* display our interesting output */ int written = 0; while (written < res) { written += write(STDOUT_FILENO, read_buf + written, res - written); } TTY_FLUSH(); } else if (res == SSL_CLOSE_NOTIFY) { printf("shutting down SSL\n"); TTY_FLUSH(); } else if (res < SSL_OK && !quiet) { ssl_display_error(res); } } #ifndef WIN32 } #endif if (res < SSL_OK) { if (!quiet) { printf("CONNECTION CLOSED\n"); TTY_FLUSH(); } break; } } /* client was disconnected or the handshake failed. */ ssl_free(ssl); SOCKET_CLOSE(client_fd); } ssl_ctx_free(ssl_ctx); }
double capacityEstimation(int tcpsock, int udpsock0, struct sockaddr_in *from, FILE *fp) { char buf[2000]; int ret1 = 0, sz = 0; struct timeval ts, tstart, tend, tout; struct timeval tsend[TRAIN_LENGTH], trecv[TRAIN_LENGTH]; int seq[TRAIN_LENGTH]; double gap = 0; double cap = -1, mediancap = -1; pcapestack pcapack; pcapack.header.ptype = P_CAP_ACK; pcapack.header.length = 0; int ret = 0, count = 0, niters = 0, nrecvd = 0; fd_set readset; int maxfd = (udpsock0 > tcpsock) ? udpsock0+1 : tcpsock+1; double caps[10*NITERATIONS], validcaps[10*NITERATIONS]; memset(caps, 0, 10*NITERATIONS*sizeof(double)); memset(validcaps, 0, 10*NITERATIONS*sizeof(double)); int validsz = 0; int ULSZ = sizeof(unsigned long), UCSZ = sizeof(unsigned char); while(1) { niters++; cap = ret1 = sz = -1; tstart.tv_sec = tstart.tv_usec = tend.tv_sec = tend.tv_usec = -1; memset(tsend, 0, TRAIN_LENGTH*sizeof(struct timeval)); memset(trecv, 0, TRAIN_LENGTH*sizeof(struct timeval)); nrecvd = 0; for(count = 0; count < TRAIN_LENGTH; count++) { FD_ZERO(&readset); FD_SET(udpsock0, &readset); tout.tv_sec = 1; tout.tv_usec = 0; ret = select(maxfd, &readset, NULL, NULL, &tout); if(ret < 0) { fprintf(stderr, "select error\n"); return -1; } else if(ret == 0) { break; } if(FD_ISSET(udpsock0, &readset)) { unsigned int fromlen = sizeof(struct sockaddr_in); ret1 = recvfrom(udpsock0, buf, 2000, 0, (struct sockaddr *)from, &fromlen); if(ret1 == -1) { fprintf(stderr, "recv error on UDP\n"); return -1; } #ifndef OSX if (ioctl(udpsock0, SIOCGSTAMP, &ts) < 0) { perror("ioctl-SIOCGSTAMP"); gettimeofday(&ts,NULL); } #else gettimeofday(&ts, NULL); #endif if(tstart.tv_sec == -1) tstart = ts; tend = ts; sz = ret1; seq[count] = buf[0]; trecv[count] = ts; tsend[count].tv_sec = ntohl(*(unsigned long *)((char *)buf +UCSZ)); tsend[count].tv_usec = ntohl(*(unsigned long *)((char *)buf +UCSZ+ULSZ)); nrecvd++; } } fprintf(fp, "### TRAIN ###\n"); for(count = 0; count < TRAIN_LENGTH; count++) { fprintf(fp, "%f %f %d\n", tsend[count].tv_sec+tsend[count].tv_usec*1e-6, trecv[count].tv_sec+trecv[count].tv_usec*1e-6, seq[count]); } fprintf(fp, "\n"); gap = timeval_diff(tend, tstart); //s if(sz != -1 && gap != 0) { cap = 1.0e-3*(nrecvd-1)*(sz+UDPIPHEADERSZ)*8.0/gap; //Kbps //printf("cap: %.2f Kbps\n", cap); //printf("."); fflush(stdout); } caps[niters-1] = cap; pcapack.capacity = htonl(cap); pcapack.finalflag = 0; pcapack.trainlength = htonl(TRAIN_LENGTH); if(niters % NITERATIONS == 0) { pcapack.finalflag = htonl(1); break; } if(niters > 10*NITERATIONS) break; ret = writewrapper(tcpsock, (char *)&pcapack, sizeof(struct _capestack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", tcpsock); close(tcpsock); return -1; } } for(ret1=0; ret1<10*NITERATIONS; ret1++) { if(caps[ret1] == -1 || caps[ret1] == 0) continue; validcaps[validsz] = caps[ret1]; validsz++; } int compd(const void *a, const void *b); qsort((void *)validcaps, validsz, sizeof(double), compd); mediancap = validcaps[(int)floor(validsz/2.0)]; pcapack.finalflag = htonl(1); pcapack.capacity = htonl(mediancap); ret = writewrapper(tcpsock, (char *)&pcapack, sizeof(struct _capestack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", tcpsock); close(tcpsock); return -1; } return mediancap; }
void * thread_read_write (void *arg) { struct thread_info *info = (struct thread_info *) arg; int i, ret; int id, fd; /* for request */ u_int32_t reqx, reqy; unsigned long boffset, nblock; struct sockaddr_in *serv_addr; struct key_request_packet kreq; /* for read */ u_int32_t resx, resy; struct sockaddr_in addr; socklen_t addrlen; struct key_response_packet kresp; int kresperr, krespsuberr, krespkeylen; struct timeval start, end, res; double time; int success; unsigned long send_count, read_count; id = info->id; memset (&info->stats, 0, sizeof (struct horus_stats)); send_count = read_count = 0; fd = socket (PF_INET, SOCK_DGRAM, 0); if (fd < 0) { printf ("thread[%d]: Unable to open socket!: %s\n", id, strerror (errno)); return NULL; } serv_addr = info->serv_addr; boffset = info->boffset; nblock = info->nblock; memset (&kreq, 0, sizeof (kreq)); reqx = info->level; kreq.x = htonl (reqx); strncpy (kreq.filename, info->filename, sizeof (kreq.filename)); if (benchmark || horus_verbose) printf ("thread[%d]: server %s:%d bsize %d boffset %lu nblock %lu\n", id, info->server, ntohs (serv_addr->sin_port), HORUS_BLOCK_SIZE, boffset, nblock); if (spinwait) { fcntl (fd, F_SETFL, O_NONBLOCK); printf ("thread[%d]: spinwait: usleep %d nanosleep %ld " "nsend %d nread %d\n", id, useconds, nanoseconds, nsend, nread); } if (benchmark) gettimeofday (&start, NULL); for (i = 0; i < nblock; i++) { reqy = boffset + i; kreq.y = htonl (reqy); success = 0; send_count = nsend; do { ret = sendto (fd, &kreq, sizeof (key_request_packet), 0, (struct sockaddr *) serv_addr, sizeof (struct sockaddr_in)); send_count--; if (ret != sizeof (key_request_packet)) { if (horus_debug) printf ("thread[%d]: sendto(): failed: %d " "send_count: %ld\n", id, ret, send_count); info->stats.sendfail++; continue; } else { if (horus_debug) printf ("thread[%d]: request %d,%d send_count: %ld\n", id, reqx, reqy, send_count); } read_count = nread; do { if (spinwait) { if (useconds) usleep (useconds); if (nanoseconds) { struct timespec nanospec; nanospec.tv_sec = 0; nanospec.tv_nsec = nanoseconds; nanosleep (&nanospec, NULL); } } addrlen = sizeof (struct sockaddr_in); ret = recvfrom (fd, &kresp, sizeof (key_response_packet), 0, (struct sockaddr *) &addr, &addrlen); read_count--; if (ret != sizeof (key_response_packet)) { if (horus_debug) printf ("thread[%d]: recvfrom(): failed: %d " "read_count: %ld\n", id, ret, read_count); info->stats.recvfail++; continue; } else { if (horus_debug) printf ("thread[%d]: recvfrom(): received %d\n", id, ret); resx = ntohl (kresp.x); resy = ntohl (kresp.y); if (resx == reqx && resy == reqy) success++; else { if (horus_debug) printf ("thread[%d]: mismatch: " "req: %d,%d: resp: %d,%d\n", id, reqx, reqy, resx, resy); info->stats.resmismatch++; } } } while (! success && read_count > 0); } while (! success && send_count > 0); info->stats.sendretry += nsend - send_count - 1; info->stats.recvretry += nread - read_count - 1; if (! success) { if (horus_verbose) printf ("thread[%d]: give up K_%d,%d: resend: %lu reread: %lu\n", id, reqx, reqy, send_count, read_count); info->stats.giveup++; continue; } info->stats.success++; kresperr = (int) ntohs (kresp.err); krespsuberr = (int) ntohs (kresp.suberr); krespkeylen = (int) ntohl (kresp.key_len); horus_stats_record (&info->stats, kresperr, krespsuberr); if (horus_verbose && ! benchmark) { if (kresperr) printf ("thread[%d]: err = %d : %s\n", id, kresperr, horus_strerror (kresperr)); if (krespsuberr) printf ("thread[%d]: suberr = %d : %s\n", id, krespsuberr, strerror (krespsuberr)); if (! kresperr) printf ("thread[%d]: key_%d,%d: key_%d,%d/%d = %s\n", id, reqx, reqy, resx, resy, krespkeylen, print_key (kresp.key, krespkeylen)); } if (simulate && ! kresperr) { char key[HORUS_MAX_KEY_LEN]; size_t key_len; int simx, simy; unsigned long sboffset, snblock; u_int32_t *kht_block_size; int j; assert (reqx == resx && reqy == resy); simx = info->leaf_level; kht_block_size = info->kht_block_size; sboffset = resy * (kht_block_size[resx] / kht_block_size[simx]); snblock = kht_block_size[resx]; if (resx == info->leaf_level) { info->stats.keycalculated = info->stats.success; } else { for (j = 0; j < snblock; j++) { simy = sboffset + j; key_len = sizeof (key); horus_block_key (key, &key_len, simx, simy, kresp.key, krespkeylen, resx, resy, kht_block_size); info->stats.keycalculated++; if (horus_verbose && ! benchmark) printf ("thread[%d]: simulated: K_%d,%d = %s\n", id, simx, simy, print_key (key, key_len)); } } } } if (benchmark) gettimeofday (&end, NULL); close (fd); if (benchmark) { timeval_sub (&end, &start, &res); time = res.tv_sec + res.tv_usec * 0.000001; info->timeval = res; printf ("thread[%d]: %llu/%lu keys in %f secs ( %f q/s\n", id, info->stats.success, nblock, time, info->stats.success/time); if (simulate) printf ("thread[%d]: %llu keys calculated in %f secs ( %f q/s\n", id, info->stats.keycalculated, time, info->stats.keycalculated/time); } else if (horus_verbose) { printf ("thread[%d]: %llu/%lu keys processed.\n", id, info->stats.success, nblock); if (simulate) printf ("thread[%d]: %llu keys calculated\n", id, info->stats.keycalculated); } return NULL; }
int main (int argc, char const * argv []) { sockaddr_in_t server_address, client_address; int sockfd, i; socklen_t server_len = sizeof(server_address), received_length; thing_p_t buffer = (thing_p_t)malloc(sizeof(thing_t)); // create a UDP Server if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { commit_suicide("socket()"); } // zero out the structure memset((char *)&server_address, 0, server_len); // set family, address and port server_address.sin_family = AF_INET; server_address.sin_port = htons(PORT); server_address.sin_addr.s_addr = htonl(INADDR_ANY); // bind socket to port if (bind(sockfd, (sockaddr_p_t)&server_address, server_len) == -1) { commit_suicide("bind()"); } while (YES) { printf("Server waiting...\n"); // blocking call; try to get some data from the client? if ((received_length = recvfrom(sockfd, buffer, BUFLEN, 0, (sockaddr_p_t)&client_address, &server_len)) == -1) { commit_suicide("recvfrom()"); } printf("Client [%s:%d] requested: %.2lf %c %.2lf\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buffer->a, buffer->op, buffer->b); switch (buffer->op) { case ADD: buffer->r = buffer->a + buffer->b; break; case SUB: buffer->r = buffer->a - buffer->b; break; case MUL: buffer->r = buffer->a * buffer->b; break; case DIV: buffer->r = buffer->a / buffer->b; break; case MOD: buffer->r = buffer->a / buffer->b; break; default: break; } // reply to client with the same data, cause echo server. if (sendto(sockfd, buffer, BUFLEN, 0, (sockaddr_p_t)&client_address, server_len) == -1) { commit_suicide("sendto()"); } } close(sockfd); return 0; }
void bench(char* proj, int cache, int image) { struct sockaddr_in server; struct sockaddr_in client; struct hostent h; int i, res_len, client_socket; common_work_t work; void *res_buf; unsigned char *image24; clock_t ticks1, ticks2, ticks3; tfloat t; ticks1 = clock(); tienet_sem_init(&bench_net_sem, 0); printf("loading and prepping ...\n"); /* Camera with no threads */ util_camera_init(&camera, 1); /* Parse Env Data */ common_db_load(&db, proj); /* * Hack the environment settings to make it think there is no cache file * if the user is generating one, otherwise it never generates one */ if (cache) db.env.kdtree_cache_file[0] = 0; /* Read the data off disk and pack it */ app_size = common_pack(&db, &app_data, proj); /* Launch a networking thread to do ipc data streaming */ pthread_create(&bench_thread, NULL, bench_ipc, 0); /* Parse the data into memory for rendering */ /* create a socket */ if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "unable to create socket, exiting.\n"); exit(1); } /* Bind any available port number */ client.sin_family = AF_INET; client.sin_addr.s_addr = htonl(INADDR_ANY); client.sin_port = htons(0); if (bind(client_socket, (struct sockaddr *)&client, sizeof(client)) < 0) { fprintf(stderr, "unable to bind socket, exiting\n"); exit(1); } /* Establish ipc connection */ if (gethostbyname("localhost")) { h = gethostbyname("localhost")[0]; } else { fprintf(stderr, "unknown host: %s\n", "localhost"); exit(1); } server.sin_family = h.h_addrtype; memcpy((char *)&server.sin_addr.s_addr, h.h_addr_list[0], h.h_length); server.sin_port = htons(LOCAL_PORT); tienet_sem_wait(&bench_net_sem); if (connect(client_socket, (struct sockaddr *)&server, sizeof(server)) < 0) { fprintf(stderr, "cannot establish connection, exiting.\n"); exit(1); } /* stream and unpack the data */ common_unpack(&db, &tie, &camera, client_socket); tie_prep(&tie); /* Prep */ common_env_prep(&db.env); util_camera_prep(&camera, &db); /* Allocate memory for a frame */ bench_frame = malloc(4 * sizeof(tfloat) * db.env.img_w * db.env.img_h); if (!bench_frame) { perror("bench_frame"); exit(1); } memset(bench_frame, 0, 4 * sizeof(tfloat) * db.env.img_w * db.env.img_h); /* Render an image */ work.orig_x = 0; work.orig_y = 0; work.size_x = db.env.img_w; work.size_y = db.env.img_h; work.format = COMMON_BIT_DEPTH_24; printf("rendering ...\n"); res_buf = NULL; ticks2 = clock(); util_camera_render(&camera, &db, &tie, &work, sizeof(common_work_t), &res_buf, &res_len); ticks3 = clock(); printf("prep time: %.3f sec\n", (tfloat)(ticks2 - ticks1) / (tfloat)CLOCKS_PER_SEC); t = (tfloat)(ticks3 - ticks2) / (tfloat)CLOCKS_PER_SEC; printf("render time: %.3f sec\n", t); printf("rays / sec: %d\n", (int)((db.env.img_w * db.env.img_h) / t)); if (image) { image24 = &((unsigned char *)res_buf)[sizeof(common_work_t)]; util_image_save_ppm("dump.ppm", image24, db.env.img_w, db.env.img_h); } close(client_socket); util_camera_free(&camera); free(app_data); free(bench_frame); common_unpack_free(&db); if (cache) { void *kdcache; unsigned int size; FILE *fh; tie_kdtree_cache_free(&tie, &kdcache); memcpy(&size, kdcache, sizeof(unsigned int)); printf("saving kd-tree cache: %d bytes\n", size); fh = fopen("kdtree.cache", "wb"); fwrite(kdcache, size, 1, fh); fclose(fh); free(kdcache); } }
// stores 32 bits in the message, increments the current offset in bytes void CWProtocolStore32(CWProtocolMessage *msgPtr, unsigned int val) { val = htonl(val); CW_COPY_MEMORY(&((msgPtr->msg)[(msgPtr->offset)]), &(val), 4); (msgPtr->offset) += 4; }
int main(int argc, char **argv) { int i, port, pid, listenfd, socketfd, hit; static struct sockaddr_in cli_addr; /* static = initialised to zeros */ static struct sockaddr_in serv_addr; /* static = initialised to zeros */ if (argc < 3 || argc > 3 || !strcmp(argv[1], "-?")) { (void)printf("hint: nweb Port-Number Top-Directory\n\n" "\tnweb is a small and very safe mini web server\n" "\tnweb only servers out file/web pages with extensions named below\n" "\t and only from the named directory or its sub-directories.\n" "\tThere is no fancy features = safe and secure.\n\n" "\tExample: nweb 8181 /home/nwebdir &\n\n\tOnly Supports:"); for (i = 0; extensions[i].ext != 0; i++) { (void)printf(" %s", extensions[i].ext); } (void)printf("\n\tNot Supported: URLs including \"..\", Java, Javascript, CGI\n" "\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev/sbin \n" "\tNo warranty given or implied\n\tNigel Griffiths [email protected]\n"); exit(0); } if (!strncmp(argv[2], "/", 2) || !strncmp(argv[2], "/etc", 5) || !strncmp(argv[2], "/bin", 5) || !strncmp(argv[2], "/lib", 5) || !strncmp(argv[2], "/tmp", 5) || !strncmp(argv[2], "/usr", 5) || !strncmp(argv[2], "/dev", 5) || !strncmp(argv[2], "/sbin", 6)) { (void)printf("ERROR: Bad top directory %s, see nweb -?\n", argv[2]); exit(3); } if (chdir(argv[2]) == -1) { (void)printf("ERROR: Can't Change to directory %s\n", argv[2]); exit(4); } /* Become deamon + unstopable and no zombies children (= no wait()) */ if (fork() != 0) { /* parent returns OK to shell */ return 0; } /* ignore child death */ (void)signal(SIGCHLD, SIG_IGN); /* ignore terminal hangups */ (void)signal(SIGHUP, SIG_IGN); for (i = 0; i < 32; i++) { /* close open files */ (void)close(i); } /* break away from process group */ (void)setpgrp(); jr_log(LOG, "nweb starting", argv[1], getpid()); /* setup the network socket */ if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { jr_log(ERROR, "system call", "socket", 0); } port = atoi(argv[1]); if (port < 0 || port > 60000) { jr_log(ERROR, "Invalid port number (try 1->60000)", argv[1], 0); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(port); if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { jr_log(ERROR, "system call", "bind", 0); } if (listen(listenfd, 64) < 0) { jr_log(ERROR, "system call", "listen", 0); } for (hit = 1;; hit++) { socklen_t length = sizeof(cli_addr); if ((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0) { jr_log(ERROR, "system call", "accept", 0); } if ((pid = fork()) < 0) { jr_log(ERROR, "system call", "fork", 0); } else { if (pid == 0) { /* child */ (void)close(listenfd); web(socketfd, hit); /* never returns */ } else { /* parent */ (void)close(socketfd); } } } }
//扫描一个网段 void scan_segment(char *argv[]){ //目的ip struct in_addr dest_ip; pthread_t *pthreads; int port_len,pthread_num; int i; //扫描主机端口的最大值 int max_port; //起始ip地址,结束ip地址 uint32_t begin_ip,end_ip; int argc = 0; while(argv[argc]) ++argc; if(argc != 9){ printf("Usage: [-b] [begin_ip] [-e] [end_ip] [-m] [max_port] [-n] [thread_num]\n"); exit(-1); } for(i=1;i<argc;++i){ if(strcmp("-m",argv[i]) == 0){ max_port = atoi(argv[i+1]); if(max_port<0 || max_port> 65535){ printf("Usage:Invalid port number\n"); exit(-1); } ++i; } if(strcmp("-b",argv[i]) == 0){ if(inet_aton(argv[i+1],&dest_ip) == 0){ printf("Usage:Invalid ip address\n"); exit(-1); } begin_ip = ip_to_uint32_t(argv[i+1]); ++i; } if(strcmp("-e",argv[i]) == 0){ if(inet_aton(argv[i+1],&dest_ip) == 0){ printf("Usage:Invalid ip address\n"); exit(-1); } end_ip = ip_to_uint32_t(argv[i+1]); ++i; } if(strcmp("-n",argv[i]) == 0){ if((pthread_num = atoi(argv[i+1])) < 0){ printf("Usage:Invalid thread address\n"); exit(-1); } } } if(max_port+1 < pthread_num){ pthread_num = max_port+1; } i = 0; while((max_port+1+i) % pthread_num != 0){ ++i; } port_len = (max_port+1+i)/pthread_num; char ip_str[256]; for(;begin_ip <= end_ip;++begin_ip){ uint32_t_to_ip(begin_ip,ip_str); /* if(ping(ip_str) == 0){ printf("%s\n",ip_str); continue; }*/ //printf("scanning ... %s\n",ip_str); pthreads = (pthread_t *)malloc(sizeof(pthread_t)*pthread_num); port_info *pi; pi = (port_info *)malloc(sizeof(port_info)*pthread_num); for(i=0;i<pthread_num;++i){ pi[i].dest_ip.s_addr = htonl(begin_ip); pi[i].begin_port = i*port_len; if(i == pthread_num -1){ pi[i].end_port = max_port; }else{ pi[i].end_port = pi[i].begin_port +port_len-1; } pthread_create(&pthreads[i],NULL,scanner,(void *)&pi[i]); } for(i=0;i<pthread_num;++i){ pthread_join(pthreads[i],NULL); } free(pthreads); free(pi); } }
/** * tso_start_new_packet - generate a new header and prepare for the new packet * @tx_queue: Efx TX queue * @skb: Socket buffer * @st: TSO state * * Generate a new header and prepare for the new packet. Return 0 on * success, or -1 if failed to alloc header. */ static int tso_start_new_packet(struct efx_tx_queue *tx_queue, const struct sk_buff *skb, struct tso_state *st) { struct efx_tso_header *tsoh; struct tcphdr *tsoh_th; unsigned ip_length; u8 *header; /* Allocate a DMA-mapped header buffer. */ if (likely(TSOH_SIZE(st->header_len) <= TSOH_STD_SIZE)) { if (tx_queue->tso_headers_free == NULL) { if (efx_tsoh_block_alloc(tx_queue)) return -1; } EFX_BUG_ON_PARANOID(!tx_queue->tso_headers_free); tsoh = tx_queue->tso_headers_free; tx_queue->tso_headers_free = tsoh->next; tsoh->unmap_len = 0; } else { tx_queue->tso_long_headers++; tsoh = efx_tsoh_heap_alloc(tx_queue, st->header_len); if (unlikely(!tsoh)) return -1; } header = TSOH_BUFFER(tsoh); tsoh_th = (struct tcphdr *)(header + SKB_TCP_OFF(skb)); /* Copy and update the headers. */ memcpy(header, skb->data, st->header_len); tsoh_th->seq = htonl(st->seqnum); st->seqnum += skb_shinfo(skb)->gso_size; if (st->out_len > skb_shinfo(skb)->gso_size) { /* This packet will not finish the TSO burst. */ ip_length = st->full_packet_size - ETH_HDR_LEN(skb); tsoh_th->fin = 0; tsoh_th->psh = 0; } else { /* This packet will be the last in the TSO burst. */ ip_length = st->header_len - ETH_HDR_LEN(skb) + st->out_len; tsoh_th->fin = tcp_hdr(skb)->fin; tsoh_th->psh = tcp_hdr(skb)->psh; } if (st->protocol == htons(ETH_P_IP)) { struct iphdr *tsoh_iph = (struct iphdr *)(header + SKB_IPV4_OFF(skb)); tsoh_iph->tot_len = htons(ip_length); /* Linux leaves suitable gaps in the IP ID space for us to fill. */ tsoh_iph->id = htons(st->ipv4_id); st->ipv4_id++; } else { struct ipv6hdr *tsoh_iph = (struct ipv6hdr *)(header + SKB_IPV6_OFF(skb)); tsoh_iph->payload_len = htons(ip_length - sizeof(*tsoh_iph)); } st->packet_space = skb_shinfo(skb)->gso_size; ++tx_queue->tso_packets; /* Form a descriptor for this header. */ efx_tso_put_header(tx_queue, tsoh, st->header_len); return 0; }
static int bt_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user) { struct cmsghdr *cmsg; struct msghdr msg; struct iovec iv; ssize_t ret; struct pcap_pkthdr pkth; pcap_bluetooth_h4_header* bthdr; bthdr = (pcap_bluetooth_h4_header*) &handle->buffer[handle->offset]; iv.iov_base = &handle->buffer[handle->offset+sizeof(pcap_bluetooth_h4_header)]; iv.iov_len = handle->snapshot; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iv; msg.msg_iovlen = 1; msg.msg_control = handle->buffer; msg.msg_controllen = handle->offset; /* ignore interrupt system call error */ do { ret = recvmsg(handle->fd, &msg, 0); if (handle->break_loop) { handle->break_loop = 0; return -2; } } while ((ret == -1) && (errno == EINTR)); if (ret < 0) { snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't receive packet: %s", strerror(errno)); return -1; } pkth.caplen = ret; /* get direction and timestamp*/ cmsg = CMSG_FIRSTHDR(&msg); int in=0; while (cmsg) { switch (cmsg->cmsg_type) { case HCI_CMSG_DIR: memcpy(&in, CMSG_DATA(cmsg), sizeof in); break; case HCI_CMSG_TSTAMP: memcpy(&pkth.ts, CMSG_DATA(cmsg), sizeof pkth.ts); break; } cmsg = CMSG_NXTHDR(&msg, cmsg); } if ((in && (handle->direction == PCAP_D_OUT)) || ((!in) && (handle->direction == PCAP_D_IN))) return 0; bthdr->direction = htonl(in != 0); pkth.caplen+=sizeof(pcap_bluetooth_h4_header); pkth.len = pkth.caplen; if (handle->fcode.bf_insns == NULL || bpf_filter(handle->fcode.bf_insns, &handle->buffer[handle->offset], pkth.len, pkth.caplen)) { callback(user, &pkth, &handle->buffer[handle->offset]); return 1; } return 0; /* didn't pass filter */ }