int main(void) { signal(SIGCHLD, SigchldHandler); int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == sockfd) { perror("Socket error:\n"); return -1; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(SERVER_PORT); addr.sin_addr.s_addr = inet_addr(SERVER_IP); int optval = 1; if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) { perror("Set socket option error:\n"); } if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))) { perror("Bind error:\n"); return -1; } if (-1 == listen(sockfd, SOMAXCONN)) { perror("Listen error:\n"); return -1; } while (1) { struct sockaddr_in clientaddr; socklen_t socklen = sizeof(clientaddr); int connfd = accept(sockfd, (struct sockaddr *)&clientaddr, &socklen); pid_t pid = fork(); if (-1 == pid) { perror("Create process error:\n"); exit(-1); } else if (0 == pid) { //child process if (-1 == connfd) { perror("Accept error:\n"); return -1; } printf("child process.\n"); printf("client address %s.\n", inet_ntoa(clientaddr.sin_addr)); while (1) { char recbuffer[1024] = {0}; int readlen = read(connfd, recbuffer, sizeof(recbuffer)); if (-1 == readlen) { if (EINTR == errno) { continue; } //return - 1; exit(-1); } else if (0 == readlen) { printf("Client close.\n"); close(connfd); exit(0); } else { // if (recbuffer[0] == 'c') { // close(connfd); // exit(0); // } printf("recv %s.\n", recbuffer); int writelen = write(connfd, recbuffer, strlen(recbuffer)); if (-1 == writelen) { if (EINTR == errno) { continue; } close(connfd); //shutdown(connfd, SHUT_RDWR); exit(-1); } else if (writelen > 0) { //TODO something } else { } memset(recbuffer, 0, sizeof(recbuffer)); } } } else if (pid > 0) { //parent process close(connfd); } } return 0; }
int main(int argc, char *argv[]) { int rc; pid_t pid; int waitstatus; int filedes[2]; int c, o; char buf[BUFSIZ]; unsigned long magic_token = SD_ID_MAGIC+1; int manual = 0; int exit_hat = 0; char * manual_string; while ((c = getopt_long (argc, argv, "+", long_options, &o)) != -1) { if (c == 0) { switch (o) { case 0: magic_token = strtoul (optarg, NULL, 10); break; case 1: manual = 1; manual_string = (char *) malloc(strlen(optarg) + 1); if (!manual_string) { fprintf(stderr, "FAIL: malloc failed\n"); exit(1); } strcpy(manual_string, optarg); break; case 2: exit_hat = 1; break; case 3: usage(argv[0]); break; default: usage(argv[0]); break; } } else { usage(argv[0]); } } if (!argv[optind]) usage(argv[0]); rc = pipe(filedes); if (rc != 0) { perror("FAIL: pipe failed"); exit(1); } pid = fork(); if (pid == -1) { fprintf(stderr, "FAIL: fork failed - %s\n", strerror(errno)); exit(1); } else if (pid != 0) { /* parent */ close(filedes[1]); read(filedes[0], &buf, sizeof(buf)); rc = wait(&waitstatus); if (rc == -1){ fprintf(stderr, "FAIL: wait failed - %s\n", strerror(errno)); exit(1); } } else { /* child */ char * pname = malloc (strlen(argv[optind]) + 3); if (!pname) { perror ("FAIL: child malloc"); return -1; } sprintf (pname, "%s", argv[optind]); rc = !manual ? change_hat(argv[optind], magic_token) : manual_change_hat(argv[optind], manual_string); if (rc != 0) { rc = !manual ? change_hat(NULL, magic_token) : manual_change_hat(NULL, manual_string); fprintf(stderr, "FAIL: hat for %s does not exist\n", argv[optind]); exit(1); } close(filedes[0]); fclose(stdout); rc = dup2(filedes[1], STDOUT_FILENO); if (rc < 0) { perror("FAIL: pipe failed"); exit(1); } exit(execv(pname, &argv[optind])); } if (exit_hat) { rc = !manual ? change_hat(NULL, magic_token) : manual_change_hat(NULL, manual_string); /* shouldn't fail, if it does, we've been killed */ if (rc != 0) { fprintf(stderr, "FAIL: exiting hat '%s' failed\n", argv[optind]); exit(1); } } if ((WEXITSTATUS(waitstatus) == 0) && strcmp("PASS\n", buf) == 0) { printf("PASS\n"); } return WEXITSTATUS(waitstatus); }
/* * Get a list of the current firewall entries * @param fw_list list of firewall entries * @return 0 on success and errno on failure */ int netconf_get_fw(netconf_fw_t *fw_list) { const char **table; const char *chain; const struct ipt_entry *entry; struct iptc_handle *handle = NULL; /* Initialize list */ netconf_list_init(fw_list); /* Search all default tables */ for (table = &netconf_table_names[0]; *table; table++) { if (strcmp(*table, "filter") && strcmp(*table, "nat")) continue; if (!(handle = iptc_init(*table))) { fprintf(stderr, "%s\n", iptc_strerror(errno)); goto err; } /* Search all default chains */ for (chain = iptc_first_chain(handle); chain; chain = iptc_next_chain(handle)) { if (strcmp(chain, "INPUT") && strcmp(chain, "FORWARD") && strcmp(chain, "OUTPUT") && strcmp(chain, "PREROUTING") && strcmp(chain, "POSTROUTING") && strcmp(chain, "VSERVER") && strcmp(chain, "UPNP")) continue; /* Search all entries */ for (entry = iptc_first_rule(chain, handle); entry; entry = iptc_next_rule(entry, handle)) { int num = target_num(entry, handle); netconf_fw_t *fw = NULL; netconf_filter_t *filter = NULL; netconf_nat_t *nat = NULL; netconf_app_t *app = NULL; const struct ipt_entry_match *match; const struct ipt_entry_target *target; struct ipt_mac_info *mac = NULL; struct ipt_state_info *state = NULL; struct ipt_conntrack_info *conntrack = NULL; struct ipt_time_info *time = NULL; /* Only know about TCP/UDP */ if (!netconf_valid_ipproto(entry->ip.proto)) continue; /* Only know about target types in the specified tables */ if (!netconf_valid_target(num) || (netconf_table_name[num] && strncmp(netconf_table_name[num], *table, IPT_FUNCTION_MAXNAMELEN) != 0)) continue; /* Only know about specified target types */ if (netconf_valid_filter(num)) fw = (netconf_fw_t *) (filter = calloc(1, sizeof(netconf_filter_t))); else if (netconf_valid_nat(num)) fw = (netconf_fw_t *) (nat = calloc(1, sizeof(netconf_nat_t))); else if (num == NETCONF_APP) fw = (netconf_fw_t *) (app = calloc(1, sizeof(netconf_app_t))); else continue; if (!fw) { perror("calloc"); goto err; } netconf_list_add(fw, fw_list); /* Get IP addresses */ fw->match.src.ipaddr.s_addr = entry->ip.src.s_addr; fw->match.src.netmask.s_addr = entry->ip.smsk.s_addr; fw->match.dst.ipaddr.s_addr = entry->ip.dst.s_addr; fw->match.dst.netmask.s_addr = entry->ip.dmsk.s_addr; fw->match.flags |= (entry->ip.invflags & IPT_INV_SRCIP) ? NETCONF_INV_SRCIP : 0; fw->match.flags |= (entry->ip.invflags & IPT_INV_DSTIP) ? NETCONF_INV_DSTIP : 0; /* Get interface names */ strncpy(fw->match.in.name, entry->ip.iniface, IFNAMSIZ); strncpy(fw->match.out.name, entry->ip.outiface, IFNAMSIZ); fw->match.flags |= (entry->ip.invflags & IPT_INV_VIA_IN) ? NETCONF_INV_IN : 0; fw->match.flags |= (entry->ip.invflags & IPT_INV_VIA_OUT) ? NETCONF_INV_OUT : 0; fw->match.ipproto = entry->ip.proto; /* Get TCP port(s) */ if (entry->ip.proto == IPPROTO_TCP) { struct ipt_tcp *tcp = NULL; for_each_ipt_match(match, entry) { if (strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN) != 0) continue; tcp = (struct ipt_tcp *) &match->data[0]; break; } if (tcp) { /* Match ports stored in host order for some stupid reason */ fw->match.src.ports[0] = htons(tcp->spts[0]); fw->match.src.ports[1] = htons(tcp->spts[1]); fw->match.dst.ports[0] = htons(tcp->dpts[0]); fw->match.dst.ports[1] = htons(tcp->dpts[1]); fw->match.flags |= (tcp->invflags & IPT_TCP_INV_SRCPT) ? NETCONF_INV_SRCPT : 0; fw->match.flags |= (tcp->invflags & IPT_TCP_INV_DSTPT) ? NETCONF_INV_DSTPT : 0; } } /* Get UDP port(s) */ else if (entry->ip.proto == IPPROTO_UDP) { struct ipt_udp *udp = NULL; for_each_ipt_match(match, entry) { if (strncmp(match->u.user.name, "udp", IPT_FUNCTION_MAXNAMELEN) != 0) continue; udp = (struct ipt_udp *) &match->data[0]; break; } if (udp) { /* Match ports stored in host order for some stupid reason */ fw->match.src.ports[0] = htons(udp->spts[0]); fw->match.src.ports[1] = htons(udp->spts[1]); fw->match.dst.ports[0] = htons(udp->dpts[0]); fw->match.dst.ports[1] = htons(udp->dpts[1]); fw->match.flags |= (udp->invflags & IPT_UDP_INV_SRCPT) ? NETCONF_INV_SRCPT : 0; fw->match.flags |= (udp->invflags & IPT_UDP_INV_DSTPT) ? NETCONF_INV_DSTPT : 0; } } /* Get source MAC address */ for_each_ipt_match(match, entry) { if (strncmp(match->u.user.name, "mac", IPT_FUNCTION_MAXNAMELEN) != 0) continue; mac = (struct ipt_mac_info *) &match->data[0]; break; } if (mac) { memcpy(fw->match.mac.octet, mac->srcaddr, ETHER_ADDR_LEN); fw->match.flags |= mac->invert ? NETCONF_INV_MAC : 0; } /* Get packet state */ for_each_ipt_match(match, entry) { if (strncmp(match->u.user.name, "state", IPT_FUNCTION_MAXNAMELEN) == 0) { state = (struct ipt_state_info *) &match->data[0]; break; } else if (strncmp(match->u.user.name, "conntrack", IPT_FUNCTION_MAXNAMELEN) == 0) { conntrack = (struct ipt_conntrack_info *) &match->data[0]; break; } } if (conntrack && (conntrack->match_flags & XT_CONNTRACK_STATE)) { fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_INVALID) ? NETCONF_INVALID : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_BIT(IP_CT_ESTABLISHED)) ? NETCONF_ESTABLISHED : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_BIT(IP_CT_RELATED)) ? NETCONF_RELATED : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_BIT(IP_CT_NEW)) ? NETCONF_NEW : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_UNTRACKED) ? NETCONF_UNTRACKED : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_SNAT) ? NETCONF_STATE_SNAT : 0; fw->match.state |= (conntrack->state_mask & XT_CONNTRACK_STATE_DNAT) ? NETCONF_STATE_DNAT : 0; } else if (state) { fw->match.state |= (state->statemask & IPT_STATE_INVALID) ? NETCONF_INVALID : 0; fw->match.state |= (state->statemask & IPT_STATE_BIT(IP_CT_ESTABLISHED)) ? NETCONF_ESTABLISHED : 0; fw->match.state |= (state->statemask & IPT_STATE_BIT(IP_CT_RELATED)) ? NETCONF_RELATED : 0; fw->match.state |= (state->statemask & IPT_STATE_BIT(IP_CT_NEW)) ? NETCONF_NEW : 0; } /* Get local time */ for_each_ipt_match(match, entry) { if (strncmp(match->u.user.name, "time", IPT_FUNCTION_MAXNAMELEN) != 0) continue; /* We added 8 bytes of day range at the end */ if (match->u.match_size < (IPT_ALIGN(sizeof(struct ipt_entry_match)) + IPT_ALIGN(sizeof(struct ipt_time_info) + 8))) continue; time = (struct ipt_time_info *) &match->data[0]; break; } if (time) { fw->match.days = time->weekdays_match; fw->match.secs[0] = time->daytime_start; fw->match.secs[1] = time->daytime_stop; } /* Set target type */ fw->target = num; target = (struct ipt_entry_target *) ((int) entry + entry->target_offset); /* Get filter target information */ if (filter) { if (!netconf_valid_dir(filter->dir = filter_dir(chain))) { fprintf(stderr, "error direction in %s\n", chain); goto err; } } /* Get NAT target information */ else if (nat) { struct ip_nat_multi_range *mr = (struct ip_nat_multi_range *) &target->data[0]; struct ip_nat_range *range = (struct ip_nat_range *) &mr->range[0]; /* Get mapped IP address */ nat->ipaddr.s_addr = range->min_ip; /* Get mapped TCP port(s) */ if (entry->ip.proto == IPPROTO_TCP) { nat->ports[0] = range->min.tcp.port; nat->ports[1] = range->max.tcp.port; } /* Get mapped UDP port(s) */ else if (entry->ip.proto == IPPROTO_UDP) { nat->ports[0] = range->min.udp.port; nat->ports[1] = range->max.udp.port; } } /* Get application specific port forward information */ else if (app) { struct ip_autofw_info *info = (struct ip_autofw_info *) &target->data[0]; app->proto = info->proto; app->dport[0] = info->dport[0]; app->dport[1] = info->dport[1]; app->to[0] = info->to[0]; app->to[1] = info->to[1]; } } } if (!iptc_commit(handle)) { fprintf(stderr, "%s\n", iptc_strerror(errno)); goto err; } iptc_free(handle); handle = NULL; }
void err_exit(char *message) { perror(message); exit(1); }
void sendFile(char *serverName, unsigned int serverPort, char *filePath) { struct sockaddr_in serverAddress; if ((clientSocketDescriptor = createTcpSocket(serverName, serverPort, &serverAddress)) == -1) { fprintf(stderr, "Creation socket error\n"); exit(EXIT_FAILURE); } if (connect (clientSocketDescriptor, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) { perror("connect"); exit(EXIT_FAILURE); } FILE *file = fopen(filePath, "r+"); if (file == NULL) { perror("Open file error"); exit(EXIT_FAILURE); } long fileSize = GetFileSize(file); char replyBuf[replyBufSize]; sprintf(replyBuf, "%s:%ld", basename(filePath), fileSize); // Send file name and file size if (send(clientSocketDescriptor, replyBuf, sizeof(replyBuf), 0) == -1) { perror("Send error"); exit(EXIT_FAILURE); } char buf[bufSize]; long totalBytesSent = 0; size_t bytesRead; int middle = (fileSize / bufSize) / 2; if (middle == 0) middle = 1; // Sending file printf("Start sending file.\n"); int i = 0; while (totalBytesSent < fileSize) { bytesRead = fread(buf, 1, sizeof(buf), file); int sendBytes = send(clientSocketDescriptor, buf, bytesRead, 0); if (sendBytes < 0) { perror("Sending error\n"); exit(EXIT_FAILURE); } totalBytesSent += sendBytes; // Send OOB data in the middle of sending file if (++i == middle) { printf("Sent OOB byte. Total bytes sent: %ld\n", totalBytesSent); sendBytes = send(clientSocketDescriptor, "!", 1, MSG_OOB); if (sendBytes < 0) { perror("Sending error"); exit(EXIT_FAILURE); } } } printf("Sending file completed. Total bytes sent: %ld\n", totalBytesSent); close(clientSocketDescriptor); fclose(file); }
void diep(char *s) { perror(s); exit(1); }
int main(int argc, char *argv[], char *envp[]) { struct stat histstat; if (modfind(VINUMMOD) < 0) { /* need to load the vinum module */ if (kldload(VINUMMOD) < 0 || modfind(VINUMMOD) < 0) { perror(VINUMMOD ": Kernel module not available"); return 1; } } dateformat = getenv("VINUM_DATEFORMAT"); if (dateformat == NULL) dateformat = "%e %b %Y %H:%M:%S"; historyfile = getenv("VINUM_HISTORY"); if (historyfile == NULL) historyfile = DEFAULT_HISTORYFILE; if (stat(historyfile, &histstat) == 0) { /* history file exists */ if ((histstat.st_mode & S_IFMT) != S_IFREG) { fprintf(stderr, "Vinum history file %s must be a regular file\n", historyfile); exit(1); } } else if ((errno != ENOENT) /* not "not there", */ &&(errno != EROFS)) { /* and not read-only file system */ fprintf(stderr, "Can't open %s: %s (%d)\n", historyfile, strerror(errno), errno); exit(1); } hist = fopen(historyfile, "a+"); if (hist != NULL) { timestamp(); fprintf(hist, "*** " VINUMMOD " started ***\n"); fflush(hist); /* before we start the daemon */ } superdev = open(VINUM_SUPERDEV_NAME, O_RDWR); /* open vinum superdevice */ if (superdev < 0) { /* no go */ if (errno == ENODEV) { /* not configured, */ superdev = open(VINUM_WRONGSUPERDEV_NAME, O_RDWR); /* do we have a debug mismatch? */ if (superdev >= 0) { /* yup! */ #if VINUMDEBUG fprintf(stderr, "This program is compiled with debug support, but the kernel module does\n" "not have debug support. This program must be matched with the kernel\n" "module. Please alter /usr/src/sbin/" VINUMMOD "/Makefile and remove\n" "the option -DVINUMDEBUG from the CFLAGS definition, or alternatively\n" "edit /usr/src/sys/modules/" VINUMMOD "/Makefile and add the option\n" "-DVINUMDEBUG to the CFLAGS definition. Then rebuild the component\n" "of your choice with 'make clean all install'. If you rebuild the kernel\n" "module, you must stop " VINUMMOD " and restart it\n"); #else fprintf(stderr, "This program is compiled without debug support, but the kernel module\n" "includes debug support. This program must be matched with the kernel\n" "module. Please alter /usr/src/sbin/" VINUMMOD "/Makefile and add\n" "the option -DVINUMDEBUG to the CFLAGS definition, or alternatively\n" "edit /usr/src/sys/modules/" VINUMMOD "/Makefile and remove the option\n" "-DVINUMDEBUG from the CFLAGS definition. Then rebuild the component\n" "of your choice with 'make clean all install'. If you rebuild the kernel\n" "module, you must stop " VINUMMOD " and restart it\n"); #endif return 1; } } else if (errno == ENOENT) /* we don't have our node, */ make_devices(); /* create them first */ if (superdev < 0) { perror("Can't open " VINUM_SUPERDEV_NAME); return 1; } } /* Check if the dæmon is running. If not, start it in the * background */ start_daemon(); if (argc > 1) { /* we have a command on the line */ if (setjmp(command_fail) != 0) /* long jumped out */ return -1; parseline(argc - 1, &argv[1]); /* do it */ } else { /* * Catch a possible race condition which could cause us to * longjmp() into nowhere if we receive a SIGINT in the next few * lines. */ if (setjmp(command_fail)) /* come back here on catastrophic failure */ return 1; setsigs(); /* set signal handler */ for (;;) { /* ugh */ char *c; int childstatus; /* from wait4 */ if (setjmp(command_fail) == 2) /* come back here on catastrophic failure */ fprintf(stderr, "*** interrupted ***\n"); /* interrupted */ while (wait4(-1, &childstatus, WNOHANG, NULL) > 0); /* wait for all dead children */ c = readline(VINUMMOD " -> "); /* get an input */ if (c == NULL) { /* EOF or error */ if (ferror(stdin)) { fprintf(stderr, "Can't read input: %s (%d)\n", strerror(errno), errno); return 1; } else { /* EOF */ printf("\n"); return 0; } } else if (*c) { /* got something there */ add_history(c); /* save it in the history */ strcpy(buffer, c); /* put it where we can munge it */ free(c); line++; /* count the lines */ tokens = tokenize(buffer, token); /* got something potentially worth parsing */ if (tokens) parseline(tokens, token); /* and do what he says */ } if (hist) fflush(hist); } } return 0; /* normal completion */ }
int OpenComport(int comport_number, int baudrate) { int baudr; if((comport_number>21)||(comport_number<0)) { printf("illegal comport number\n"); return(1); } switch(baudrate) { case 50 : baudr = B50; break; case 75 : baudr = B75; break; case 110 : baudr = B110; break; case 134 : baudr = B134; break; case 150 : baudr = B150; break; case 200 : baudr = B200; break; case 300 : baudr = B300; break; case 600 : baudr = B600; break; case 1200 : baudr = B1200; break; case 1800 : baudr = B1800; break; case 2400 : baudr = B2400; break; case 4800 : baudr = B4800; break; case 9600 : baudr = B9600; break; case 19200 : baudr = B19200; break; case 38400 : baudr = B38400; break; case 57600 : baudr = B57600; break; case 115200 : baudr = B115200; break; case 230400 : baudr = B230400; break; case 460800 : baudr = B460800; break; case 500000 : baudr = B500000; break; case 576000 : baudr = B576000; break; case 921600 : baudr = B921600; break; case 1000000 : baudr = B1000000; break; default : printf("invalid baudrate\n"); return(1); break; } Cport[comport_number] = open(comports[comport_number], O_RDWR | O_NOCTTY | O_NDELAY); if(Cport[comport_number]==-1) { perror("unable to open comport "); return(1); } error = tcgetattr(Cport[comport_number], old_port_settings + comport_number); if(error==-1) { close(Cport[comport_number]); perror("unable to read portsettings "); return(1); } memset(&new_port_settings, 0, sizeof(new_port_settings)); /* clear the new struct */ new_port_settings.c_cflag = baudr | CS8 | CLOCAL | CREAD; new_port_settings.c_iflag = IGNPAR; new_port_settings.c_oflag = 0; new_port_settings.c_lflag = 0; new_port_settings.c_cc[VMIN] = 0; /* block untill n bytes are received */ new_port_settings.c_cc[VTIME] = 0; /* block untill a timer expires (n * 100 mSec.) */ error = tcsetattr(Cport[comport_number], TCSANOW, &new_port_settings); if(error==-1) { close(Cport[comport_number]); perror("unable to adjust portsettings "); return(1); } return(0); }
int main(int argc, char *argv[]) { pid_t pid; int status; int ServerFD[2]; int ServerFD2[2]; char *data = "accept"; char *data2 = "reject"; char *terminate = "terminate"; char pubbuf[1025]; char pubbufend[1025]; char pubbufterm[1025]; char subbuf[1025]; char subbufend[1025]; char subbufterm[1025]; pipe(ServerFD); pipe(ServerFD2); pid = fork(); if(pid == 0){//this is the child of the main process, the DIServer int i; //n is # of publisher int n = atoi(argv[1]); //m is number of subscribers int m = atoi(argv[2]); //t are topics int t = atoi(argv[3]); pthread_t pubthreads[n]; pthread_t subthreads[m]; int rc; int rc2; void *pubthreadstatus; void *subthreadstatus; pthread_attr_t pubattr; pthread_attr_t subattr; pthread_attr_init(&pubattr); pthread_attr_setdetachstate(&pubattr, PTHREAD_CREATE_JOINABLE); pthread_attr_init(&subattr); pthread_attr_setdetachstate(&subattr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutexlock,NULL); Record record[n+m]; /*need to use n and m to create child procs of the DIServer, publishers and subscriers*/ //loop to create publisher procs and stroe pid in array; pid_t pubpid; pid_t subpid; //map space for the pub array pubpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (!pubpids) { perror("mmap failed"); exit(1); } memset((void *)pubpids, 0, MAX_PIDS*sizeof(pid_t)); //map space for sub array subpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (!subpids) { perror("mmap failed"); exit(1); } memset((void *)subpids, 0, MAX_PIDS*sizeof(pid_t)); //loop to creat forked pubs for(i=0;i<n;i++) { //create the record struct //create the publisher struct int z; Publisher pub; pub.pubConnect = "Pub Connect"; pub.pubTopic = "Topic 1";//topic of interest pub.pubEnd = "End"; pub.pubterm = "terminate"; pipe(pub.fileDescriptor); pubpid = fork(); int articles; char article[12]; if(pubpid == 0) { //doPublisher(n); write(pub.fileDescriptor[1], pub.pubConnect, strlen(pub.pubConnect)); if ((z = read(ServerFD[0], pubbuf, 1024)) >= 0) { pubbuf[z] = 0; /* terminate the string */ //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbuf); if (strcmp(pubbuf, data) == 0) { write(pub.fileDescriptor[1], pub.pubTopic, strlen(pub.pubTopic)); if ((z = read(ServerFD[0], pubbufend, 1024)) >= 0) { pubbufend[z] = 0; //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbufend); if (strcmp(pubbufend, data) == 0){ write(pub.fileDescriptor[1], pub.pubEnd, strlen(pub.pubEnd)); if((z = read(ServerFD[0], pubbufend, 1024)) >= 0) { // printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbufend); /*if (strcmp(pubbufend, data)==0){ for (articles = 0; articles<10;articles++){ if(articles%2 != 0){ sprintf(article, "Topic 1 Article %d", articles); write(pub.fileDescriptor[1], article, strlen(article)); } } }*/ } } else{ write(pub.fileDescriptor[1], pub.pubterm, strlen(pub.pubterm)); continue; } } } else{ write(pub.fileDescriptor[1], pub.pubterm, strlen(pub.pubterm)); continue; } } else perror("read"); //if reads accept then write to publisher pipe exit(0); } else if (pubpid < 0){ perror("fork failed"); } else{//back to the DIServer record[i].pipe = pub.fileDescriptor; record[i].type = "Publisher"; record[i].pid = i+1; record[i].selectTopics = pub.pubTopic; record[i].serverPipe = ServerFD; rc=pthread_create(&pubthreads[i],&pubattr,pubThr_fn,(void *) &record[i]); if(rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } pthread_attr_destroy(&pubattr); rc = pthread_join(pubthreads[i], &pubthreadstatus); // want to create the thread here, then handle all of reading a writng of pipes in thread handler} } } //loop to create forked subs; for(i=0;i<m;i++) { //create the subscriber struct int z; Subscriber sub; sub.subConnect = "Sub Connect"; sub.subTopic = "Topic 1"; //topic of interest sub.subEnd = "End"; sub.subterm = "terminate"; pipe(sub.fileDescriptor); subpid = fork(); if(subpid == 0) { //doPublisher(n); write(sub.fileDescriptor[1], sub.subConnect, strlen(sub.subConnect)); if ((z = read(ServerFD2[0], subbuf, 1024)) >= 0) { subbuf[z] = 0; /* terminate the string */ //printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbuf); if (strcmp(subbuf, data) == 0) { write(sub.fileDescriptor[1], sub.subTopic, strlen(sub.subTopic)); if ((z = read(ServerFD2[0], subbufend, 1024)) >= 0) { subbufend[z] = 0; // printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbufend); if (strcmp(subbufend, data) == 0){ write(sub.fileDescriptor[1], sub.subEnd, strlen(sub.subEnd)); if((z = read(ServerFD2[0], subbufend, 1024)) >= 0) { //printf("sub read %d bytes from the DIServer pipe: \"%s\"\n", z, subbufend); } } else{ write(sub.fileDescriptor[1], sub.subterm, strlen(sub.subterm)); continue; } } } else{ write(sub.fileDescriptor[1], sub.subterm, strlen(sub.subterm)); continue; } } else perror("read"); //if reads accept then write to publisher pipe exit(0); } else if (subpid < 0){ perror("fork failed"); } else{//back to the DIServer record[i+n].pipe = sub.fileDescriptor; record[i+n].type = "Subscriber"; record[i+n].pid = i+1; record[i+n].selectTopics = sub.subTopic; record[i+n].serverPipe = ServerFD2; rc2 = pthread_create(&subthreads[i],&subattr,subThr_fn,(void *) &record[i+n]); if(rc2){ printf("ERROR; return code from pthread_create() is %d\n", rc2); exit(-1); } pthread_attr_destroy(&subattr); rc2 = pthread_join(subthreads[i], &subthreadstatus); } } /* pthread_attr_destroy(&subattr); for(i=0;i<n;i++){ printf("here\n"); rc = pthread_join(pubthreads[i], &pubthreadstatus); if (rc) { printf("ERROR; return code from pthread_join() is %d\n", rc); exit(-1); } } pthread_attr_destroy(&subattr); for(i=0;i<m;i++){ printf("here\n"); rc2 = pthread_join(subthreads[i], &subthreadstatus); if (rc2) { printf("ERROR; return code from pthread_join() is %d\n", rc2); exit(-1); } } */ /*this works because the way code is written, if it makes it here all connections have been made*/ //printf("all pubs and subs have connected to server\n"); for(i = 0; i<n+m; i++){ printf("Type:%s, ID: %d, Topic: %s\n", record[i].type, record[i].pid, record[i].selectTopics); } //begin termination write(ServerFD[1], terminate, strlen(terminate)); close(ServerFD[1]); for(i = 0; i<n+m; i++){ printf("%s-%d: terminated\n", record[i].type,record[i].pid); } //printf("%s\n", ); pthread_exit(NULL); } else wait(&status); //main process just needs to wait for everything else to be done. return(0); }
int LocalFilesRecursiveDir ( struct collectionFormat *collection, int (*documentExist)(struct collectionFormat *collection,struct crawldocumentExistFormat *crawldocumentExist), int (*documentAdd)(struct collectionFormat *collection,struct crawldocumentAddFormat *crawldocumentAdd), char prefix[], char dirname[], int accessmode ) { //char *dokument_buff = malloc(_dokument_buff_size +1); char *dokument_buff; printf("opening dir \"%s\", prefix %s\n",dirname,prefix); DIR *DIRH; struct dirent *dp; char nextdirname[512]; char filname[512]; char lotinternfilname[512]; FILE *FH; struct stat inode; // lager en struktur for fstat å returnere. int dokument_size; int diraccessmode; int filecessmode; struct passwd *pw; struct group *gp; //char acl[4][64]; char acl[3 * 64]; int count; char uri[512]; struct crawldocumentExistFormat crawldocumentExist; struct crawldocumentAddFormat crawldocumentAdd; if (stat(dirname,&inode) != 0) { perror("stat"); return 0; } //har ownaccessmode som den laveste i hele pathen int ownaccessmode = inode.st_mode & accessmode; if ((DIRH = opendir(dirname)) == NULL) { perror(dirname); return; } while ((dp = readdir(DIRH)) != NULL) { sprintf(nextdirname,"%s/%s",dirname,dp->d_name); if (stat(nextdirname,&inode) != 0) { perror("fstat"); continue; } if (dp->d_name[0] == '.') { printf(". domain (\"%s\")\n",dp->d_name); } //else if (dp->d_type == DT_DIR) { else if (S_ISDIR(inode.st_mode)) { sprintf(nextdirname,"%s/%s",dirname,dp->d_name); printf("dir (nextdirname %s)\n",nextdirname); //kaller seg selv rekurift LocalFilesRecursiveDir(collection,documentExist,documentAdd,prefix,nextdirname,ownaccessmode); } //else if (dp->d_type == DT_REG) { else if (S_ISREG(inode.st_mode)) { sprintf(filname,"%s/%s",dirname,dp->d_name); snprintf(uri,sizeof(uri),"%s/%s",prefix,filname); //sprintf(lotinternfilname,"%s%s",lotinternpath,dp->d_name); printf("file %s\n",filname); //rSendFile(filname,lotinternfilname,lotNr, "w",subname); if ((FH = fopen(filname,"rb")) == NULL) { perror(filname); //exit(1); continue; } crawldocumentExist.documenturi = uri; crawldocumentExist.lastmodified = inode.st_mtime; crawldocumentExist.dokument_size = inode.st_size; //spør Boitho om filområdet finnes //if (!(documentExist)(collection, &crawldocumentExist ) ) { dokument_size = inode.st_size; dokument_buff = malloc(dokument_size +1); printf("uid %i, gid %i\n",inode.st_uid,inode.st_gid); //lager acl acl[0] = '\0'; filecessmode = ownaccessmode & inode.st_mode; printf("mode %i\n",(int)inode.st_mode); if (filecessmode & S_IRUSR) { printf("ovner have read permission. S_IRUSR %i\n",inode.st_mode & S_IRUSR); //find username and appendit if ((pw = getpwuid(inode.st_uid)) == NULL) { printf("unknown user id %i\n",inode.st_uid); } else { printf("user name is %s\n",pw->pw_name); //strcmp(acl[nrofacls++],pw->pw_name); strcat(acl,pw->pw_name); strcat(acl,","); } } if (filecessmode & S_IRGRP) { printf("group have read permission. S_IRGRP %i\n",inode.st_mode & S_IRGRP); if ((gp = getgrgid(inode.st_gid)) == NULL) { printf("unknown group id %i\n",inode.st_gid); } else { printf("group is %s\n",gp->gr_name); //strcmp(acl[nrofacls++],gp->gr_name); strcat(acl,gp->gr_name); strcat(acl,","); } } if (filecessmode & S_IROTH) { printf("others have read permission. S_IROTH %i\n",inode.st_mode & S_IROTH); //strcmp(acl[nrofacls++],"EVERYONE"); strcat(acl,"Everyone"); //toDo bruker msad sin gruppe fro alle her. Bør kansje ha en engen?? strcat(acl,","); } //uefektift, bruker strlen() to ganger if (acl[strlen(acl)] == ',') { acl[strlen(acl)] = '\0'; } //leser hele dokumentet fread(dokument_buff,sizeof(char),dokument_size,FH); crawldocumentAdd.documenturi = uri; crawldocumentAdd.documenttype = ""; crawldocumentAdd.document = dokument_buff; crawldocumentAdd.dokument_size = dokument_size; crawldocumentAdd.lastmodified = inode.st_mtime; crawldocumentAdd.acl = acl; crawldocumentAdd.title = dp->d_name; crawldocumentAdd.doctype = ""; printf("\tdokument_size \"%i\"\n",dokument_size); (*documentAdd)(collection ,&crawldocumentAdd); //bbdn_docadd(bbdh,collection,filname,"",dokument_buff,dokument_size,(unsigned int)inode.st_mtime,acl,dp->d_name,""); free(dokument_buff); //} fclose(FH); } else { printf("unknown type %i. Name \"%s\"\n",inode.st_mode,dp->d_name); } //printf("%s %i\n",dp->d_name,dp->d_type); } closedir(DIRH); }
int main(int argc, char** argv) { mqd_t msg_queue = mq_open("/CprE308-Queue", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP, NULL); if(msg_queue == -1) { perror("mq_open\n"); return -1; } // Determine max. msg size; allocate buffer to receive msg struct mq_attr attr; char *buf; if (mq_getattr(msg_queue, &attr)) { perror("mq_getattr\n"); exit(-1); } buf = malloc(attr.mq_msgsize); if (buf == NULL) { perror("malloc"); exit(-1); } sleep(10); ssize_t size; size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL); if (size == -1) { perror("mq_receive\n"); exit(-1); } printf("Received message \"%s\"\n", buf); size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL); if (size == -1) { perror("mq_receive\n"); exit(-1); } printf("Received message \"%s\"\n", buf); free(buf); char my_string[] = "I am Clara"; if( mq_send(msg_queue, my_string, strlen(my_string), 12)) { perror("mq_send\n"); return -1; } char my_string2[] = "I am Rose"; if( mq_send(msg_queue, my_string2, strlen(my_string2), 11)) { perror("mq_send\n"); return -1; } return 0; }
int main(int argc, char *argv[]) { if (getpid() == 1) { if (open("/dev/tty0", O_RDWR) != 0) return 1; if (dup(0) != 1) return 1; if (dup(1) != 2) return 1; setenv("PATH", "/usr/local/bin:/usr/bin:/bin", 1); setenv("HOME", "/root", 1); setenv("LD_LIBRARY_PATH", "/usr/local/lib:/usr/lib:/lib", 1); struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_sigaction = on_signal; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; if (sigaction(SIGINT, &sa, NULL) != 0) { perror("sigaction SIGINT"); return 1; }; if (sigaction(SIGCHLD, &sa, NULL) != 0) { perror("sigaction SIGCHLD"); return 1; }; if (sigaction(SIGTERM, &sa, NULL) != 0) { perror("sigaction SIGTERM"); return 1; }; if (sigaction(SIGHUP, &sa, NULL) != 0) // SIGHUP is sent when the power button is pressed { perror("sigaction SIGHUP"); return 1; }; if (mkdir("/sem", 01777) != 0) { perror("mkdir /run/sem"); return 1; }; loadmods(); printf("init: initializing partitions...\n"); init_parts(); printf("init: looking for root filesystem...\n"); if (try_mount_root() != 0) { printf("init: failed to find the root filesystem!\n"); return 1; }; printf("init: setting up second-level filesystem...\n"); if (mount("bind", "/dev", "/rootfs/dev", 0, NULL, 0) != 0) { perror("init: bind /dev"); return 1; }; if (mount("bind", "/proc", "/rootfs/proc", 0, NULL, 0) != 0) { perror("init: bind /proc"); return 1; }; if (mount("bind", "/initrd", "/rootfs/initrd", 0, NULL, 0) != 0) { perror("init: bind /initrd"); return 1; }; if (mount("bind", "/run", "/rootfs/run", 0, NULL, 0) != 0) { perror("init: bind /run"); return 1; }; if (mount("bind", "/run", "/rootfs/var/run", 0, NULL, 0) != 0) { perror("init: bind /var/run"); return 1; }; printf("init: setting up fsinfo...\n"); int fd = open("/run/fsinfo", O_WRONLY | O_CREAT | O_EXCL, 0644); if (fd == -1) { perror("init: open /run/fsinfo"); return 1; }; struct __fsinfo_record record; memset(&record, 0, sizeof(struct __fsinfo_record)); strcpy(record.__image, rootImage); strcpy(record.__mntpoint, "/"); write(fd, &record, sizeof(struct __fsinfo_record)); strcpy(record.__image, "none"); strcpy(record.__mntpoint, "/dev"); write(fd, &record, sizeof(struct __fsinfo_record)); strcpy(record.__mntpoint, "/proc"); write(fd, &record, sizeof(struct __fsinfo_record)); strcpy(record.__mntpoint, "/initrd"); write(fd, &record, sizeof(struct __fsinfo_record)); strcpy(record.__mntpoint, "/run"); write(fd, &record, sizeof(struct __fsinfo_record)); strcpy(record.__mntpoint, "/var/run"); write(fd, &record, sizeof(struct __fsinfo_record)); close(fd); printf("init: executing startup script...\n"); if (fork() == 0) { if (chdir("/rootfs") != 0) { fprintf(stderr, "init: cannot switch to /rootfs: %s\n", strerror(errno)); _exit(1); }; if (chroot("/rootfs") != 0) { fprintf(stderr, "init: failed to set root directory to /rootfs: %s\n", strerror(errno)); _exit(1); }; execl("/bin/sh", "/bin/sh", "/etc/init/startup.sh", NULL); perror("init: exec"); _exit(1); }; while (1) { pause(); if (shouldHalt) { tcsetpgrp(0, getpgrp()); printf("init: received shutdown request\n"); int fd = open("/run/down-action", O_RDONLY); char downAction[256]; memset(downAction, 0, 256); downAction[read(fd, downAction, 16)] = 0; close(fd); int action = _GLIDIX_DOWN_HALT; if (strcmp(downAction, "poweroff") == 0) { action = _GLIDIX_DOWN_POWEROFF; } else if (strcmp(downAction, "reboot") == 0) { action = _GLIDIX_DOWN_REBOOT; }; shutdownSystem(action); } else if ((shouldRunPoweroff) && (!ranPoweroff)) { ranPoweroff = 1; if (fork() == 0) { if (execl("/usr/bin/halt", "poweroff", NULL) == -1) { perror("exec poweroff"); fprintf(stderr, "forcing shutdown\n"); kill(1, SIGTERM); exit(1); }; }; }; }; } else { fprintf(stderr, "%s: not allowed to execute with pid other than 1!\n", argv[0]); return 1; }; return 0; };
static void lock_cachefile(int type) { struct flock fl = { .l_len = 0, .l_start = 0, .l_whence = SEEK_SET, }; fl.l_pid = getpid(); fl.l_type = type; if (verbose) output(2, "waiting on lock for cachefile\n"); if (fcntl(cachefile, F_SETLKW, &fl) == -1) { perror("fcntl F_SETLKW"); return; } if (verbose) output(2, "took lock for cachefile\n"); } static void unlock_cachefile(void) { struct flock fl = { .l_len = 0, .l_start = 0, .l_whence = SEEK_SET, }; fl.l_pid = getpid(); fl.l_type = F_UNLCK; if (fcntl(cachefile, F_SETLK, &fl) == -1) { perror("fcntl F_UNLCK F_SETLK "); return; } if (verbose) output(2, "dropped lock for cachefile\n"); } static unsigned int valid_proto(unsigned int family) { const char *famstr; famstr = get_domain_name(family); /* Not used for creating sockets. */ if (strncmp(famstr, "UNSPEC", 9) == 0) return FALSE; if (strncmp(famstr, "BRIDGE", 9) == 0) return FALSE; if (strncmp(famstr, "SECURITY", 11) == 0) return FALSE; /* Not actually implemented (or now removed). */ if (strncmp(famstr, "NETBEUI", 10) == 0) return FALSE; if (strncmp(famstr, "ASH", 6) == 0) return FALSE; if (strncmp(famstr, "ECONET", 9) == 0) return FALSE; if (strncmp(famstr, "SNA", 6) == 0) return FALSE; if (strncmp(famstr, "WANPIPE", 10) == 0) return FALSE; /* Needs root. */ if (orig_uid != 0) { if (strncmp(famstr, "KEY", 6) == 0) return FALSE; if (strncmp(famstr, "PACKET", 9) == 0) return FALSE; if (strncmp(famstr, "LLC", 6) == 0) return FALSE; } return TRUE; } static bool write_socket_to_cache(struct socket_triplet *st) { unsigned int buffer[3]; int n; if (cachefile == -1) return FALSE; buffer[0] = st->family; buffer[1] = st->type; buffer[2] = st->protocol; n = write(cachefile, &buffer, sizeof(int) * 3); if (n == -1) { outputerr("something went wrong writing the cachefile! : %s\n", strerror(errno)); return FALSE; } return TRUE; } static bool generate_socket(unsigned int family, unsigned int protocol, unsigned int type) { struct socket_triplet st; int fd; st.family = family; st.type = type; st.protocol = protocol; fd = open_socket(st.family, st.type, st.protocol); if (fd > -1) { write_socket_to_cache(&st); return TRUE; } output(2, "Couldn't open socket %d:%d:%d. %s\n", family, type, protocol, strerror(errno)); return FALSE; } static bool generate_specific_socket(int family) { struct socket_triplet st; int fd; st.family = family; BUG_ON(st.family >= ARRAY_SIZE(no_domains)); if (no_domains[st.family]) return FALSE; if (get_domain_name(st.family) == NULL) return FALSE; if (valid_proto(st.family) == FALSE) { outputerr("Can't do protocol %s\n", get_domain_name(st.family)); return FALSE; } st.protocol = rnd() % 256; if (sanitise_socket_triplet(&st) == -1) rand_proto_type(&st); fd = open_socket(st.family, st.type, st.protocol); if (fd == -1) { output(0, "Couldn't open socket (%d:%d:%d). %s\n", st.family, st.type, st.protocol, strerror(errno)); return FALSE; } return write_socket_to_cache(&st); } #define NR_SOCKET_FDS 50 static bool generate_sockets(void) { int i, r, ret = FALSE; bool domains_disabled = FALSE; cachefile = creat(cachefilename, S_IWUSR|S_IRUSR); if (cachefile == -1) { outputerr("Couldn't open cachefile for writing! (%s)\n", strerror(errno)); return FALSE; } lock_cachefile(F_WRLCK); if (do_specific_domain == TRUE) { while (nr_sockets < NR_SOCKET_FDS) { ret = generate_specific_socket(specific_domain); if (ret == FALSE) return FALSE; } goto out_unlock; } /* * check if all domains are disabled. */ for (i = 0; i < (int)ARRAY_SIZE(no_domains); i++) { if (no_domains[i] == FALSE) { domains_disabled = FALSE; break; } else { domains_disabled = TRUE; } } if (domains_disabled == TRUE) { output(0, "All domains disabled!\n"); goto out_unlock; } for (i = 0; i < TRINITY_PF_MAX; i++) { const struct netproto *proto = net_protocols[i].proto; struct socket_triplet *triplets; unsigned int j; if (no_domains[i] == TRUE) continue; /* check for ctrl-c again. */ if (shm->exit_reason != STILL_RUNNING) goto out_unlock; if (proto == NULL) continue; if (proto->nr_triplets == 0) continue; triplets = proto->valid_triplets; for (j = 0; j < proto->nr_triplets; j++) ret |= generate_socket(triplets[j].family, triplets[j].protocol, triplets[j].type); if (proto->nr_privileged_triplets == 0) continue; if (orig_uid != 0) continue; triplets = proto->valid_privileged_triplets; for (j = 0; j < proto->nr_privileged_triplets; j++) ret |= generate_socket(triplets[j].family, triplets[j].protocol, triplets[j].type); } /* This is here temporarily until we have sufficient ->valid_proto's */ while (nr_sockets < NR_SOCKET_FDS) { r = rnd() % TRINITY_PF_MAX; for (i = 0; i < 10; i++) generate_specific_socket(r); } out_unlock: if (cachefile != -1) { unlock_cachefile(); close(cachefile); } return ret; }
void* slam_junk(void *data) { int fd, fd_rand; int pages, bytes_wrote, ret; char fname[100]; char buff[4096]; gen_random_filename(fname, sizeof(fname)); pthread_cleanup_push(slam_cleanup, fname); while(1) { // O_SYNC tried fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXO); if(fd < 0) { printf("open:%s:\n",fname); perror("open:"); pthread_exit(NULL); } fd_rand = open("/dev/zero", O_RDONLY); if(fd_rand < 0) { perror("open:/dev/zero:"); close(fd); pthread_exit(NULL); } //pages = random()%max_pages + 1; pages = max_pages; bytes_wrote = 0; while(pages--) { if((ret = read(fd_rand, buff, sizeof(buff)))<0) { perror("read:"); close(fd_rand); close(fd); pthread_exit(NULL); } if((ret = write(fd, buff, ret))<0) { perror("write:"); close(fd_rand); close(fd); pthread_exit(NULL); } bytes_wrote+=ret; total_bytes_written += bytes_wrote; } //lets see..whether it hangs fsync(fd); close(fd); close(fd_rand); fd = open(fname, O_RDONLY); while(read(fd, buff, sizeof(buff))); close(fd); //printf("%d bytes written\n", bytes_wrote); //pthread_mutex_lock(&total_bytes_mutex); //pthread_mutex_unlock(&total_bytes_mutex); pthread_testcancel(); } pthread_cleanup_pop(0); pthread_exit(NULL); }
int main(int argc, char *argv[]) { int ret; int i; if(argc < 6) { printf("Usage: fs_slammer <hddisk> <dir> <no. of files> <no-of-pages> <time in secs> <rw>\n"); return -1; } time_t tt; time(&tt); srandom(tt); char fs_path[256]; char *hd_name; struct stat stat_buf; char **argp =++argv; hd_name = (char *)malloc(10); strcpy(hd_name, *argp++); if((ret = stat(hd_name, &stat_buf))<0) { perror("stat:"); return ret; } strcpy(fs_path, *argp++); if((ret = stat(fs_path, &stat_buf))<0) { perror("stat:"); return ret; } if((ret=chdir(fs_path))<0) { printf("%s:\n", fs_path); perror("chdir:"); return ret; } int no_threads = 0; sscanf(*argp++, "%d", &no_threads); sscanf(*argp++, "%d", &max_pages); int slam_time; sscanf(*argp++, "%d", &slam_time); char rw[4]; sscanf(*argp++, "%s", rw); pthread_t *read_threads; pthread_t *slam_threads; if(strchr(rw, 'w')) { slam_threads = (pthread_t*)malloc(sizeof(pthread_t)*no_threads); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); for(i = 0; i < no_threads; i++) { if((ret = pthread_create(slam_threads+i, &attr, slam_junk, NULL))) { perror("pthread_create:"); return ret; } } } if(strchr(rw, 'r')) { read_threads = (pthread_t*)malloc(sizeof(pthread_t)*no_threads); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); for(i = 0; i < no_threads; i++) { if((ret = pthread_create(read_threads+i, &attr, raw_reader, hd_name))) { perror("pthread_create:"); return ret; } } } signal(SIGINT, termination_hdlr); signal(SIGTERM, termination_hdlr); signal(SIGQUIT, termination_hdlr); if(slam_time <0) pause(); else sleep(slam_time); for(i = 0; i < no_threads; i++) { if(strchr(rw, 'w')) pthread_cancel(slam_threads[i]); if(strchr(rw, 'r')) pthread_cancel(read_threads[i]); } printf("Total bytes written = %lu\n", total_bytes_written); printf("Total bytes raw read = %lu\n", total_bytes_read); pthread_exit(NULL); }
static void setRaw(int fd, int baud, int databits, char parity, unsigned stopBits, struct termios &oldState) { tcgetattr(fd,&oldState); /* set raw mode for keyboard input */ struct termios newState = oldState; newState.c_cc[VMIN] = 1; bool nonStandard = false ; unsigned baudConst ; if (baudRateToConst(baud, baudConst)) { cfsetispeed(&newState, baudConst); cfsetospeed(&newState, baudConst); } else { cfsetispeed(&newState,B38400); cfsetospeed(&newState,B38400); bool worked = false ; struct serial_struct nuts; int rval = ioctl(fd, TIOCGSERIAL, &nuts); if (0 == rval) { unsigned const divisor = nuts.baud_base / baud ; nuts.custom_divisor = divisor ; nuts.flags &= ~ASYNC_SPD_MASK; nuts.flags |= ASYNC_SPD_CUST; rval = ioctl(fd, TIOCSSERIAL, &nuts); if (0 == rval) { printf("baud changed\n"); rval = ioctl(fd, TIOCGSERIAL, &nuts); if (0 == rval) { printf("divisor is now %u\n", nuts.custom_divisor); } else perror("TIOCGSERIAL2"); } else perror("TIOCSSERIAL"); } else perror("TIOCGSERIAL"); } // non-standard serial // // Note that this doesn't appear to work! // Reads always seem to be terminated at 16 chars! // newState.c_cc[VTIME] = 0; // 1/10th's of a second, see http://www.opengroup.org/onlinepubs/007908799/xbd/termios.html newState.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS); // Mask character size to 8 bits, no parity, Disable hardware flow control if ('E' == parity) { newState.c_cflag |= PARENB ; newState.c_cflag &= ~PARODD ; } else if ('O' == parity) { newState.c_cflag |= PARENB | PARODD ; } else if ('S' == parity) { newState.c_cflag |= PARENB | IGNPAR | CMSPAR ; newState.c_cflag &= ~PARODD ; } else if ('M' == parity) { newState.c_cflag |= PARENB | IGNPAR | CMSPAR | PARODD ; } else { } // no parity... already set newState.c_cflag |= (CLOCAL | CREAD |CS8); // Select 8 data bits if (7 == databits) { newState.c_cflag &= ~CS8 ; } if (1 != stopBits) newState.c_cflag |= CSTOPB ; newState.c_lflag &= ~(ICANON | ECHO); // set raw mode for input newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC); //no software flow control newState.c_oflag &= ~OPOST; //raw output tcsetattr(fd, TCSANOW, &newState); }
void error(char *msg) { perror(msg); exit(1); }
void setup_every_copy() { int i; char tmpfilename[256] = ""; /* Initialize test dir and file names */ sprintf(pathname, "readlinkattestdir%d", getpid()); sprintf(dpathname, "dreadlinkattestdir%d", getpid()); sprintf(testfile, "readlinkattestfile%d.txt", getpid()); sprintf(dtestfile, "dreadlinkattestfile%d.txt", getpid()); sprintf(testfile2, "readlinkattestdir%d/readlinkattestfile%d.txt", getpid(), getpid()); sprintf(dtestfile2, "dreadlinkattestdir%d/dreadlinkattestfile%d.txt", getpid(), getpid()); sprintf(testfile3, "/tmp/readlinkattestfile%d.txt", getpid()); sprintf(dtestfile3, "/tmp/dreadlinkattestfile%d.txt", getpid()); ret = mkdir(pathname, 0700); if (ret < 0) { perror("mkdir: "); exit(-1); } ret = mkdir(dpathname, 0700); if (ret < 0) { perror("mkdir: "); exit(-1); } dirfd = open(dpathname, O_DIRECTORY); if (dirfd < 0) { perror("open: "); exit(-1); } fd = open(testfile, O_CREAT | O_RDWR, 0600); if (fd < 0) { perror("open: "); exit(-1); } ret = symlink(testfile, dtestfile); if (ret < 0) { perror("symlink: "); exit(-1); } fd = open(testfile2, O_CREAT | O_RDWR, 0600); if (fd < 0) { perror("open: "); exit(-1); } tmpfilename[0] = '\0'; strcat(strcat(tmpfilename, "../"), testfile2); ret = symlink(tmpfilename, dtestfile2); if (ret < 0) { perror("symlink: "); exit(-1); } fd = open(testfile3, O_CREAT | O_RDWR, 0600); if (fd < 0) { perror("open: "); exit(-1); } ret = symlink(testfile3, dtestfile3); if (ret < 0) { perror("symlink: "); exit(-1); } fds[0] = fds[1] = dirfd; fds[2] = fd; fds[3] = 100; fds[4] = AT_FDCWD; filenames[0] = filenames[2] = filenames[3] = filenames[4] = dtestfile; filenames[1] = dtestfile3; for (i = 0; i < TEST_CASES; i++) expected_buff[i][0] = '\0'; strcat(strcat(expected_buff[0], "../"), testfile2); strcat(expected_buff[1], testfile3); strcat(expected_buff[2], ""); strcat(expected_buff[3], ""); strcat(expected_buff[4], testfile); }
int main(void) { int status; pid_t pid; // Allocate a shared block. share = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if ((pid = fork()) < 0) { perror("fork"); abort(); } else if (pid == 0) { ptrace(PTRACE_TRACEME, 0, NULL, NULL); kill(getpid(), SIGSTOP); share[0] = 1; // open("foo.bar", O_WRONLY | O_CREAT); _exit(0); } #if 0 if (waitpid(pid, &status, 0) < 0) { perror("waitpid"); abort(); } assert(WIFSTOPPED(status)); assert(WSTOPSIG(status) == SIGSTOP); if (ptrace(PTRACE_SYSCALL, pid, NULL, NULL) < 0) { perror("ptrace(PTRACE_SYSCALL, ...)"); ptrace(PTRACE_KILL, pid, NULL, NULL); abort(); } if (waitpid(pid, &status, 0) < 0) { perror("waitpid"); ptrace(PTRACE_KILL, pid, NULL, NULL); abort(); } assert(WIFSTOPPED(status)); assert(WSTOPSIG(status) == SIGTRAP); #endif printf("ORIG_ACCUM %d and ORIG_EAX %d, DR_OFFSET(0) %d DR_OFFSET(1) %d total %d\n",ORIG_ACCUM, ORIG_EAX, DR_OFFSET(0), DR_OFFSET(1), sizeof(struct user)); #if 0 if(ptrace(PTRACE_ATTACH, pid, 0, 0) < 0) { perror("ptrace(PTRACE_ATTACH, ...)" ); ptrace(PTRACE_KILL, pid, NULL, NULL); abort(); } #endif /* Change the system call to something invalid, so it will be denied. */ // if (ptrace(PTRACE_POKEUSER, pid, ORIG_ACCUM, 0xbadca11) < 0) { if (ptrace(PTRACE_POKEUSER, pid, DR_OFFSET(0), share) < 0) { perror("ptrace(PTRACE_POKEUSER, ...)"); ptrace(PTRACE_KILL, pid, NULL, NULL); abort(); } /* Let the process continue */ ptrace(PTRACE_CONT, pid, NULL, NULL); waitpid(pid, &status, 0); // assert(WIFEXITED(status)); exit(WEXITSTATUS(status)); }
int main(int argc, char **argv) { int sfd = 0, s = 0; int efd = 0; struct epoll_event event = {}; struct epoll_event *events = NULL; if (argc != 2) { fprintf(stderr, "usage: %s [port]\n", argv[0]); exit(EXIT_FAILURE); } sfd = create_and_bind(argv[1]); if (sfd == -1) {abort();} fprintf(stdout, "sfd: %d\n", sfd); s = make_socket_non_blocking(sfd); if (s == -1) {abort();} s = listen(sfd, SOMAXCONN); if (s == -1) { perror("listen"); abort(); } efd = epoll_create(256); if (efd == -1) { perror("epoll_create1"); abort(); } event.data.fd = sfd; event.events = EPOLLIN | EPOLLET; s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event); if (s == -1) { perror("epoll_ctl"); abort(); } //Buffer where events are returned events = calloc(MAXEVENTS, sizeof(event)); fprintf(stdout, "before event loop\n"); //The event loop while (1) { int n, i; n = epoll_wait(efd, events, MAXEVENTS, -1); fprintf(stdout, "epoll wait return: %d\n", n); for (i=0; i<n; i++) { fprintf(stdout, "events[%d].data.fd=%d\n", i, events[i].data.fd); if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { //an error has occured on this fd, or the socket is not ready for reading fprintf(stderr, "epoll error\n"); close(events[i].data.fd); continue; } else if (sfd == events[i].data.fd) { //we have a notification on the listening socket, which means one or more //incoming connections fprintf(stdout, "sfd == events[i].data.fd\n"); while (1) { struct sockaddr in_addr = {}; socklen_t in_len = 0; int infd = 0; char hbuf[NI_MAXHOST] = {}, sbuf[NI_MAXSERV] = {}; in_len = sizeof(in_addr); infd = accept(sfd, &in_addr, &in_len); if (infd == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { //we have processed all incoming connections fprintf(stderr, "accept error: %d\n", errno); break; } else { perror("accept"); break; } } fprintf(stdout, "infd=%d\n", infd); s = getnameinfo(&in_addr, in_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV); if (s == 0) { printf("accepted connection on descriptor %d (host=%s, port=%s)\n", infd, hbuf, sbuf); } fprintf(stdout, "getnameinfo return s:%d\n", s); //make the incoming socket non-blocking and add it to the list of fds //to monitor s = make_socket_non_blocking(infd); if (s == -1) {abort();} event.data.fd = infd; event.events = EPOLLIN | EPOLLET; s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event); if (s == -1) { perror("epoll_ctl"); abort(); } } continue; } else { //we have data on the fd waiting to be read. Read and display it. We must read //whatever data is available completely, as we are running in edge-triggered //mode and won't get a notification again for the same data int done = 0; fprintf(stdout, "else\n"); while (1) { ssize_t count = 0; char buf[512] = "hello epoll"; count = read(events[i].data.fd, buf, sizeof(buf)); fprintf(stdout, "read return count=%d\n", count); if (count == -1) { //if errno == EAGAIN , that means we have read all data. //So go back to the main loop fprintf(stdout, "count==-1, errno:%d\n", errno); if (errno != EAGAIN) { perror("read"); done = 1; } break; } else if (count == 0) { //end of file. The remote has closed the connection fprintf(stdout, "count == 0\n"); done = -1; break; } printf("read data: %s\n", buf); //write the buffer to standard output s = write(STDOUT_FILENO, buf, count); if (s == -1) { perror("write"); abort(); } } if (done) { printf("closed connection on descriptor %d\n", events[i].data.fd); //closing the descriptor will make epoll remove it from the set of //descriptors which are monitored close(events[i].data.fd); } } } } free(events); events = NULL; close(sfd); return EXIT_SUCCESS; }
/* * Create the device nodes for vinum objects * * XXX - Obsolete, vinum kernel module now creates is own devices. */ void make_devices(void) { #if 0 int volno; int plexno; int sdno; int driveno; #endif if (hist) { timestamp(); fprintf(hist, "*** Created devices ***\n"); } #if 0 system("rm -rf " VINUM_DIR); /* remove the old directories */ system("mkdir -p " VINUM_DIR "/drive " /* and make them again */ VINUM_DIR "/plex " VINUM_DIR "/sd " VINUM_DIR "/vol"); if (mknod(VINUM_SUPERDEV_NAME, S_IRUSR | S_IWUSR | S_IFCHR, /* user only */ makedev(VINUM_CDEV_MAJOR, VINUM_SUPERDEV)) < 0) fprintf(stderr, "Can't create %s: %s\n", VINUM_SUPERDEV_NAME, strerror(errno)); if (mknod(VINUM_WRONGSUPERDEV_NAME, S_IRUSR | S_IWUSR | S_IFCHR, /* user only */ makedev(VINUM_CDEV_MAJOR, VINUM_WRONGSUPERDEV)) < 0) fprintf(stderr, "Can't create %s: %s\n", VINUM_WRONGSUPERDEV_NAME, strerror(errno)); superdev = open(VINUM_SUPERDEV_NAME, O_RDWR); /* open the super device */ if (mknod(VINUM_DAEMON_DEV_NAME, /* daemon super device */ S_IRUSR | S_IWUSR | S_IFCHR, /* user only */ makedev(VINUM_CDEV_MAJOR, VINUM_DAEMON_DEV)) < 0) fprintf(stderr, "Can't create %s: %s\n", VINUM_DAEMON_DEV_NAME, strerror(errno)); #endif if (ioctl(superdev, VINUM_GETCONFIG, &vinum_conf) < 0) { perror("Can't get vinum config"); return; } #if 0 for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) make_vol_dev(volno, 0); for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++) make_plex_dev(plexno, 0); for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) make_sd_dev(sdno); /* Drives. Do this later (both logical and physical names) XXX */ for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) { char filename[PATH_MAX]; /* for forming file names */ get_drive_info(&drive, driveno); if (drive.state > drive_referenced) { sprintf(filename, "ln -s %s " VINUM_DIR "/drive/%s", drive.devicename, drive.label.name); system(filename); } } #endif }
int main() { socklen_t clt_addr_len; int listen_fd; int com_fd; int old_fd; int ret; int i; static char recv_buf[1024]; int len; struct sockaddr_un clt_addr; struct sockaddr_un srv_addr; listen_fd=socket(PF_UNIX,SOCK_STREAM,0); if(listen_fd<0){ perror("cannot create listening socket"); return 1; } srv_addr.sun_family=AF_UNIX; strncpy(srv_addr.sun_path,UNIX_DOMAIN,sizeof(srv_addr.sun_path)-1); unlink(UNIX_DOMAIN); ret=bind(listen_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr)); if(ret==-1){ perror("cannot bind server socket"); close(listen_fd); unlink(UNIX_DOMAIN); return 1; } ret=listen(listen_fd,1); if(ret==-1){ perror("cannot listen the client connect request"); close(listen_fd); unlink(UNIX_DOMAIN); return 1; } len=sizeof(clt_addr); com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len); if(com_fd<0){ perror("cannot accept client connect request"); close(listen_fd); unlink(UNIX_DOMAIN); return 1; } printf("\n=====info=====\n"); for(i=0;i<4;i++){ memset(recv_buf,0,1024); int num=read(com_fd,recv_buf,sizeof(recv_buf)); printf("Message from client (%d)) :%s\n",num,recv_buf); } close(com_fd); close(listen_fd); unlink(UNIX_DOMAIN); return 0; }
/* Initialize the /dev/fbN device for a specific screen */ static int pvrQwsInitFbScreen(int screen) { struct fb_var_screeninfo var; struct fb_fix_screeninfo fix; unsigned long start; unsigned long length; int width, height, stride; PVR2DFORMAT format; void *mapped; int fd, bytesPerPixel; char name[64]; PVR2DMEMINFO *memInfo; unsigned long pageAddresses[2]; /* Bail out if already initialized, or the number is incorrect */ if (screen < 0 || screen >= PVRQWS_MAX_SCREENS) return 0; if (pvrQwsDisplay.screens[screen].initialized) return 1; /* Open the framebuffer and fetch its properties */ sprintf(name, "/dev/fb%d", screen); fd = open(name, O_RDWR, 0); if (fd < 0) { perror(name); return 0; } if (ioctl(fd, FBIOGET_VSCREENINFO, &var) < 0) { perror("FBIOGET_VSCREENINFO"); close(fd); return 0; } if (ioctl(fd, FBIOGET_FSCREENINFO, &fix) < 0) { perror("FBIOGET_FSCREENINFO"); close(fd); return 0; } width = var.xres; height = var.yres; bytesPerPixel = var.bits_per_pixel / 8; stride = fix.line_length; format = PVR2D_1BPP; if (var.bits_per_pixel == 16) { if (var.red.length == 5 && var.green.length == 6 && var.blue.length == 5 && var.red.offset == 11 && var.green.offset == 5 && var.blue.offset == 0) { format = PVR2D_RGB565; } if (var.red.length == 4 && var.green.length == 4 && var.blue.length == 4 && var.transp.length == 4 && var.red.offset == 8 && var.green.offset == 4 && var.blue.offset == 0 && var.transp.offset == 12) { format = PVR2D_ARGB4444; } } else if (var.bits_per_pixel == 32) { if (var.red.length == 8 && var.green.length == 8 && var.blue.length == 8 && var.transp.length == 8 && var.red.offset == 16 && var.green.offset == 8 && var.blue.offset == 0 && var.transp.offset == 24) { format = PVR2D_ARGB8888; } } if (format == PVR2D_1BPP) { fprintf(stderr, "%s: could not find a suitable PVR2D pixel format\n", name); close(fd); return 0; } start = fix.smem_start; length = var.xres_virtual * var.yres_virtual * bytesPerPixel; if (screen == 0) { /* We use PVR2DGetFrameBuffer to map the first screen. On some chipsets it is more reliable than using PVR2DMemWrap */ mapped = 0; memInfo = 0; } else { /* Other screens: map the framebuffer region into memory */ mapped = mmap(0, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (!mapped || mapped == (void *)(-1)) { perror("mmap"); close(fd); return 0; } /* Allocate a PVR2D memory region for the framebuffer */ memInfo = 0; if (pvrQwsDisplay.context) { pageAddresses[0] = start & 0xFFFFF000; pageAddresses[1] = 0; if (PVR2DMemWrap (pvrQwsDisplay.context, mapped, PVR2D_WRAPFLAG_CONTIGUOUS, length, pageAddresses, &memInfo) != PVR2D_OK) { munmap(mapped, length); close(fd); return 0; } } } /* We don't need the file descriptor any more */ close(fd); /* The framebuffer is ready, so initialize the PvrQwsScreenInfo */ pvrQwsDisplay.screens[screen].screenRect.x = 0; pvrQwsDisplay.screens[screen].screenRect.y = 0; pvrQwsDisplay.screens[screen].screenRect.width = width; pvrQwsDisplay.screens[screen].screenRect.height = height; pvrQwsDisplay.screens[screen].screenStride = stride; pvrQwsDisplay.screens[screen].pixelFormat = format; pvrQwsDisplay.screens[screen].bytesPerPixel = bytesPerPixel; pvrQwsDisplay.screens[screen].screenDrawable = 0; if (mapped) { /* Don't set these fields if mapped is 0, because PVR2DGetFrameBuffer may have already been called and set them */ pvrQwsDisplay.screens[screen].frameBuffer = memInfo; pvrQwsDisplay.screens[screen].mapped = mapped; } pvrQwsDisplay.screens[screen].mappedLength = length; pvrQwsDisplay.screens[screen].screenStart = start; pvrQwsDisplay.screens[screen].needsUnmap = (mapped != 0); pvrQwsDisplay.screens[screen].initialized = 1; return 1; }
/** @main Application entry-point. */ int main(int argc, char* argv[]) { int c; strcpy(initcmd, DEF_CMD_INIT); while (true) { static struct option long_options[] = { {"adapter", required_argument, 0, 'a'}, {"remote-adapter", required_argument, 0, 'b'}, {"close", no_argument, 0, 'c'}, {"blink-on-receive", no_argument, 0, 'k'}, {"log-packets", no_argument, 0, 'p'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "a:b:ckpvV?", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 'a': tc_eth_adapter = optarg; break; case 'b': tc_eth_remoteAdapter = optarg; break; case 'c': exitReason = 0; break; case 'p': dbg_logPackets = true; break; case 'v': dbg_debugOut = true; break; case 'k': dbg_blinkOnReceive = true; break; case 'V': printf("Asus-TCCI (TrendChip Command Interpreter), version %s, build %s\n", VERSION, VERSION_BUILD); printf(" by %s. Sources and updates: %s\n", AUTHOR, URL); return EC_NORMAL; case 'h': /* getopt_long already printed an error message. */ printf("usage: %s -V|--version\n", argv[0]); printf("or: %s [-a|--adapter=\"%s\"] [-b|--remote-adapter=\"%s\"] [-c|--close] [-p|--log-packets] [-v|--verbose] [-k|--blink-on-receive] [<%s>]\n", argv[0], tc_eth_adapter, tc_eth_remoteAdapter, initcmd); return EC_NORMAL; default: return 9; } } /* Print any remaining command line arguments (not options). */ if (optind < argc) { initcmd[0] = '\0'; // Clear string while (optind < argc) strncat(initcmd, argv[optind++], sizeof(initcmd)); } debugf("-- Starting...\n"); // Initialize in-socket tc_eth_sockIn = socket(AF_INET, SOCK_DGRAM, 0); if (tc_eth_sockIn < 0) { errorf("-- E: Input socket init failed!\n"); return EC_APIFAIL; } /*debugf("-- dbg_debugOut = %d, dbg_logPackets = %d, tc_eth_adapter = \"%s\", initcmd = \"%s\"\n", dbg_debugOut, dbg_logPackets, tc_eth_adapter, initcmd);*/ // Initialize adapter eth_adapterId = if_nametoindex(tc_eth_adapter); initAdapter(tc_eth_adapter); // Initialize out-socket tc_eth_sockOut = socket(AF_PACKET,SOCK_RAW, htons(ETH_P_ALL)); if (tc_eth_sockOut < 0) { errorf("-- E: Output socket init failed!\n"); return EC_APIFAIL; } // Acquired MACs debugf("Remote (TrendChip) MAC: "); printmac(debugf, tc_eth_remoteMac); debugf("\nLocal (terminal) MAC: "); printmac(debugf, tc_eth_localMac); // Initial command execution debugf("\n-- Phase 2 - Perform init-command (%s)\n", initcmd); if (!tc_exec(initcmd)) return EC_NETFAIL; // Interactive shell char inbuff[TC_CMD_MAX_LEN]; fd_set rfds; struct timeval tv; int retval; while(exitReason < 0) { FD_ZERO(&rfds); FD_SET(0, &rfds); tv.tv_sec = 0; tv.tv_usec = 100000; //100ms retval = select(1, &rfds, NULL, NULL, &tv); if (retval == -1){ perror("-- select(stdin)"); return EC_APIFAIL; } else if (retval){ debugf("-- Gathering input... "); char* cmd = fgets(inbuff, TC_CMD_MAX_LEN, stdin); if (cmd[strlen(cmd)-1] == '\n') cmd[strlen(cmd)-1] = '\0'; // Trim the trailing '\n' char. debugf("Got '%s'\n", cmd); if (cmd[0] == '\0') {} // Do nothing on blank lines. else if (strcmp(cmd, "!q") == 0 || strcmp(cmd, "!quit") == 0) exitReason = EC_NORMAL; else if (strcmp(cmd, "!v") == 0 || strcmp(cmd, "!verbose") == 0) errorf("-- Verbose output is now %s.\n", (dbg_debugOut = !dbg_debugOut) ? "ON" : "OFF"); else if (strcmp(cmd, "!p") == 0 || strcmp(cmd, "!logpackets") == 0) errorf("-- Packet logging is now %s.\n", (dbg_logPackets = !dbg_logPackets) ? "ON" : "OFF"); else if (strcmp(cmd, "!k") == 0 || strcmp(cmd, "!blink") == 0) errorf("-- Blink-on-receive is now %s.\n", (dbg_blinkOnReceive = !dbg_blinkOnReceive) ? "ON" : "OFF"); else if (strcmp(cmd, "!h") == 0 || strcmp(cmd, "!help") == 0) errorf("-- Valid client commands: \n-- ![blin]k, !h[elp], ![log]p[ackets], !q[uit], !v[erbose].\n"); else if (cmd[0] == '!') errorf("-- Unrecognized client command. Please try \"!help\" if you aren't sure.\n"); else if (!tc_exec(cmd)) errorf("-- W: Command request fail!\n"); //exitReason = EC_NETFAIL; // I/O error? } if (!tc_listen()) exitReason = EC_NETFAIL; } if (tc_eth_sockIn) close(tc_eth_sockIn); else debugf("-- W: Input socket already closed!"); if (tc_eth_sockOut) close(tc_eth_sockOut); else debugf("-- W: Output socket already closed!"); debugf("-- Connection closed, reason = %d (-1).\n", exitReason); return exitReason-1; }
void receiveFile(char *hostName, unsigned int port) { struct sockaddr_in sin; if ((serverSocketDescriptor = createTcpServerSocket(hostName, port, &sin, 5)) == -1) { printf("Creation socket error\n"); exit(EXIT_FAILURE); } char replyBuf[replyBufSize], buf[bufSize]; while (1) { printf("\nAwaiting connections...\n"); remoteSocketDescriptor = accept(serverSocketDescriptor, NULL, NULL); struct sigaction urgSignal; urgSignal.sa_handler = urgHandler; sigaction(SIGURG, &urgSignal, NULL); if (fcntl(remoteSocketDescriptor, F_SETOWN, getpid()) < 0) { perror("fcntl()"); exit(-1); } // Receive file name and file size if (ReceiveToBuf (remoteSocketDescriptor, replyBuf, sizeof(replyBuf)) <= 0) { close(remoteSocketDescriptor); fprintf(stderr, "Error receiving file name and file size\n"); continue; } char *fileName = strtok(replyBuf, ":"); if (fileName == NULL) { close(remoteSocketDescriptor); fprintf(stderr, "Bad file name\n"); continue; } char *size = strtok(NULL, ":"); if (size == NULL) { close(remoteSocketDescriptor); fprintf(stderr, "Bad file size\n"); continue; } long fileSize = atoi(size); printf("File size: %ld, file name: %s\n", fileSize, fileName); FILE *file = CreateReceiveFile(fileName, "Received_files"); if (file == NULL) { perror("Create file error"); exit(EXIT_FAILURE); } // Receiving file int recvSize; long totalBytesReceived = 0; while (totalBytesReceived < fileSize) { if (sockatmark(remoteSocketDescriptor) == 1 && oobFlag == 1) { printf("Receive OOB byte. Total bytes received: %ld\n", totalBytesReceived); char oobBuf; int n = recv(remoteSocketDescriptor, &oobBuf, 1, MSG_OOB); if (n == -1) fprintf(stderr, "receive OOB error\n"); oobFlag = 0; } recvSize = recv(remoteSocketDescriptor, buf, sizeof(buf), 0); if (recvSize > 0) { totalBytesReceived += recvSize; fwrite(buf, 1, recvSize, file); } else if (recvSize == 0) { printf("Received EOF\n"); break; } else { if (errno == EINTR) continue; else { perror("receive error"); break; } } } fclose(file); printf("Receiving file completed. %ld bytes received.\n", totalBytesReceived); close(remoteSocketDescriptor); } }
// Shamelessly stolen from PCVideoServer int DashboardCommandServer() { /* Setup to PC sockets */ struct sockaddr_in serverAddr; int sockAddrSize = sizeof(serverAddr); int pcSock = ERROR; bzero ((char *) &serverAddr, sockAddrSize); serverAddr.sin_len = (u_char) sockAddrSize; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons (kDashboardCommandPort); serverAddr.sin_addr.s_addr = htonl (INADDR_ANY); while (true) { taskSafe(); // Create the socket. if ((pcSock = socket (AF_INET, SOCK_STREAM, 0)) == ERROR) { perror ("socket"); continue; } // Set the TCP socket so that it can be reused if it is in the wait state. int reuseAddr = 1; setsockopt(pcSock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&reuseAddr), sizeof(reuseAddr)); // Bind socket to local address. if (bind (pcSock, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR) { perror ("bind"); close (pcSock); continue; } // Create queue for client connection requests. if (listen (pcSock, 1) == ERROR) { perror ("listen"); close (pcSock); continue; } struct sockaddr_in clientAddr; int clientAddrSize; int newPCSock = accept (pcSock, reinterpret_cast<sockaddr*>(&clientAddr), &clientAddrSize); if (newPCSock == ERROR) { close(pcSock); continue; } char cmdBuffer[32]; char *pBuffer; while(1) { int numBytes = 0; pBuffer = cmdBuffer; while (numBytes < 2 || (*(pBuffer-2) != '\r' && *(pBuffer-1) != '\n')) { numBytes += read(newPCSock, pBuffer++, 1); } char command = cmdBuffer[0]; switch (command) { case 'E': speedJag.EnableControl(); //printf("Enable\n"); break; case 'D': speedJag.DisableControl(); //printf("Disable\n"); break; case 'G': { double P, I, D; memcpy((char*)&P, cmdBuffer+1, sizeof(double)); memcpy((char*)&I, cmdBuffer+9, sizeof(double)); memcpy((char*)&D, cmdBuffer+17, sizeof(double)); speedJag.SetPID(P, I, D); //printf("Set- P: %f I: %f D: %f\n", P, I, D); //P = speedJag.GetP(); //I = speedJag.GetI(); //D = speedJag.GetD(); //printf("Get- P: %f I: %f D: %f\n", P, I, D); } break; } //no point in running too fast - Wait(0.01); } // Clean up close (newPCSock); newPCSock = ERROR; close (pcSock); pcSock = ERROR; taskUnsafe(); Wait(0.1); } return (OK); }
int main(int argc, char **argv) { FILE *fp; struct rtnl_handle rth; int family = AF_UNSPEC; unsigned groups = ~0U; int llink = 0; int laddr = 0; int lroute = 0; char *file = NULL; while (argc > 1) { if (matches(argv[1], "-family") == 0) { argc--; argv++; if (argc <= 1) usage(); if (strcmp(argv[1], "inet") == 0) family = AF_INET; else if (strcmp(argv[1], "inet6") == 0) family = AF_INET6; else if (strcmp(argv[1], "link") == 0) family = AF_INET6; else if (strcmp(argv[1], "help") == 0) usage(); else { fprintf(stderr, "Protocol ID \"%s\" is unknown, try \"rtmon help\".\n", argv[1]); exit(-1); } } else if (strcmp(argv[1], "-4") == 0) { family = AF_INET; } else if (strcmp(argv[1], "-6") == 0) { family = AF_INET6; } else if (strcmp(argv[1], "-0") == 0) { family = AF_PACKET; } else if (matches(argv[1], "-Version") == 0) { printf("rtmon utility, iproute2-ss%s\n", SNAPSHOT); exit(0); } else if (matches(argv[1], "file") == 0) { argc--; argv++; if (argc <= 1) usage(); file = argv[1]; } else if (matches(argv[1], "link") == 0) { llink=1; groups = 0; } else if (matches(argv[1], "address") == 0) { laddr=1; groups = 0; } else if (matches(argv[1], "route") == 0) { lroute=1; groups = 0; } else if (strcmp(argv[1], "all") == 0) { groups = ~0U; } else if (matches(argv[1], "help") == 0) { usage(); } else { fprintf(stderr, "Argument \"%s\" is unknown, try \"rtmon help\".\n", argv[1]); exit(-1); } argc--; argv++; } if (file == NULL) { fprintf(stderr, "Not enough information: argument \"file\" is required\n"); exit(-1); } if (llink) groups |= RTMGRP_LINK; if (laddr) { if (!family || family == AF_INET) groups |= RTMGRP_IPV4_IFADDR; if (!family || family == AF_INET6) groups |= RTMGRP_IPV6_IFADDR; } if (lroute) { if (!family || family == AF_INET) groups |= RTMGRP_IPV4_ROUTE; if (!family || family == AF_INET6) groups |= RTMGRP_IPV6_ROUTE; } fp = fopen(file, "w"); if (fp == NULL) { perror("Cannot fopen"); exit(-1); } if (rtnl_open(&rth, groups) < 0) exit(1); if (rtnl_wilddump_request(&rth, AF_UNSPEC, RTM_GETLINK) < 0) { perror("Cannot send dump request"); exit(1); } write_stamp(fp); if (rtnl_dump_filter(&rth, dump_msg, fp, NULL, NULL) < 0) { fprintf(stderr, "Dump terminated\n"); return 1; } init_phase = 0; if (rtnl_listen(&rth, dump_msg, (void*)fp) < 0) exit(2); exit(0); }
int main(int argc, char const * const argv[]) { if (2 >= argc) { fprintf(stderr, "Usage: %s device baud " "[databits=8 [parity=N [stopbits=1]]]\n", argv[0]); return -1; } char const *const deviceName = argv[1]; int const fdSerial = open(deviceName, O_RDWR); if (0 > fdSerial) { perror(deviceName); return -1; } fcntl(fdSerial, F_SETFD, FD_CLOEXEC); fcntl(fdSerial, F_SETFL, O_NONBLOCK); int baud = strtoul(argv[2], 0, 0); int databits = ((3 < argc) && (7 == strtoul(argv[3], 0, 0))) ? 7 : 8 ; char parity = (4 < argc) ? toupper(*argv[4]) : 'N' ; unsigned stopBits = ((5 < argc) && ('2' == *argv[5])) ? 2 : 1 ; printf("device %s opened: %u baud, %d bits, parity %c\n", deviceName, baud, databits, parity); struct termios oldSerialState; setRaw(fdSerial, baud, databits, parity, stopBits, oldSerialState); struct termios oldStdinState; tcgetattr(0,&oldStdinState); /* set raw mode for keyboard input */ struct termios newState = oldStdinState; newState.c_cc[VMIN] = 1; newState.c_lflag &= ~(ICANON | ECHO); // set raw mode for input newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC); //no software flow control newState.c_oflag &= ~OPOST; //raw output tcsetattr(0, TCSANOW, &newState); signal(SIGINT, ctrlcHandler); pollfd fds[2]; fds[0].fd = fdSerial ; fds[0].events = POLLIN | POLLERR ; fds[1].fd = fileno(stdin); fds[1].events = POLLIN | POLLERR ; while (!doExit) { ::poll(fds, 2, 1000); for (unsigned i = 0 ; i < 2 ; i++) { if (fds[i].revents & POLLIN) { char inBuf[80]; int numRead = read(fds[i].fd, inBuf, sizeof(inBuf)); if (0 < numRead) { int fdout = i ? fdSerial : 1; write(fdout,inBuf,numRead); } } } } tcsetattr(fdSerial, TCSANOW, &oldSerialState); tcsetattr(0, TCSANOW, &oldStdinState); close(fdSerial); return 0 ; }
int main(void) { ZStream *input; int pair[2], status = 0; pid_t pid; gchar *line; gsize length; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) < 0) { perror("socketpair()"); return 254; } pid = fork(); if (pid < 0) { perror("fork()"); return 254; } else if (pid != 0) { close(pair[1]); g_return_val_if_fail(write(pair[0], "1\n2\n3\n", 6) == 6, 253); g_return_val_if_fail(write(pair[0], "0123", 4) == 4, 253); g_return_val_if_fail(write(pair[0], "4567\n", 5) == 5, 253); g_return_val_if_fail(write(pair[0], "0123456789", 10) == 10, 253); g_return_val_if_fail(write(pair[0], "abc\nAabc\nabcdef\n", 16) == 16, 253); /* Because of truncate A will be eliminated */ g_return_val_if_fail(write(pair[0], "0123456789", 10) == 10, 253); g_return_val_if_fail(write(pair[0], "0123456789", 10) == 10, 253); g_return_val_if_fail(write(pair[0], "012345678\nAabcdef\n", 18) == 18, 253); /* Because of truncate A will be eliminated */ g_return_val_if_fail(write(pair[0], "012345678\nAabcdef", 17) == 17, 253); close(pair[0]); waitpid(pid, &status, 0); } else { gint rc; guint i; printf("%d\n", getpid()); sleep(1); close(pair[0]); input = z_stream_fd_new(pair[1], "sockpair input"); input = z_stream_line_new(input, 10, ZRL_EOL_NL | ZRL_TRUNCATE); i = 0; if (!z_stream_unget(input, "A", 1, NULL)) { printf("Error on unget\n"); _exit(1); } rc = z_stream_line_get(input, &line, &length, NULL); while (rc == G_IO_STATUS_NORMAL) { if (i >= (sizeof(expected_outputs) / sizeof(gchar *)) || line[0] != 'A' || strlen(expected_outputs[i]) != length - 1 || memcmp(expected_outputs[i], line + 1, length - 1) != 0) { printf("Error checking line: [%.*s] (length: %"G_GSIZE_FORMAT"), should be: %s\n", (int) length - 1, line + 1, length - 1, expected_outputs[i]); _exit(1); } else { printf("line ok: %.*s\n", (int) length, line); } if (!z_stream_unget(input, "A", 1, NULL)) { printf("Error on unget\n"); _exit(1); } rc = z_stream_line_get(input, &line, &length, NULL); i++; } if (i < (sizeof(expected_outputs) / sizeof(gchar *))) { printf("Missing output %u of %"G_GSIZE_FORMAT"\n", i, (sizeof(expected_outputs) / sizeof(gchar *))); _exit(1); } close(pair[1]); _exit(0); } return status >> 8; }
/** Aborta a execucao do programa, imprime informacoes da variavel errno e * exibe uma mensagem de erro customizavel. */ void arg_abort_exec_errno(char *error_msg) { perror(error_msg); exit(EXIT_FAILURE); }