int main(void) { int n, fd1[2], fd2[2]; pid_t pid; char line[MAXLINE]; // 创建信号,用于接受SIGPIPE信号,用自定义sig_pipe()函数进行处理. if (signal(SIGPIPE, sig_pipe) == SIG_ERR) { err_sys("signal error"); } // 创建两个管道 if (pipe(fd1) < 0 || pipe(fd2) < 0) { err_sys("pipe error"); } // 创建子进程 if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid > 0) { // 父进程 close(fd1[0]); close(fd2[1]); while (fgets(line, MAXLINE, stdin) != NULL) { // 从标准输入读取数据写入到fd1管道 n = strlen(line); if (write(fd1[1], line, n) != n) { err_sys("write error to pipe"); } if ((n = read(fd2[0], line, MAXLINE)) < 0) { // 从fd2管道读取结果 err_sys("read error from pipe"); } if (n == 0) { err_msg("child closed pipe"); break; } line[n] = 0; if (fputs(line, stdout) == EOF) { err_sys("fputs error"); } } if (ferror(stdin)) { err_sys("fgets error on stdin"); } exit(0); } else { // 子进程 close(fd1[1]); close(fd2[0]); if (fd1[0] != STDIN_FILENO) { if (dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO) { err_sys("dup2 error to stdin"); } close(fd1[0]); } if (fd2[1] != STDOUT_FILENO) { if (dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO) { err_sys("dup2 error to stdout"); } close(fd2[1]); } if (execl("./add2", "add2", (char *)0) < 0) { // 执行过滤程序 err_sys("execl error"); } } exit(0); }
void Bind(int fd, const struct sockaddr *sa, socklen_t salen) { if (bind(fd, sa, salen) < 0) err_sys("bind error"); }
void Getsockname(int fd, struct sockaddr *sa, socklen_t *salenptr) { if (getsockname(fd, sa, salenptr) < 0) err_sys("getsockname error"); }
void Send(int fd, const void *ptr, size_t nbytes, int flags) { if (send(fd, ptr, nbytes, flags) != (ssize_t)nbytes) err_sys("send error"); }
void Shutdown(int fd, int how) { if (shutdown(fd, how) < 0) err_sys("shutdown error"); }
struct ifi_info * get_ifi_info(int family, int doaliases) { struct ifi_info *ifi, *ifihead, **ifipnext; int sockfd, len, lastlen, flags, myflags, idx = 0, hlen = 0; char *ptr, *buf, lastname[IFNAMSIZ], *cptr, *haddr, *sdlname; struct ifconf ifc; struct ifreq *ifr, ifrcopy; struct sockaddr_in *sinptr; struct sockaddr_in6 *sin6ptr; int bufsz; sockfd = Socket(AF_INET, SOCK_DGRAM, 0); lastlen = 0; if (ioctl(sockfd, SIOCGIFIFNUM, &bufsz) > 0) { len = bufsz; } else { len = 100 * sizeof(struct ifreq); /* initial buffer size guess */ } for ( ; ; ) { buf = Malloc(len); ifc.ifc_len = len; ifc.ifc_buf = buf; if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) { if (errno != EINVAL || lastlen != 0) err_sys("ioctl error"); } else { if (ifc.ifc_len == lastlen) break; /* success, len has not changed */ lastlen = ifc.ifc_len; } len += 10 * sizeof(struct ifreq); /* increment */ free(buf); } ifihead = NULL; ifipnext = &ifihead; lastname[0] = 0; sdlname = NULL; /* end get_ifi_info1 */ /* include get_ifi_info2 */ for (ptr = buf; ptr < buf + ifc.ifc_len; ) { ifr = (struct ifreq *) ptr; #ifdef HAVE_SOCKADDR_SA_LEN len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len); #else switch (ifr->ifr_addr.sa_family) { #ifdef IPV6 case AF_INET6: len = sizeof(struct sockaddr_in6); break; #endif case AF_INET: default: len = sizeof(struct sockaddr); break; } #endif /* HAVE_SOCKADDR_SA_LEN */ ptr += sizeof(ifr->ifr_name) + len; /* for next one in buffer */ #ifdef HAVE_SOCKADDR_DL_STRUCT /* assumes that AF_LINK precedes AF_INET or AF_INET6 */ if (ifr->ifr_addr.sa_family == AF_LINK) { struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr; sdlname = ifr->ifr_name; idx = sdl->sdl_index; haddr = sdl->sdl_data + sdl->sdl_nlen; hlen = sdl->sdl_alen; } #endif if (ifr->ifr_addr.sa_family != family) continue; /* ignore if not desired address family */ myflags = 0; if ( (cptr = strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0; /* replace colon with null */ if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) { if (doaliases == 0) continue; /* already processed this interface */ myflags = IFI_ALIAS; } memcpy(lastname, ifr->ifr_name, IFNAMSIZ); ifrcopy = *ifr; Ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy); flags = ifrcopy.ifr_flags; if ((flags & IFF_UP) == 0) continue; /* ignore if interface not up */ /* end get_ifi_info2 */ /* include get_ifi_info3 */ ifi = Calloc(1, sizeof(struct ifi_info)); *ifipnext = ifi; /* prev points to this new one */ ifipnext = &ifi->ifi_next; /* pointer to next one goes here */ ifi->ifi_flags = flags; /* IFF_xxx values */ ifi->ifi_myflags = myflags; /* IFI_xxx values */ #if defined(SIOCGIFMTU) && defined(HAVE_STRUCT_IFREQ_IFR_MTU) Ioctl(sockfd, SIOCGIFMTU, &ifrcopy); ifi->ifi_mtu = ifrcopy.ifr_mtu; #else ifi->ifi_mtu = 0; #endif memcpy(ifi->ifi_name, ifr->ifr_name, IFI_NAME); ifi->ifi_name[IFI_NAME-1] = '\0'; /* If the sockaddr_dl is from a different interface, ignore it */ if (sdlname == NULL || strcmp(sdlname, ifr->ifr_name) != 0) idx = hlen = 0; ifi->ifi_index = idx; ifi->ifi_hlen = hlen; if (ifi->ifi_hlen > IFI_HADDR) ifi->ifi_hlen = IFI_HADDR; if (hlen) memcpy(ifi->ifi_haddr, haddr, ifi->ifi_hlen); /* end get_ifi_info3 */ /* include get_ifi_info4 */ switch (ifr->ifr_addr.sa_family) { case AF_INET: sinptr = (struct sockaddr_in *) &ifr->ifr_addr; ifi->ifi_addr = Calloc(1, sizeof(struct sockaddr_in)); memcpy(ifi->ifi_addr, sinptr, sizeof(struct sockaddr_in)); #ifdef SIOCGIFBRDADDR if (flags & IFF_BROADCAST) { Ioctl(sockfd, SIOCGIFBRDADDR, &ifrcopy); sinptr = (struct sockaddr_in *) &ifrcopy.ifr_broadaddr; ifi->ifi_brdaddr = Calloc(1, sizeof(struct sockaddr_in)); memcpy(ifi->ifi_brdaddr, sinptr, sizeof(struct sockaddr_in)); } #endif #ifdef SIOCGIFDSTADDR if (flags & IFF_POINTOPOINT) { Ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy); sinptr = (struct sockaddr_in *) &ifrcopy.ifr_dstaddr; ifi->ifi_dstaddr = Calloc(1, sizeof(struct sockaddr_in)); memcpy(ifi->ifi_dstaddr, sinptr, sizeof(struct sockaddr_in)); } #endif break; case AF_INET6: sin6ptr = (struct sockaddr_in6 *) &ifr->ifr_addr; ifi->ifi_addr = Calloc(1, sizeof(struct sockaddr_in6)); memcpy(ifi->ifi_addr, sin6ptr, sizeof(struct sockaddr_in6)); #ifdef SIOCGIFDSTADDR if (flags & IFF_POINTOPOINT) { Ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy); sin6ptr = (struct sockaddr_in6 *) &ifrcopy.ifr_dstaddr; ifi->ifi_dstaddr = Calloc(1, sizeof(struct sockaddr_in6)); memcpy(ifi->ifi_dstaddr, sin6ptr, sizeof(struct sockaddr_in6)); } #endif break; default: break; } } free(buf); return(ifihead); /* pointer to first structure in linked list */ }
void Connect(int fd, const struct sockaddr *sa, socklen_t salen) { if ( connect( fd, sa, salen) < 0) err_sys( "connect error"); }
int main ( int argc, char *argv[] ) { struct stat struct_stat; pthread_t pid; pthread_attr_t attr; int i, num_sources; uid_t gmetad_uid; mode_t rrd_umask; char * gmetad_username; struct passwd *pw; char hostname[HOSTNAMESZ]; gmetad_config_t *c = &gmetad_config; apr_interval_time_t sleep_time; apr_time_t last_metadata; double random_sleep_factor; unsigned int rand_seed; /* Ignore SIGPIPE */ signal( SIGPIPE, SIG_IGN ); if (cmdline_parser(argc, argv, &args_info) != 0) err_quit("command-line parser error"); num_sources = number_of_datasources( args_info.conf_arg ); if(!num_sources) { err_quit("%s doesn't have any data sources specified", args_info.conf_arg); } memset(&root, 0, sizeof(root)); root.id = ROOT_NODE; /* Get the real number of data sources later */ sources = hash_create( num_sources + 10 ); if (! sources ) { err_quit("Unable to create sources hash\n"); } root.authority = hash_create( num_sources + 10 ); if (!root.authority) { err_quit("Unable to create root authority (our grids and clusters) hash\n"); } root.metric_summary = hash_create (DEFAULT_METRICSIZE); if (!root.metric_summary) { err_quit("Unable to create root summary hash"); } parse_config_file ( args_info.conf_arg ); /* If given, use command line directives over config file ones. */ if (args_info.debug_given) { c->debug_level = args_info.debug_arg; } debug_level = c->debug_level; set_debug_msg_level(debug_level); /* Setup our default authority pointer if the conf file hasnt yet. * Done in the style of hash node strings. */ if (!root.stringslen) { gethostname(hostname, HOSTNAMESZ); root.authority_ptr = 0; sprintf(root.strings, "http://%s/ganglia/", hostname); root.stringslen += strlen(root.strings) + 1; } rand_seed = apr_time_now() * (int)pthread_self(); for(i = 0; i < root.stringslen; rand_seed = rand_seed * root.strings[i++]); /* Debug level 1 is error output only, and no daemonizing. */ if (!debug_level) { rrd_umask = c->umask; daemon_init (argv[0], 0, rrd_umask); } if (args_info.pid_file_given) { update_pidfile (args_info.pid_file_arg); } /* The rrd_rootdir must be writable by the gmetad process */ if( c->should_setuid ) { if(! (pw = getpwnam(c->setuid_username))) { err_sys("Getpwnam error"); } gmetad_uid = pw->pw_uid; gmetad_username = c->setuid_username; } else { gmetad_uid = getuid(); if(! (pw = getpwuid(gmetad_uid))) { err_sys("Getpwnam error"); } gmetad_username = strdup(pw->pw_name); } debug_msg("Going to run as user %s", gmetad_username); if( c->should_setuid ) { become_a_nobody(c->setuid_username); } if( c->write_rrds ) { if( stat( c->rrd_rootdir, &struct_stat ) ) { err_sys("Please make sure that %s exists", c->rrd_rootdir); } if ( struct_stat.st_uid != gmetad_uid ) { err_quit("Please make sure that %s is owned by %s", c->rrd_rootdir, gmetad_username); } if (! (struct_stat.st_mode & S_IWUSR) ) { err_quit("Please make sure %s has WRITE permission for %s", gmetad_username, c->rrd_rootdir); } } if(debug_level) { fprintf(stderr,"Sources are ...\n"); hash_foreach( sources, print_sources, NULL); } #ifdef WITH_MEMCACHED if (c->memcached_parameters != NULL) { memcached_connection_pool = memcached_pool(c->memcached_parameters, strlen(c->memcached_parameters)); } #endif /* WITH_MEMCACHED */ server_socket = g_tcp_socket_server_new( c->xml_port ); if (server_socket == NULL) { err_quit("tcp_listen() on xml_port failed"); } debug_msg("xml listening on port %d", c->xml_port); interactive_socket = g_tcp_socket_server_new( c->interactive_port ); if (interactive_socket == NULL) { err_quit("tcp_listen() on interactive_port failed"); } debug_msg("interactive xml listening on port %d", c->interactive_port); /* Forward metrics to Graphite using carbon protocol */ if (c->carbon_server != NULL) { if (!strcmp(c->carbon_protocol, "udp")) { carbon_udp_socket = init_carbon_udp_socket (c->carbon_server, c->carbon_port); if (carbon_udp_socket == NULL) err_quit("carbon %s socket failed for %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port); } debug_msg("carbon forwarding ready to send via %s to %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port); } /* initialize summary mutex */ root.sum_finished = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(root.sum_finished, NULL); pthread_attr_init( &attr ); pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); /* Spin off the non-interactive server threads. (Half as many as interactive). */ for (i=0; i < c->server_threads/2; i++) pthread_create(&pid, &attr, server_thread, (void*) 0); /* Spin off the interactive server threads. */ for (i=0; i < c->server_threads; i++) pthread_create(&pid, &attr, server_thread, (void*) 1); hash_foreach( sources, spin_off_the_data_threads, NULL ); /* A thread to cleanup old metrics and hosts */ pthread_create(&pid, &attr, cleanup_thread, (void *) NULL); debug_msg("cleanup thread has been started"); /* Meta data */ last_metadata = 0; for(;;) { /* Do at a random interval, between (shortest_step/2) +/- METADATA_SLEEP_RANDOMIZE percent */ random_sleep_factor = (1 + (METADATA_SLEEP_RANDOMIZE / 50.0) * ((rand_r(&rand_seed) - RAND_MAX/2)/(float)RAND_MAX)); sleep_time = random_sleep_factor * apr_time_from_sec(c->shortest_step) / 2; /* Make sure the sleep time is at least 1 second */ if(apr_time_sec(apr_time_now() + sleep_time) < (METADATA_MINIMUM_SLEEP + apr_time_sec(apr_time_now()))) sleep_time += apr_time_from_sec(METADATA_MINIMUM_SLEEP); apr_sleep(sleep_time); /* Need to be sure root is locked while doing summary */ pthread_mutex_lock(root.sum_finished); /* Flush the old values */ hash_foreach(root.metric_summary, zero_out_summary, NULL); root.hosts_up = 0; root.hosts_down = 0; /* Sum the new values */ hash_foreach(root.authority, do_root_summary, NULL ); /* summary completed */ pthread_mutex_unlock(root.sum_finished); /* Save them to RRD */ hash_foreach(root.metric_summary, write_root_summary, NULL); /* Remember our last run */ last_metadata = apr_time_now(); } return 0; }
int main(int argc, char **argv) { int i, maxi, listenfd, connfd, sockfd; int nready; ssize_t n; char buf[MAXLINE]; socklen_t clilen; struct pollfd client[OPEN_MAX]; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); client[0].fd = listenfd; client[0].events = POLLIN; for (i = 1; i < OPEN_MAX; i++) client[1].fd = -1; maxi = 0; for ( ; ; ) { nready = Poll(client, maxi + 1, INFTIM); if (client[0].revents & POLLIN) /* new client connection */ { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *)&cliaddr, &clilen); for (i = 1; i < OPEN_MAX; i++) if (client[i].fd < 0) { client[i].fd = connfd; /* save descriptor */ break; } if (i == OPEN_MAX) err_quit("too many clients"); client[i].events = POLLIN; if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready <= 0) continue; /* no more readable descriptors */ } for (i = 1; i <= maxi; i++) /* check all clients for data */ { if ((sockfd = client[i].fd) < 0) continue; if (client[i].revents & (POLLIN | POLLERR)) { if ((n = read(sockfd, buf, MAXLINE)) < 0) { if (errno == ECONNRESET) /* connection reset by client */ { Close(sockfd); client[i].fd = -1; } else err_sys("read error"); } else if (n == 0) /* connection closed by client */ { Close(sockfd); client[i].fd = -1; } else Writen(sockfd, buf, n); if (--nready <= 0) /* no more readable descriptors */ break; } } } }
int main(void) { int fd1[2], fd2[2]; pid_t pid; char line[MAXLINE]; FILE *infp, *outfp; if (signal(SIGPIPE, sig_pipe) == SIG_ERR) err_sys("signal error"); if (pipe(fd1) < 0 || pipe(fd2) < 0) err_sys("pipe error"); if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid > 0) { /* parent */ close(fd1[IN]), close(fd2[OUT]); if (((infp = fdopen(fd2[IN], "r")) == NULL) || ((outfp = fdopen(fd1[OUT], "w")) == NULL)) err_sys("fdopen error"); if ((setvbuf(infp, NULL, _IOLBF, 0) != 0) || (setvbuf(outfp, NULL, _IOLBF, 0) != 0)) err_sys("setvbuf error"); while (fgets(line, MAXLINE, stdin) != NULL) { if (fputs(line, outfp) == EOF) err_sys("fputs error"); if (fgets(line, MAXLINE, infp) == NULL) { if (ferror(infp) != 0) err_sys("fgets error"); else err_msg("child closed pipe"); } if (fputs(line, stdout) == EOF) err_sys("fputs error"); } Fclose(infp); Fclose(outfp); if (ferror(stdin)) err_sys("fgets error on stdin"); exit(0); } else { /* child */ close(fd1[OUT]); close(fd2[IN]); if (fd1[IN] != STDIN_FILENO) { if (dup2(fd1[IN], STDIN_FILENO) != STDIN_FILENO) err_sys("dup2 error to stdin"); close(fd1[IN]); } if (fd2[OUT] != STDOUT_FILENO) { if (dup2(fd2[OUT], STDOUT_FILENO) != STDOUT_FILENO) err_sys("dup2 error to stdout"); close(fd2[OUT]); } if (execl("./add2", "add2", (char *)0)) err_sys("execl error"); } exit(0); }
static int init_fpga_task(void) { int j, i; int ans; static int firsttime = TRUE; //enter code /* get home path */ homePath= getenv ("HOME"); ////////////////////////////////////////////////////////////////////////// // Create a MMAP ////////////////////////////////////////////////////////////////////////// #ifdef WIN32 /*// Create a 4K memory-mapped file (MMF) hFile = CreateFile((LPCTSTR) "input.dat", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { // Failed to create file return 1; } map = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 1024, "MMAPShmem"); g_fpga2robot = (char *) MapViewOfFile (map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); */ #else printf("buffer_size: %d\n\n", statbuf.st_size); int fd_i; char* fgpa2robot_FilePath; fgpa2robot_FilePath = strncat(homePath, "/prog/masterUser/src/fpga2robot.dat", 100); //max number of characers to be concatinated :100 if((fd_i = open(fgpa2robot_FilePath, O_RDWR)) == -1) { printf("Couldn't open 'fpga2robot.dat'\n"); } g_fpga2robot = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd_i, 0); if (g_fpga2robot == MAP_FAILED) { close(fd_i); perror("Error mmapping the file"); exit(EXIT_FAILURE); } int fd_o; if((fd_o = open("/home/eric/prog/masterUser/src/robot2fpga.dat", O_RDWR)) == -1) { printf("Couldn't open 'robot2fpga.dat'\n"); } lseek(fd_o, 0, SEEK_SET); g_robot2fpga = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd_o, 0); if (g_robot2fpga == MAP_FAILED) { close(fd_o); perror("Error mmapping the file"); exit(EXIT_FAILURE); } #endif if(g_fpga2robot != NULL) { printf("Wrapper has created a MMAP for file 'fpga2robot.dat'\n"); } if(g_robot2fpga != NULL) { printf("Wrapper has created a MMAP for file 'robot2fpga.dat'\n"); } /* find size of input file */ if (fstat (fd_i, &statbuf) < 0) err_sys ("fstat error"); system("/home/eric/prog/masterUser/src/py/py_mmap.py &"); //end code if (firsttime){ firsttime = FALSE; freq = 0.1; // frequency amp = 0.5; // amplitude } // prepare going to the default posture bzero((char *)&(target[1]),N_DOFS*sizeof(target[1])); for (i=1; i<=N_DOFS; i++) target[i] = joint_default_state[i]; // go to the target using inverse dynamics (ID) if (!go_target_wait_ID(target)) return FALSE; // ready to go ans = 999; while (ans == 999) { if (!get_int("Enter 1 to start or anthing else to abort ...",ans,&ans)) return FALSE; } // only go when user really types the right thing if (ans != 1) return FALSE; start_time = task_servo_time; printf("start time = %.3f, task_servo_time = %.3f\n", start_time, task_servo_time); return TRUE; }
int main(int argc, char argv**) { socklen_t len; int n, listenfd, connfd, char_in, count = 0; struct sockaddr_in servaddr, cliaddr; char buff[40], wbuff[MAXLINE], rbuff[MAXLINE], cmd[16], path1[64]=".", path[64], vers[16]; FILE * hFile; if(argc != 2) { err_quit("usage: a.out <Port>"); } listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.sin_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(atoi(argv[1])); Bind(listenfd, (SA*) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); for( ; ; ) { len = sizeof(cliaddr); connfd = Accept(listenfd, (SA*) &cliaddr, &len); printf("\nConnection from %s, port %d\n", Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)) ntohs(cliaddr.sin_port)); while((n = read(connfd, rbuff, MAXLINE)) > 0) { rbuff[n] = 0; if(fputs(rbuff, stdout) == 0) { err_sys("fputs error"); } if(strstr(rbuff,"\r\n\r\n") > 0) { break; } } if(n < 0) { err_sys("read error"); } sscanf(rbuff, "%s %s %s", cmd, path, vers); strcat(path1, path); if(strcmp(path1, "./") == 0) { strcpy(path1, "./index.html"); } hFile = fopen(path1, "r"); if(hFile == NULL) { hFIle = fopen("error.html", "r"); } strcpy(wbuff,""); while((char_in = fgetc(hFile)) != EOF) { wbuff(count) = char_in; count++; } wbuff(count) = 0; Write(connfd, wbuff, strlen(wbuff)); count = 0; fclose(hFile); strcpy(path1,"."); Close(connfd); } }
int main(int argc, char const *argv[]) { char line[MAXLINE]; FILE *fpout, *fpin; if((fpout = popen("./kbfilter", "w")) == NULL) err_sys("popen error"); //if((fpin = popen("./kbfilter", "r")) == NULL) // err_sys("popen error"); struct termios termios_struct; tcgetattr(STDIN_FILENO, &orig_termios_struct); tcgetattr(STDIN_FILENO, &termios_struct); // could be done like this also: // termios_struct = orig_termios_struct; termios_struct.c_lflag &= (~ICANON) & (~ECHO); termios_struct.c_cc[VTIME] = 0; termios_struct.c_cc[VMIN] = 1; tcsetattr(STDIN_FILENO, TCSANOW, &termios_struct); sleep(1); char c[2]; //while((c = getchar()) != EOF) while((c[0] = getc(stdin)) != EOF) { c[1] = 0; //printf("%s\n", c); if(fputs(c,fpout) == EOF) { tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios_struct); err_sys("fputs error to pipe"); } } tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios_struct); if (ferror(fpout)) //||ferror(fpin)) err_sys("fputs error to pipe"); if(pclose(fpout) == -1) err_sys("pclose fpout error"); //if(pclose(fpin) == -1) // err_sys("pclose fpin error"); /* if((fpin = popen("./kbfilter", "r")) == NULL) err_sys("popen error"); for(;;) { //fputs("prompt> ", stdout); //fflush(stdout); if(fgets(line, MAXLINE, fpin) == NULL) // read from pipe break; if(fputs(line, stdout) == EOF) err_sys("fputs error to pipe"); } if(pclose(fpin) == -1) err_sys("pclose error"); // tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios_struct); */ putchar('\n'); exit(0); }
void receive_cmd(int sockfd) { Writen(sockfd, welcome, sizeof(welcome) - 1); ssize_t n = 0; char buf[MAX_BUFF]; int pipes[MAX_LINE][2]; int line = 0; memset(pipes, -1, sizeof(pipes)); setenv("PATH", "bin:.", TRUE); printf("%s\n" ,getenv("PATH")); int pos = 0; int unknown_command = 0; again: while ( (n = read(sockfd, &buf[pos], MAX_BUFF - pos)) > 0) { if (buf[pos + n - 1] != '\n') { printf("n-1 != newline...\n"); printf("n-1 is (%c), (%x)\n", buf[n-1], buf[n-1]); pos += n; goto again; } else { buf[pos + n] = '\0'; pos = 0; printf("I see newline!!\n"); } char *linv[MAX_LINE]; int linc = parse_line(buf, linv); for (int z = 0; z < linc; z++) { char *cmdv[MAX_CMDS]; int cmdc = parse_cmd(linv[z], cmdv); printf("line: %d\n unknwon: %d\n", line, unknown_command); int fd_in = pipes[line][0]; if (pipes[line][1] != -1 && !unknown_command) { Close(pipes[line][1]); pipes[line][1] = -1; } unknown_command = 0; for (int i = 0; i < cmdc; i++) { printf("cmdv[%d] = %s\n", i, cmdv[i]); char *argv[MAX_ARGS]; int argc = parse_argv(cmdv[i], argv); if (argc == 0) continue; for (int j = 0; j < argc; j++) printf("argv[%d] = %s\n", j, argv[j]); if (strcmp(argv[0], "exit") == 0) return; if (strcmp(argv[0], "printenv") == 0) { for (int j = 1; j < argc; j++) dprintf(sockfd, "%s=%s\n", argv[j], getenv(argv[j])); break; } if (strcmp(argv[0], "setenv") == 0) { if (argc == 3) setenv(argv[1], argv[2], TRUE); else dprintf(sockfd, "usage: setenv KEY VALIE\n"); break; } int fd_out; int fd_errout; int in_out_pipe[2]; int close_fd_out = 1; int close_fd_errout = 1; if (i + 1 < cmdc) { // If there's next command Pipe(in_out_pipe); fd_out = in_out_pipe[1]; fd_errout = in_out_pipe[1]; } else { // This is last one fd_out = sockfd; fd_errout = sockfd; int minus = 0; for (int q = 0; q < argc; q++) { if (strcmp(argv[q], ">") == 0) { fd_out = open(argv[q + 1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); argv[q] = '\0'; argc = q; break; } else if (argv[q][0] == '|' && argv[q][1] != '!') { int dest_pipe = parse_number(&argv[q][1]) + line; printf("dest_pipe std = %d\n", dest_pipe); if (pipes[dest_pipe][1] == -1) Pipe(pipes[dest_pipe]); fd_out = pipes[dest_pipe][1]; close_fd_out = 0; argv[q] = '\0'; minus++; } else if (argv[q][0] == '!' && argv[q][1] != '|') { int dest_pipe = parse_number(&argv[q][1]) + line; printf("dest_pipe err = %d\n", dest_pipe); if (pipes[dest_pipe][1] == -1) Pipe(pipes[dest_pipe]); fd_errout = pipes[dest_pipe][1]; close_fd_errout = 0; argv[q] = '\0'; minus++; } else if ( (argv[q][0] == '!' && argv[q][1] == '|') || (argv[q][0] == '|' && argv[q][1] == '!')) { int dest_pipe = atoi(&argv[q][2]) + line; printf("dest_pipe std+err = %d\n", dest_pipe); if (pipes[dest_pipe][1] == -1) Pipe(pipes[dest_pipe]); fd_out = pipes[dest_pipe][1]; fd_errout = pipes[dest_pipe][1]; argv[q] = '\0'; minus++; } } argc -= minus; } printf("pipe[0]=%d\n", in_out_pipe[0]); printf("pipe[1]=%d\n", in_out_pipe[1]); char exit_code = fork_process(argv, fd_in, fd_out, fd_errout, sockfd); if (close_fd_out && fd_out != sockfd && fd_out != -1) Close(fd_out); if (close_fd_errout && fd_errout != fd_out && fd_errout != sockfd && fd_errout != -1) Close(fd_errout); if (exit_code == ERR_CMD_NOT_FOUND) { dprintf(sockfd, "Unknown command: [%s].\n", argv[0]); unknown_command = 1; break; } else { if (fd_in != -1) Close(fd_in); fd_in = in_out_pipe[0]; } } showSymbol(sockfd); if (!unknown_command) line++; } } if (n < 0 && errno == EINTR) { pos += n; goto again; } else if (n < 0) { err_sys("str_echo: read error"); } }
void err_setout(int fd) { if (dup2(fd, STDERR_FILENO) == -1) err_sys("liberr redirect stderr"); _err_tty = isatty(STDERR_FILENO); }
int main (int argc, char **argv) { int listenfd, connfd, n; struct sockaddr_in servaddr, clientaddr; //char buf[MAXDATASIZE]; char recvline[MAXLINE + 1]; //time_t ticks; char error[MAXLINE + 1]; //para obter o endereço do socket socklen_t addrlen = sizeof(clientaddr); //valor temporario para o id dos processos filhos pid_t child_pid; if (argc != 3) { //caso o usuário não tenha fornecido um IP e a porta para conexão strcpy(error,"uso: "); strcat(error,argv[0]); strcat(error," <Porta> <listen Backlog value"); perror(error); exit(1); } //Inicializa o socket listenfd = Socket(AF_INET, SOCK_STREAM, 0); //Preenche informacoes relativas ao socket do servidor Servaddr(&servaddr, argv[1]); //Associa socket com um ip e uma porta Bind(listenfd, &servaddr); //Diz para o socket ouvir conexoes Listen(listenfd, atoi(argv[2])); //Registra funcao de handler Signal(SIGCHLD, sig_child); //Prepara arquivo de log time_t now; char timeString[256]; FILE *log; while (1){ //Retarda a remoção dos sockets da fila de conexões completas sleep(10); //Aceita uma conexao e atribui a um socket if ((connfd = Accept(listenfd, &clientaddr, &addrlen)) < 0){ if (errno = EINTR){ continue; } else{ err_sys("accept error"); } } //Registra conexao time(&now); strftime (timeString, 256, "%Y-%m-%d %H:%M:%S", localtime(&now)); log = fopen("log.txt","a"); if (log == NULL){ printf ("Failed to log entry.\n"); } else{ fprintf(log,"[%s] %s:%u conectou-se\n", timeString, inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); } fclose(log); // Cria subprocesso que lidara com essa conexao if ((child_pid = fork()) == 0) { //Processo filho //Fecha socket para ouvir novas conexoes close(listenfd); //Imprime o endereço do socket local getsockname(connfd,(struct sockaddr *)&servaddr, &addrlen); printf("Endereço local: %s:%u \n",inet_ntoa(servaddr.sin_addr), ntohs(servaddr.sin_port)); //Imprime o endereço do socket remoto printf("Endereço do cliente: %s:%u \n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); while(1) { //Executa comandos enviados pelo cliente n = read(connfd, recvline, MAXLINE); if (n == 0){ // socket disconnected break; } if (strcmp(recvline,"bye\n") == 0){ break; } else { char outputbuffer[MAXLINE + 1]; recvline[n] = 0; FILE* p = popen(recvline,"r"); if (p == NULL){ printf("Erro executando comando.\n Valor de retorno: %d\n", pclose(p) / 256); } else{ sprintf(outputbuffer, "(%s:%u) %s", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), recvline); printf("%s",outputbuffer); while (fgets(outputbuffer,MAXLINE+1,p)){ //printf("%s",outputbuffer); write(connfd, outputbuffer, strlen(outputbuffer)); } pclose(p); } } } // Registra desconexao time(&now); strftime (timeString, 256, "%Y-%m-%d %H:%M:%S", localtime(&now)); log = fopen("log.txt","a"); if (log == NULL){ printf ("Falha no registro\n"); } else{ fprintf(log,"[%s] %s:%u desconectou-se\n", timeString, inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); } fclose(log); //Fecha socket da conexao printf("Cliente %s:%u desconectou-se.\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); close(connfd); return(0); } printf("Numero do processo filho: %d\n", child_pid); close(connfd); } }
void Fclose(FILE *fp) { if (fclose(fp) != 0) err_sys("fclose error"); }
int recv_v6(int seq, struct timeval *tv) { int hlen2, icmp6len, ret; ssize_t n; socklen_t len; struct ip6_hdr *hip6; struct icmp6_hdr *icmp6; struct udphdr *udp; gotalarm = 0; alarm(3); for ( ; ; ) { if (gotalarm) return -3; /* alarm expired */ len = pr->salen; n = recvfrom(recvfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len); if (n < 0) { /* * EINTR indicates an interrupted system call (maybe by our SIGALRM). * Linux doesn't interrupt recvfrom() so we set a socket timeout option * (in traceloop() function). If recvfrom() times out, it returns * EAGAIN == EWOULDBLOCK */ if (errno == EINTR || errno == EAGAIN) continue; else err_sys("recvfrom() error"); } icmp6 = (struct icmp6_hdr *) recvbuf; /* ICMP header */ if ((icmp6len = n) < 8) continue; /* not enough to look at ICMP header */ if (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED && icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) { if (icmp6len < 8 + sizeof(struct ip6_hdr) + 4) continue; /* not enough data to look at inner header */ hip6 = (struct ip6_hdr *) (recvbuf + 8); /* skip over ICMP header to get to inner IPv6 */ hlen2 = sizeof(struct ip6_hdr); udp = (struct udphdr *) (recvbuf + 8 + hlen2); /* skip over IPv6 header and inner IPv6 to get to inner UDP */ if (hip6->ip6_nxt == IPPROTO_UDP && udp->source == htons(sport) && /* BSD: udp->uh_sport */ udp->dest == htons(dport + seq)) { /* BSD: udp->uh_dport */ ret = -2; /* we hit an intermediate router */ break; } } else if (icmp6->icmp6_type == ICMP6_DST_UNREACH) { if (icmp6len < 8 + sizeof(struct ip6_hdr) + 4) continue; /* not enough data to look at inner header */ hip6 = (struct ip6_hdr *) (recvbuf + 8); /* skip over ICMP header to get to inner IPv6 */ hlen2 = sizeof(struct ip6_hdr); udp = (struct udphdr *) (recvbuf + 8 + hlen2); /* skip over IPv6 header and inner IPv6 to get to inner UDP */ if (hip6->ip6_nxt == IPPROTO_UDP && udp->source == htons(sport) && /* BSD: udp->uh_sport */ udp->dest == htons(dport + seq)) { /* BSD: udp->uh_dport */ if (icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT) ret = -1; /* have reached destination */ else ret = icmp6->icmp6_code; /* 0, 1, 2, ... */ break; } } else if (verbose) { printf(" (from %s: type = %d, code = %d)\n", sock_ntop_host(pr->sarecv, pr->salen), icmp6->icmp6_type, icmp6->icmp6_code); } /* Some other ICMP error, recvfrom() again */ } alarm(0); /* don't leave alarm running */ gettimeofday(tv, NULL); /* get time of packet arrival */ return ret; }
void Dup2(int fd1, int fd2) { if (dup2(fd1, fd2) == -1) err_sys("dup2 error"); }
int main(int argc,char *argv[]) { int listenfd,acceptfd,maxfd,client[MAXSIZE],nread,i,imax; char recvmsg[MAXLINE]; struct sockaddr sa; socklen_t salen; fd_set rset,rsetsave; for(i=0;i<MAXSIZE;i++) client[i] = -1; listenfd = acceptfd = -1; imax = 0; if(argc == 2) listenfd = Tcp_listen(NULL,argv[1],&salen); else if(argc == 3) listenfd = Tcp_listen(argv[1],argv[2],&salen); else err_quit("usage : server02 [<host>] <serv>"); maxfd = listenfd; FD_ZERO(&rsetsave); FD_SET(listenfd,&rsetsave); while(1){ rset = rsetsave; if((nread = select(maxfd+1,&rset,NULL,NULL,NULL)) < 0) err_quit("select error"); if(FD_ISSET(listenfd,&rset)) { if((acceptfd = accept(listenfd,&sa,&salen)) < 0) { if((errno == EINTR)) continue; else err_sys("server02 error in accept!"); }else { for(i=0;i<MAXSIZE;i++){ if(client[i] < 0){ client[i] = acceptfd; break; } } if(i == MAXSIZE) err_quit("reach max client!please wait\n"); FD_SET(acceptfd,&rsetsave); if(acceptfd > maxfd) maxfd = acceptfd; if(i > imax) imax = i; if(--nread <= 0) continue; } } for(i=0;i<=imax;i++){ if(client[i] < 0) continue; if(FD_ISSET(client[i],&rset)) { if((Readline(client[i],recvmsg,MAXLINE)) == 0){ Close(client[i]); FD_CLR(client[i],&rsetsave); client[i] = -1; printf("has disconnect with one socket!\n"); }else { Writen(client[i],recvmsg,strlen(recvmsg)); } if(--nread <= 0) continue; } } } }
void Writen(int fd, void *ptr, size_t nbytes) { if (writen(fd, ptr, nbytes) != nbytes) err_sys("writen error"); }
int main(int argc, char *argv[]) { int fd; struct stat statbuf; pid_t pid; char buf[5]; if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); exit(1); } /* create file by input name */ if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) err_sys("open error"); if (write(fd, "abcdef", 6) < 0) err_sys("write error"); /* * turn on set-group-ID and turn off group-execute * to open mandatory lock */ if (fstat(fd, &statbuf) < 0) err_sys("fstat error"); if (fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) err_sys("fchmod error"); if ((pid = fork()) < 0) err_sys("fork error"); else if (pid > 0) /* parent */ { /* write lock entire file */ if (write_lock(fd, 0, SEEK_SET, 0) < 0) err_sys("write_lock error"); sleep(5); if(waitpid(pid, NULL, 0) < 0) err_sys("waitpid error"); } else /* child */ { sleep(2); /* wait for parent to set lock */ set_fl(fd, O_NONBLOCK); /* first let's see what error we get if region is locked */ if (read_lock(fd, 0, SEEK_SET, 0) != -1) /* no wait */ err_sys("child: read_lock succeeded"); printf("read_lock of already-locked region returns %d\n", errno); /* now try to read the mandatory locked file */ if (lseek(fd, 0, SEEK_SET) < 0) err_sys("lseek error"); if (read(fd, buf, 2) < 0) err_sys("read failed (mandatory locking works)"); else printf("read OK (no mandatory locking), buf = %2.2s\n", buf); } return 0; }
void Setsockopt(int fd, int level, int optname, const void *optval, socklen_t optlen) { if (setsockopt(fd, level, optname, optval, optlen) < 0) err_sys("setsockopt error"); }
struct udpiphdr *dlt_udp_read(void) { const u_char *ptr; int len, size_eth, size_ip; const struct ip *pip; const struct udphdr *pudp; struct udpiphdr *pui; for (;;) { ptr = dlt_next_pcap(&len); switch (linktype) { case 0: size_eth = 4; break; case 1: size_eth = 14; /* 6src + 6dst + 2(length of type) */ break; default: err_quit("can't handle the linktype: %d", linktype); } pip = (struct ip *)(ptr + size_eth); if ((size_ip = pip->ip_hl * 4) < 20) { fprintf(stderr, "* Invalid IP header length: %u bytes\n", size_ip); continue; } if (pip->ip_p == IPPROTO_ICMP) { printf("capture ICMP packet\n"); if ((pui = dlt_icmp_read(ptr + size_eth + size_ip, len - size_eth - size_ip)) != NULL) return pui; else continue; } if (pip->ip_p != IPPROTO_UDP) { fprintf(stderr, "* not UDP packet: protocol = %d\n", pip->ip_p); continue; } if (dlt_cksum((uint16_t *)pip, size_ip) != 0) { /* IP checksum on the header length */ fprintf(stderr, "* IP checksum error\n"); continue; } pudp = (struct udphdr *)(ptr + size_eth + size_ip); if (len - size_eth - size_ip < sizeof(struct udphdr)) { fprintf(stderr, "* Invalid UDP header length: %u bytes\n", len - size_eth - size_ip); continue; } #if (_DEBUG) printf("capture UDP cksum = 0x%x\n", ntohs(pudp->uh_sum)); u_char *payload = (u_char *)(ptr + size_eth + size_ip + sizeof(struct udphdr)); int size_payload = len - size_eth - size_ip - sizeof(struct udphdr); struct pseudo_udphdr pseudo_udphdr; pseudo_udphdr.ip_src = pip->ip_src; pseudo_udphdr.ip_dst = pip->ip_dst; pseudo_udphdr.pad = 0; pseudo_udphdr.ip_p = IPPROTO_UDP; pseudo_udphdr.uh_ulen = pudp->uh_ulen; pseudo_udphdr.udphdr = *pudp; memmove(pseudo_udphdr.data, payload, size_payload); printf(">> calculate UDP checksum = 0x%x\n", dlt_cksum((uint16_t *)&pseudo_udphdr, sizeof(struct in_addr) + /* 4 bytes */ sizeof(struct in_addr) + /* 4 bytes */ sizeof(u_char) + sizeof(u_char) + /* 2 bytes */ sizeof(u_short) + /* 2 bytes */ sizeof(struct udphdr) + /* 8 bytes */ size_payload)); char strsrc[64], strdst[64]; /* Don't use inet_ntoa(), it will share the same pointer */ if (inet_ntop(AF_INET, &pip->ip_src, strsrc, sizeof(strsrc)) == NULL) err_sys("inet_ntop error"); if (inet_ntop(AF_INET, &pip->ip_dst, strdst, sizeof(strdst)) == NULL) err_sys("inet_ntop error"); printf("capture from %s:%d to %s:%d\n", strsrc, ntohs(pudp->uh_sport), strdst, ntohs(pudp->uh_dport)); #endif return (struct udpiphdr *)(ptr + size_eth); } }
void Fputs(const char *ptr, FILE *stream) { if (fputs(ptr, stream) == EOF) err_sys("fputs error"); }
int main(int argc, char **argv) { int ch, whence, n, is_read, is_write; int fd; size_t offset; char buf[BUFFSIZE]; n = 0; offset = 0; whence = SEEK_CUR; while ((ch = getopt(argc, argv, "o:w:R:W:")) != -1) { switch (ch) { case 'o': offset = (size_t) atoi(optarg); break; case 'w': if (strcmp(optarg, "SEEK_SET") == 0) { whence = SEEK_SET; } else if (strcmp(optarg, "SEEK_CUR") == 0) { whence = SEEK_CUR; } else if (strcmp(optarg, "SEEK_END") == 0) { whence = SEEK_END; } else err_quit("unknown whence (%s)", optarg); break; case 'R': if (!is_write) { n = atoi(optarg); is_read = 1; } break; case 'W': if (!is_read) { strncpy(buf, optarg, BUFFSIZE); n = strlen(buf) + 1; is_write = 1; } break; case '?': default: break; } } argc -= optind; if (argc != 1) err_quit("usage: %s [options] <file>", argv[0]); argv += optind; if ((fd = open(argv[0], O_RDWR|O_APPEND|O_CREAT)) == -1) err_sys("open error for %s", argv[0]); if (lseek(fd, offset, whence) == -1) err_sys("lseek error for %d, %s", (int) offset, str_whence(whence)); else printf("lseek (offset: %d, whence: %s)\n", (int) offset, str_whence(whence)); if (is_read) { if (read(fd, buf, n) < 0) err_sys("read error"); printf("read: %s\n", buf); } else if (is_write) { if (write(fd, buf, n) != n) err_sys("write error"); } close(fd); exit(0); }
void Close(int fd) { if (close(fd) == -1) err_sys("close error"); }
void ctaocrypt_test(void* args) { int ret = 0; ((func_args*)args)->return_code = -1; /* error state */ if ( (ret = md5_test()) ) err_sys("MD5 test failed!\n", ret); else printf( "MD5 test passed!\n"); #ifndef NO_MD4 if ( (ret = md4_test()) ) err_sys("MD4 test failed!\n", ret); else printf( "MD4 test passed!\n"); #endif if ( (ret = sha_test()) ) err_sys("SHA test failed!\n", ret); else printf( "SHA test passed!\n"); #ifndef NO_SHA256 if ( (ret = sha256_test()) ) err_sys("SHA-256 test failed!\n", ret); else printf( "SHA-256 test passed!\n"); #endif #ifndef NO_HMAC if ( (ret = hmac_test()) ) err_sys("HMAC test failed!\n", ret); else printf( "HMAC test passed!\n"); #endif if ( (ret = arc4_test()) ) err_sys("ARC4 test failed!\n", ret); else printf( "ARC4 test passed!\n"); #ifndef NO_HC128 if ( (ret = hc128_test()) ) err_sys("HC-128 test failed!\n", ret); else printf( "HC-128 test passed!\n"); #endif #ifndef NO_RABBIT if ( (ret = rabbit_test()) ) err_sys("Rabbit test failed!\n", ret); else printf( "Rabbit test passed!\n"); #endif #ifndef NO_DES if ( (ret = des_test()) ) err_sys("DES test failed!\n", ret); else printf( "DES test passed!\n"); #endif #ifndef NO_DES3 if ( (ret = des3_test()) ) err_sys("DES3 test failed!\n", ret); else printf( "DES3 test passed!\n"); #endif #ifndef NO_AES if ( (ret = aes_test()) ) err_sys("AES test failed!\n", ret); else printf( "AES test passed!\n"); #endif if ( (ret = random_test()) ) err_sys("RANDOM test failed!\n", ret); else printf( "RANDOM test passed!\n"); if ( (ret = rsa_test()) ) err_sys("RSA test failed!\n", ret); else printf( "RSA test passed!\n"); #ifndef NO_DH if ( (ret = dh_test()) ) err_sys("DH test failed!\n", ret); else printf( "DH test passed!\n"); #endif #ifndef NO_DSA if ( (ret = dsa_test()) ) err_sys("DSA test failed!\n", ret); else printf( "DSA test passed!\n"); #endif #ifdef OPENSSL_EXTRA if ( (ret = openssl_test()) ) err_sys("OPENSSL test failed!\n", ret); else printf( "OPENSSL test passed!\n"); #endif ((func_args*)args)->return_code = ret; }
void Getsockopt(int fd, int level, int optname, void *optval, socklen_t *optlenptr) { if (getsockopt(fd, level, optname, optval, optlenptr) < 0) err_sys("getsockopt error"); }
int main(int argc, char *argv[]) { unsigned int portnumber; unsigned int maxslidewindowsize; interface_info_t ii[MAX_INTERFACE_INFO] = {0,}; size_t interface_info_len; fd_set rset, mainset; int maxfdp1, i, n, mysockfd, is_local, pid, client_sockfd, temp_port, new_client_conn, table_count = 0; const int do_not_route = 1, on = 1; char str[INET_ADDRSTRLEN], msg[MAXLINE]; struct sockaddr_in cliaddr, my_recv_addr, my_recv_netmask, cli_conn; table_t table[1000]; socklen_t len = sizeof(cliaddr); char filename[4096] = {0,}; bzero(&cliaddr, sizeof(cliaddr)); bzero(&cli_conn, sizeof(cli_conn)); bzero(&my_recv_addr, sizeof(my_recv_addr)); if (readargsfromfile(&portnumber, &maxslidewindowsize) == -1) { err_quit("Read/parse error from server.in file"); return -1; } printf("port num: %d\nmaxslidewinsize:%d\n\n", portnumber, maxslidewindowsize); build_inferface_info(ii, &interface_info_len, 1, portnumber); print_interface_info(ii, interface_info_len); build_fd_set(&mainset, ii, interface_info_len, &maxfdp1); for ( ; ; ) { rset = mainset; Select(maxfdp1, &rset, NULL, NULL, NULL); for (i = 0; i < interface_info_len; i++) { if (FD_ISSET(ii[i].sockfd, &rset)) { printf("Data recieved on %s\n", Sock_ntop((SA*) (ii[i].ip), sizeof(*(ii[i].ip)))); mysockfd = ii[i].sockfd; my_recv_addr = *(ii[i].ip); my_recv_netmask = *(ii[i].netmask); n = Recvfrom(ii[i].sockfd, msg, MAXLINE, 0, (SA*) &cliaddr, &len); printf("Data recieved from: %s\n", Sock_ntop((SA*) &cliaddr, len)); memcpy(filename, msg, 4096); if (strchr(filename, '\n')) *strchr(filename, '\n') = '\0'; printf("Data(Filename):%s\n", msg); if (checktable(cliaddr, table_count, table) < 0 ) { printf("Same <ip and port> tried to conected again, not creating new child.\n"); continue; } if ((pid = Fork()) == 0) { // Child // CLose all other sockets. for (i = 0; i < interface_info_len; i++) if (ii[i].sockfd != mysockfd) close(ii[i].sockfd); // Find out if client is loopback or local or not. is_local = find_if_client_local(my_recv_addr, cliaddr, ii, interface_info_len, my_recv_netmask); if (is_local < 3) printf("Client host is local\n"); else printf("Client host is not local\n"); // Create UDP socket to handle file transfer with this client."connection socket" client_sockfd = Socket(AF_INET, SOCK_DGRAM, 0); if (is_local < 3) Setsockopt(client_sockfd, SOL_SOCKET, SO_DONTROUTE, &do_not_route, sizeof(do_not_route)); Setsockopt(client_sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); cli_conn.sin_addr = my_recv_addr.sin_addr; cli_conn.sin_family = AF_INET; cli_conn.sin_port = htons(0); Bind(client_sockfd, (SA *) &cli_conn, sizeof(cli_conn)); len = sizeof(cli_conn); Getsockname(client_sockfd, (SA*) &cli_conn, &len); printf("\nConnection socket bound, protocol Address:%s\n", Sock_ntop((SA*) &cli_conn, len)); Connect(client_sockfd, (SA*) &cliaddr, sizeof(cliaddr)); len = sizeof(cliaddr); Getpeername(client_sockfd, (SA*) &cliaddr, &len); printf("\nServer child connected to client, protocol Address:%s\n", Sock_ntop((SA*) &cliaddr, len)); temp_port = ntohs(cli_conn.sin_port); send_buffer_t buf; sprintf(buf.payload, "%d", temp_port); buf.hdr.cntrl = 1; long long seq = -1; static void sig_alrm(int signo); Signal(SIGALRM, sig_alrm); Sendto(mysockfd, &buf, sizeof(buf), 0,(SA*) &cliaddr, len); printf("New port sent.\n"); alarm(5); if (sigsetjmp(jmpbuf, 1) != 0) { printf ("Didn't receive ack for port number transfer. Resending.\n"); Sendto(mysockfd, &buf, sizeof(buf), 0,(SA*) &cliaddr, len); Write(client_sockfd, &buf, sizeof(buf)); alarm (5); } send_buffer_t rb; do { memset(&rb, 0, sizeof(rb)); n = read(client_sockfd, &rb, sizeof(rb)); } while (rb.hdr.cntrl == 0); printf("Msg (ACK) on new port\n"); close(mysockfd); alarm(0); memset(&buf, 0, sizeof(buf)); buf.hdr.sft = 1; Write(client_sockfd, &buf, sizeof(buf)); if (send_file(filename, client_sockfd, maxslidewindowsize)) printf("Failed to send file\n"); table[table_count].is_conn = 0; exit(0);// exit child } else if (pid > 0) { table[table_count].ip = cliaddr; table[table_count].is_conn = 1; table_count++; } else { err_sys("Creating child failed: "); } } } } return 0; }