int main() { int s[2]; /* Send-throttling. */ int rc = unix_pair(s); assert(rc == 0); int pfx0 = pfx_start(s[0]); assert(pfx0 >= 0); int pfx1 = pfx_start(s[1]); assert(pfx1 >= 0); int thr = mthrottler_start(pfx0, 1000, 10, 0, 0); assert(thr >= 0); int64_t start = now(); int i; for(i = 0; i != 95; ++i) { rc = msend(thr, "ABC", 3, -1); assert(rc == 0); } int64_t elapsed = now() - start; assert(elapsed > 80 && elapsed < 100); char buf[3]; for(i = 0; i != 95; ++i) { ssize_t sz = mrecv(pfx1, buf, sizeof(buf), -1); assert(sz == 3); } hclose(thr); hclose(pfx1); /* Recv-throttling. */ rc = unix_pair(s); assert(rc == 0); int crlf0 = crlf_start(s[0]); assert(pfx0 >= 0); int crlf1 = crlf_start(s[1]); assert(pfx1 >= 0); thr = mthrottler_start(crlf0, 0, 0, 1000, 10); assert(thr >= 0); for(i = 0; i != 95; ++i) { rc = msend(crlf1, "ABC", 3, -1); assert(rc == 0); } start = now(); for(i = 0; i != 95; ++i) { rc = mrecv(thr, buf, sizeof(buf), -1); assert(rc == 0); } elapsed = now() - start; assert(elapsed > 80 && elapsed < 100); hclose(thr); hclose(crlf1); return 0; }
/* * Watches socket to find a response for the given title * using TIMEOUT as maximum time to wait * returns adress:port string */ char* discoverHost(int sock, char* title) { struct timeval timeout; int found = 0; fd_set fds; char message[MESSAGE_SIZE]; int titleLen = strlen(title); msToTime(TIMEOUT, &timeout); //set up the timeout while(timeToMs(&timeout) > 0){ //use select() to wait on socket up to timeout FD_ZERO(&fds); FD_SET(sock, &fds); select(sock+1, &fds, NULL, NULL, &timeout); if(FD_ISSET(sock, &fds)) { mrecv(sock, message, MESSAGE_SIZE); //read next message from socket //check if its the right title if(strncmp(title, message, titleLen) == 0){ //get second line, which will have address:port char* host = (char*) calloc(strlen(message)-titleLen, sizeof(char)); strcpy(host, &message[titleLen+1]); return host; } } } //matching host was not found, return NULL return NULL; }
static ssize_t mthrottler_mrecv(int s, void *buf, size_t len, int64_t deadline) { struct mthrottlersock *obj = hdata(s, msock_type); dsock_assert(obj->vfptrs.type == mthrottler_type); /* If recv-throttling is off forward the call. */ if(obj->recv_full == 0) return mrecv(obj->s, buf, len, deadline); /* If there's no quota wait till it is renewed. */ if(!obj->recv_remaining) { int rc = msleep(obj->recv_last + obj->recv_interval); if(dsock_slow(rc < 0)) return -1; obj->recv_remaining = obj->recv_full; obj->recv_last = now(); } /* Receive the message. */ int rc = mrecv(obj->s, buf, len, deadline); if(dsock_slow(rc < 0)) return -1; --obj->recv_remaining; return 0; }
static ssize_t mlog_mrecv(int s, void *buf, size_t len, int64_t deadline) { struct mlogsock *obj = hdata(s, msock_type); dsock_assert(obj->vfptrs.type == mlog_type); ssize_t sz = mrecv(obj->s, buf, len, deadline); if(dsock_slow(sz < 0)) return -1; fprintf(stderr, "recv %8zuB: 0x", len); size_t i; for(i = 0; i != sz && i != len; ++i) fprintf(stderr, "%02x", (int)((uint8_t*)buf)[i]); fprintf(stderr, "\n"); return sz; }
static BT_u32 i2c_master_transfer(BT_HANDLE hI2C, BT_I2C_MESSAGE *msgs, BT_u32 num, BT_ERROR *pError) { while(hI2C->pRegs->STATUS & STATUS_BA) { BT_ThreadYield(); } if(num > 1) { hI2C->bHold = 1; hI2C->pRegs->CONTROL |= CONTROL_HOLD; } else { hI2C->bHold = BT_FALSE; } BT_u32 count; for(count = 0; count < num; count++, msgs++) { if(count == (num - 1)) { hI2C->bHold = BT_FALSE; } retry: hI2C->err_status = 0; hI2C->p_msg = msgs; if(msgs->flags & BT_I2C_M_TEN) { hI2C->pRegs->CONTROL &= ~CONTROL_NEA; } else { hI2C->pRegs->CONTROL |= CONTROL_NEA; } if(msgs->flags & BT_I2C_M_RD) { mrecv(hI2C); } else { msend(hI2C); } // Wait on transfer complete signal. BT_kMutexPend(hI2C->pMutex, 0); hI2C->pRegs->INT_DISABLE = 0x000002FF; if(hI2C->err_status & INT_MASK_ARB_LOST) { BT_kPrint("ZYNQ I2C: Lost ownership on bus, trying again..."); BT_ThreadSleep(2); goto retry; } } hI2C->p_msg = NULL; hI2C->err_status = 0; return num; }
static int exchange(request_rec *r, msg_t *tmsg, msg_t **rmsg) { char *data; char szbuf[4]; int msgsz = 4; int rv; tmsg = decode(r, tmsg); if ((rv = msend(r, tmsg->data, &(tmsg->size))) != OK) return rv; if ((rv = mrecv(r, szbuf, &msgsz)) != OK) return rv; msgsz = (szbuf[3] << 24) | (szbuf[2] << 16) | (szbuf[1] << 8) | szbuf[0]; msgsz -= 4; if (msgsz < 0 || msgsz > MAX_MSG_SIZE) return HTTP_BAD_REQUEST; data = apr_pcalloc(r->pool, msgsz); if ((rv = mrecv(r, data, &msgsz)) != OK) return rv; msgsz += 4; (*rmsg) = apr_pcalloc(r->pool, sizeof(msg_t)); (*rmsg)->data = apr_pcalloc(r->pool, msgsz + 1); (*rmsg)->data[msgsz] = '\0'; (*rmsg)->size = msgsz; memcpy((*rmsg)->data, szbuf, 4); memcpy((*rmsg)->data + 4, data, msgsz - 4); *rmsg = encode(r, *rmsg); return OK; }
coroutine void dialogue(int s) { int rc = msend(s, "What's your name?", 17, -1); if(rc != 0) goto cleanup; char inbuf[256]; ssize_t sz = mrecv(s, inbuf, sizeof(inbuf), -1); if(sz < 0) goto cleanup; inbuf[sz] = 0; char outbuf[256]; rc = snprintf(outbuf, sizeof(outbuf), "Hello, %s!", inbuf); rc = msend(s, outbuf, rc, -1); if(rc != 0) goto cleanup; cleanup: rc = hclose(s); assert(rc == 0); }
void do_recv() { int c = 0; mhost *t; for(t=members;t;t=t->next){ c++; } while(mrecv()){ if(c){ c--; }else{ break; } } }
/* * Thread that watches for multicast requests, and responds if this server * has the requested movie */ void *monitor_queries() { printf("Server Started\n"); int count; char message[MESSAGE_SIZE]; int reqSock, resSock; //create multicast socket to watch for requests on M_REQ_ADDR:M_REQ_PORT if((reqSock = msockcreate(RECV, request_address, request_port)) < 0){ fprintf(stderr, "Unable to bind multicast %s:%d\n", request_address, request_port); exit(1); } //create multicast socket of respond to requests on M_RES_ADDR:M_RES_PORT if((resSock = msockcreate(SEND, response_address, response_port)) < 0){ fprintf(stderr, "Unable to bind multicast %s:%d\n", response_address, response_port); exit(1); } while(1){ //read in a movie request memset(message, 0, MESSAGE_SIZE); count = mrecv(reqSock, message, MESSAGE_SIZE); if(count > 0){ printf("requested: \"%s\"", message); //check if we have the requested movie if(checkForTitle(message)){ strcat(message, "\n"); strcat(message, connectAddr); printf("(FOUND, SENDING ADDRESS)\n"); //send response over mulitcast response socket msend(resSock, message, strlen(message)); } else { printf("(not found)\n"); } } } }
coroutine void dialogue(int s, int ch) { int op = CONN_ESTABLISHED; int rc = chsend(ch, &op, sizeof(op), -1); assert(rc == 0); int64_t deadline = now() + 60000; rc = msend(s, "What's your name?", 17, deadline); if(rc != 0) goto cleanup; char inbuf[256]; ssize_t sz = mrecv(s, inbuf, sizeof(inbuf), deadline); if(sz < 0) goto cleanup; inbuf[sz] = 0; char outbuf[256]; rc = snprintf(outbuf, sizeof(outbuf), "Hello, %s!", inbuf); rc = msend(s, outbuf, rc, deadline); if(rc != 0) goto cleanup; cleanup: op = errno == 0 ? CONN_SUCCEEDED : CONN_FAILED; rc = chsend(ch, &op, sizeof(op), -1); assert(rc == 0 || errno == ECANCELED); rc = hclose(s); assert(rc == 0); }
static ssize_t lz4_mrecvv(struct msock_vfs *mvfs, const struct iovec *iov, size_t iovlen, int64_t deadline) { struct lz4_sock *obj = dsock_cont(mvfs, struct lz4_sock, mvfs); /* Adjust the buffer size as needed. */ size_t len = iov_size(iov, iovlen); size_t maxlen = LZ4F_compressFrameBound(len, NULL); if(obj->inlen < maxlen) { uint8_t *newbuf = realloc(obj->inbuf, maxlen); if(dsock_slow(!newbuf)) {errno = ENOMEM; return -1;} obj->inbuf = newbuf; obj->inlen = maxlen; } /* Get the compressed message. */ ssize_t sz = mrecv(obj->s, obj->inbuf, obj->inlen, deadline); if(dsock_slow(sz < 0)) return -1; /* Extract size of the uncompressed message from LZ4 frame header. */ LZ4F_frameInfo_t info; size_t infolen = sz; size_t ec = LZ4F_getFrameInfo(obj->dctx, &info, obj->inbuf, &infolen); if(dsock_slow(LZ4F_isError(ec))) {errno = EPROTO; return -1;} /* Size is a required field. */ if(dsock_slow(info.contentSize == 0)) {errno = EPROTO; return -1;} /* Decompressed message would exceed the buffer size. */ if(dsock_slow(info.contentSize > len)) {errno = EMSGSIZE; return -1;} /* Decompress. */ /* TODO: Avoid the extra allocations and copies. */ uint8_t *buf = malloc(len); if(dsock_slow(!buf)) {errno = ENOMEM; return -1;} size_t dstlen = len; size_t srclen = sz - infolen; ec = LZ4F_decompress(obj->dctx, buf, &dstlen, obj->inbuf + infolen, &srclen, NULL); if(dsock_slow(LZ4F_isError(ec))) {errno = EPROTO; return -1;} if(dsock_slow(ec != 0)) {errno = EPROTO; return -1;} dsock_assert(srclen == sz - infolen); iov_copyallto(iov, iovlen, buf); free(buf); return dstlen; }
coroutine void client(void) { ipaddr addr; int rc = ipaddr_remote(&addr, "127.0.0.1", 5555, 0, -1); assert(rc == 0); int s = tcp_connect(&addr, -1); assert(s >= 0); int cs = crlf_start(s); assert(cs >= 0); rc = msend(cs, "ABC", 3, -1); assert(rc == 0); char buf[3]; ssize_t sz = mrecv(cs, buf, 3, -1); assert(sz == 3); assert(buf[0] == 'G' && buf[1] == 'H' && buf[2] == 'I'); rc = msend(cs, "DEF", 3, -1); assert(rc == 0); s = crlf_stop(cs, -1); assert(s >= 0); rc = hclose(s); assert(rc == 0); }
int main(int argc, char *argv[]) { int mtype, size, c, list = FALSE, limit = -1, deflt = -1; int fd; char *userlist = 0, *user, **users, *p; short status; struct user_priority *ppri_tbl, *ld_priority_file(); extern char *optarg; extern int optind, opterr, optopt, errno; setlocale(LC_ALL, ""); #if !defined(TEXT_DOMAIN) #define TEXT_DOMAIN "SYS_TEST" #endif (void) textdomain(TEXT_DOMAIN); if(argc == 1) { usage: (void) printf(gettext("usage: \n")); (void) printf(gettext("(assign priority limit to users)\n")); (void) printf(gettext("\tlpusers -q priority -u user-list\n")); (void) printf(gettext( "(assign default priority limit for balance of users)\n")); (void) printf(gettext("\tlpusers -q priority\n")); (void) printf(gettext("(put users back to default priority limit)\n")); (void) printf(gettext("\tlpusers -u user-list\n")); (void) printf(gettext("(assign default priority)\n")); (void) printf(gettext("\tlpusers -d priority\n")); (void) printf(gettext("(examine priority limits, defaults)\n")); (void) printf(gettext("\tlpusers -l\n")); exit(argc == 1); } opterr = 0; /* disable printing of errors by getopt */ while ((c = getopt(argc, argv, "ld:q:u:")) != -1) switch(c) { case 'l': if (list) LP_ERRMSG1(WARNING, E_LP_2MANY, 'l'); list = TRUE; break; case 'd': if (deflt != -1) LP_ERRMSG1(WARNING, E_LP_2MANY, 'd'); deflt = (int)strtol(optarg,&p,10); if (*p || deflt<PRI_MIN || deflt>PRI_MAX) { LP_ERRMSG1(ERROR, E_LP_BADPRI, optarg); exit(1); } break; case 'q': if (limit != -1) LP_ERRMSG1(WARNING, E_LP_2MANY, 'q'); limit = (int)strtol(optarg,&p,10); if (*p || limit<PRI_MIN || limit>PRI_MAX) { LP_ERRMSG1(ERROR, E_LP_BADPRI, optarg); exit(1); } break; case 'u': if (userlist) LP_ERRMSG1(WARNING, E_LP_2MANY, 'u'); userlist = optarg; break; case '?': if (optopt == '?') goto usage; (p = "-X")[1] = optopt; if (strchr("ldqu", optopt)) LP_ERRMSG1(ERROR, E_LP_OPTARG, p); else LP_ERRMSG1(ERROR, E_LP_OPTION, p); exit(1); } if (optind < argc) { LP_ERRMSG1(ERROR, E_LP_EXTRA, argv[optind]); exit(1); } if (((list || deflt != -1) && (limit != -1 || userlist)) || (list && deflt != -1)) { LP_ERRMSG(ERROR, E_LP_OPTCOMB); /* invalid combination of options */ exit(1); } PRIORITY = Lp_Users; /* load existing priorities from file */ if (!(ppri_tbl = ld_priority_file(PRIORITY))) { switch (errno) { case EBADF: LP_ERRMSG1(ERROR, E_LPU_BADFORM, PRIORITY); break; default: LP_ERRMSG2(ERROR, E_LPU_BADFILE, PRIORITY, errno); } exit(1); } if (list) { print_tbl(ppri_tbl); exit (0); } else { if (userlist) { users = getlist(userlist, " \t", ","); if (users) while (user = *users++) { if (del_user(ppri_tbl, user) && (limit == -1)) LP_ERRMSG1(WARNING, E_LPU_NOUSER, user); if (limit != -1) { if (add_user(ppri_tbl, user, limit)) LP_ERRMSG1(WARNING, E_LPU_BADU, user); } } } else if (deflt != -1) ppri_tbl->deflt = deflt; else ppri_tbl->deflt_limit = limit; if ((fd = open_locked(PRIORITY, "w", LPU_MODE)) < 0) { LP_ERRMSG1(ERROR, E_LP_ACCESS, PRIORITY); exit(1); } output_tbl(fd, ppri_tbl); close(fd); } if (mopen()) /* error on mopen == no spooler, exit quietly */ exit(0); (void)putmessage (message, S_LOAD_USER_FILE); if (msend(message)) goto Error; if (mrecv(reply, sizeof(reply)) == -1) goto Error; mtype = getmessage(reply, R_LOAD_USER_FILE, &status); if (mtype != R_LOAD_USER_FILE) { LP_ERRMSG1 (ERROR, E_LP_BADREPLY, mtype); goto NoError; } if (status == 0) goto NoError; Error: LP_ERRMSG (ERROR, E_LPU_NOLOAD); NoError:(void)mclose (); return (0); }
int main(int argc) { char message[MESSAGE_LEN]; char movie_title[MOVIE_TITLE_LEN]; int len, check_sock, found_sock, cnt; int sock, length, n; socklen_t fromlen; struct sockaddr_in server; struct sockaddr_in from; char buf[1024]; struct hostent *hp; printf("Nutella Server Started\n"); printf("Listening for movie requests\n"); char hostname[HOST_NAME_MAX]; if (gethostname(hostname, sizeof hostname) != 0) { printf("hostname error"); exit(1); } while (1) { /* set up socket */ if ((check_sock=msockcreate(RECV, CHECK_ADDR, CHECK_PORT)) < 0) { perror("msockcreate"); exit(1); } /* get multicasted message */ cnt = mrecv(check_sock, movie_title, MOVIE_TITLE_LEN); if (cnt < 0) { perror("mrecv"); exit(1); } else if (cnt==0) { return 0; } printf("Received search request for \"%s\"\n", movie_title); char *nut_file; int num_movies; char movies[100][25]; char movie_locs[100][25]; char frame[1440]; char temp_frame[960]; fstream inStream; nut_file = ".nutella"; inStream.open(nut_file, ios :: in); if(inStream.fail()) { //return false; cout << "couldn't open\n"; return 0; } //get number of movies from .nutella file inStream >> num_movies; int i; for (i = 0; i < num_movies; i++) { inStream >> movies[i]; inStream >> movie_locs[i]; } inStream.close(); int movie_loc; int movie_found = 0; for (i = 0; i < num_movies; i++) { if (strcmp(movies[i], lowercase(movie_title)) == 0) { //printf("Found the movie %s\n", movie_title); movie_found = 1; movie_loc = i; break; } } if (movie_found != 1) { printf("Couldn't find the movie %s\n", movie_title); return 0; } else { printf("Found the movie %s\n", movie_title); /* set up socket */ if ((found_sock=msockcreate(SEND, FOUND_ADDR, FOUND_PORT)) < 0) { perror("msockcreate"); exit(1); } printf("Sending port %d and address %s to client \n", STREAM_PORT, STREAM_ADDR); char found_message[100]; sprintf(found_message, "%d %s %s", STREAM_PORT, STREAM_ADDR, hostname); /* multicast message */ cnt = msend(found_sock, found_message, strlen(found_message)+1); if (cnt < 0) { perror("msend"); exit(1); } } sock=socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) printf("Opening socket error"); length = sizeof(server); bzero(&server,length); server.sin_family=AF_INET; //server.sin_addr.s_addr=STREAM_ADDR; if (inet_aton(STREAM_ADDR, &server.sin_addr) == 0) { perror("inet_aton"); exit(EXIT_FAILURE); } /* bcopy((char *)STREAM_ADDR, (char *)&server.sin_addr, strlen(STREAM_ADDR)); */ //hp = gethostbyaddr(stream_addr); hp = gethostbyname(hostname); if (hp==0) printf("Unknown host"); bcopy((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length); server.sin_port=htons(STREAM_PORT); if (bind(sock,(struct sockaddr *)&server,length)<0) printf("binding error"); fromlen = sizeof(struct sockaddr_in); n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen); if (n < 0) printf("recvfrom"); write(1,"Received a datagram: ",21); write(1,buf,n); char *filename = movie_locs[movie_loc]; FILE *file = fopen ( filename, "r" ); if ( file != NULL ) { char line [ 512 ]; /* or other suitable maximum line size */ strcpy(frame, ""); strcpy(temp_frame, ""); bzero(frame ,1440); struct timespec tim, tim2; tim.tv_sec = 0; tim.tv_nsec = 100000000; while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */ { //printf("%s", frame); if (strcmp(line, "end\n") == 0) { //bzero(buf ,256); //sprintf(buffer, "stream_request:%s", movie_title); printf("Sending: \n%s\n", frame); n = sendto(sock, frame, strlen(frame), 0,(struct sockaddr *)&from,fromlen); //sleep(.09); nanosleep(&tim , &tim2); if (n < 0) printf("sendto error"); memset(&frame[0], 0, sizeof(frame)); printf("Starting new cycle \n"); } else strcat(frame, line); //strcat(frame, "\n"); //fputs ( line, stdout ); /* write the line */ } fclose ( file ); n = sendto(sock, "End Movie", 9, 0,(struct sockaddr *)&from,fromlen); } else { printf ( "file didn't open" ); /* why didn't the file open? */ } /* while (1) { n = sendto(sock,"Got your message\n",17, 0,(struct sockaddr *)&from,fromlen); if (n < 0) printf("sendto error"); return 0; } */ msockdestroy(check_sock); msockdestroy(found_sock); close(sock); } }
void startServer(){ puts("Server Mode Starting..."); char* movieDir = getenv("NUTELLA"); if(!movieDir){ fprintf(stderr,"Error: NUTELLA variable not set, please set $NUTELLA to a movie directory.\n"); exit(1); } char hostname[1028]; hostname[1023] = '\0'; gethostname(hostname, 1023); strcat(hostname, ":7777"); int querySock = msockcreate(RECV, QUERYGROUP, QUERYPORT); int responseSock = msockcreate(SEND, RESPGROUP, RESPPORT); if(querySock == -1){ fprintf(stderr, "Error: Could not create query socket."); exit(-1); } if(responseSock == -1){ fprintf(stderr, "Error: Could not create response socket."); exit(-1); } char* query = calloc(256, sizeof(char)); int receivedLength; int port = 7777; DIR *dp; struct dirent *d; while(1) { puts("Now waiting for queries..."); receivedLength = mrecv(querySock, query, 256); printf("Received Query for: %s\n", query); dp = opendir(movieDir); if (dp == NULL) { fprintf(stderr, "ERROR: Couldn't open movie directory.\n"); exit(-1); } d = readdir(dp); while (d) { if(!strcmp(d->d_name, query)) break; d = readdir(dp); } closedir(dp); if(d) { msend(responseSock, hostname, strlen(hostname)); printf("Movie Found! Sending IP and port: %s\n", hostname); char* file = malloc(strlen(query) + strlen(movieDir) + 1); strcpy(file, movieDir); strcat(file, "/"); strcat(file, query); bindServer(file); }else{ puts("Movie not found."); } d =NULL; memset(query, 0, 256); } }
void startClient(){ puts("Client Mode Selected..."); int length = 128; char* movieName = (char*) calloc(length, sizeof(char)); char* respBuff; short int port; int receivedLength = 0; int i = 0; struct timeval timeout; timeout.tv_sec = 3; timeout.tv_usec = 0; while(1) { respBuff = calloc(1024, sizeof(char)); memset(movieName,0, 128 * sizeof(char)); printf("Enter movie name: "); movieName = readInput(movieName,&length); int querySock = msockcreate(SEND, QUERYGROUP, QUERYPORT); int responseSock = msockcreate(RECV, RESPGROUP, RESPPORT); msend(querySock, movieName, strlen(movieName)); if (setsockopt (responseSock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); receivedLength = mrecv(responseSock, respBuff, 1024); msockdestroy(querySock); msockdestroy(responseSock); if(receivedLength == -1) { puts("Movie not found on any listening servers..."); free(respBuff); continue; } i = 0; while( respBuff[i] != ':') i++; char* host = calloc(i+1, sizeof(char)); strncpy(host, respBuff, i); i++; sscanf(respBuff+i, "%hu", &port); puts("Server and socket received!"); struct hostent *hostname = gethostbyname(host); // Convert server name into 32bit ip breakdownURL(host); int sd; if(0 > (sd = socket(AF_INET, SOCK_STREAM, 0))) { // Create the socket to the server puts("Error creating socket."); printf("\n Error : Connect Failed \nReason: %s\n", strerror(errno)); } struct sockaddr_in serv_addr; memset(&serv_addr, '\0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); if(inet_pton(AF_INET, host, &serv_addr.sin_addr)<=0) { fprintf(stderr, "ERROR: %s\n", strerror(errno)); exit(1); } if( connect(sd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { fprintf(stderr, "ERROR: Connect Failed \nReason: %s\n", strerror(errno)); exit(1); } char* recvBuffer = calloc(1024, sizeof(char)); int c = 0; while(read(sd, recvBuffer, 1) > 0){ if(c == 0 && recvBuffer[0] == '\n'){ c++; } else if(c == 1 && recvBuffer[0] == 'd'){ c++; } else if(c == 2 && recvBuffer[0] == 'o'){ c++; } else if(c == 3 && recvBuffer[0] == 'n'){ c++; } else if(c == 4 && recvBuffer[0] == 'e'){ c++; } else if(c == 5 && recvBuffer[0] == '\n') { break; } printf("%s", recvBuffer); fflush(stdout); } puts(""); free(recvBuffer); free(respBuff); } }
/* function definition: listener() * listen on query port for movie requests * stream if found to user */ int listener(){ int query_socket_id, reply_socket_id, tcp_socket_id, stream_socket_id, bytesRecv, flag_for_replay, incorrect_response_counter; int number_of_movies_discovered = 0; char query_buffer[80]; char ip_of_stream[IP_LEN]; char response_buffer[120]; char list_of_movies[LIST_OF_MOVIES][80]; char handshake_buffer[80]; char handshake_reponse_buffer[120]; FILE *movie_fd; fd_set readFrom; struct timeval timeout, timeout_replay; timeout.tv_sec = 5; timeout.tv_usec = 0; timeout_replay.tv_sec = 10; timeout_replay.tv_usec = 0; if ((movie_fd = fopen(LOCATION_OF_MOVIE_LIST, "r")) == NULL){ perror("error: opening movie file"); exit(2); } else{ while (number_of_movies_discovered < LIST_OF_MOVIES && (fgets(list_of_movies[number_of_movies_discovered], 80 + 1, movie_fd)) != NULL){ list_of_movies[number_of_movies_discovered][strlen(list_of_movies[number_of_movies_discovered]) - 1] = '\0'; number_of_movies_discovered++; } if (fclose(movie_fd)){ perror("error: closing file"); exit(2); } } if (getIPAddress(ip_of_stream) < 0){ perror("error: getting IP address"); exit(2); } /* open query socket */ if ((query_socket_id = msockcreate(RECV, ADDRESS_FOR_QUERY, PORT_FOR_QUERY)) < 0){ perror("error: query_buffer socket creation"); exit(2); } /* open response socket */ if ((reply_socket_id = msockcreate(SEND, ADDRESS_FOR_REPLY, PORT_FOR_REPLY)) < 0){ perror("error: response socket creation"); exit(2); } /* open TCP socket */ if ((tcp_socket_id = openAndBindStream(atoi(PORT_TO_CONNECT_ON))) < 0){ perror("error: streaming socket creation"); exit(2); } /* set socket to nonblocking so it can time out*/ if (fcntl(tcp_socket_id, F_SETFL, O_NONBLOCK) < 0){ perror("error: set nonblocking"); exit(2); } while(1){ if (mrecv(query_socket_id, query_buffer, 80 + 1) < 0){ perror("error: receiving query"); exit(2); } /* search movie array to see if queried name exists */ if (searchForInputMovieName(query_buffer, list_of_movies, number_of_movies_discovered) == 0){ /* movie found, send ip and port information */ strncpy(response_buffer, query_buffer, strlen(query_buffer) + 1); strcat(response_buffer, ASCII_DELIMITER); strcat(response_buffer, ip_of_stream); strcat(response_buffer, ASCII_DELIMITER); strcat(response_buffer, PORT_TO_CONNECT_ON); sleep(1); //give client time to setup recieve port /* send response message */ if (msend(reply_socket_id, response_buffer, strlen(response_buffer) + 1) < 0){ perror("error: sending response_buffer"); exit(2); } /* add TCP socket to readset */ FD_ZERO(&readFrom); if (FD_SET(tcp_socket_id, &readFrom) < 0){ perror("error: could not add tcp_socket_id to readset"); exit(2); } //code from http://web.cs.wpi.edu/~cs4513/d14/samples/select.c was adapted //for the select function bytesRecv = select(tcp_socket_id + 1, &readFrom, NULL, NULL, &timeout); if (bytesRecv != 0){ if (FD_ISSET(tcp_socket_id, &readFrom)){ if ((stream_socket_id = listenAndConnect(tcp_socket_id)) < 0){ perror("error: listening for response"); exit(2); } else{ do{ flag_for_replay = 0; //start streaming movie if (playMovie(stream_socket_id, query_buffer) < 0){ perror("error: playing movie"); exit(2); } /* send half of a handshake */ if (sprintf(handshake_buffer, "%d", stream_socket_id) < 0){ perror("error: convert stream sock to handshake"); exit(2); } usleep(ACCEPT_WAIT); //wait for accept if (write(stream_socket_id, handshake_buffer, 80) == -1){ perror("error: failed to write"); exit(2); } incorrect_response_counter = 0; do{ FD_ZERO(&readFrom); if (FD_SET(stream_socket_id, &readFrom) < 0){ perror("error: adding tcp_socket_id to readset"); exit(2); } //code from http://web.cs.wpi.edu/~cs4513/d14/samples/select.c was adapted //for the select function bytesRecv = select(stream_socket_id + 1, &readFrom, NULL, NULL, &timeout_replay); if (bytesRecv > 0){ if (FD_ISSET(stream_socket_id, &readFrom)){ if (read(stream_socket_id, handshake_reponse_buffer, 120) < 0){ perror("error: receiving handshake response"); exit(2); } /* look for handshake_buffer for each reply */ if (strncmp(handshake_buffer, handshake_reponse_buffer, strlen(handshake_buffer) + 1) == 0){ flag_for_replay++; break; } else{ //incorrect response incorrect_response_counter++; } } } else if (bytesRecv == 0){ break; } } while ((bytesRecv != 0) || (incorrect_response_counter < 10)); } while (flag_for_replay > 0); if (close(stream_socket_id) < 0){ perror("error: closing stream socket"); exit(2); } } } } } } /* close the query socket */ if (msockdestroy(query_socket_id) < 0){ perror("error: query_buffer socket destruction"); exit(2); } /* close the response socket */ if (msockdestroy(reply_socket_id) < 0){ perror("error: response socket destruction"); exit(2); } /* close the TCP socket*/ if (close(tcp_socket_id) < 0){ perror("error: closing tcp socket"); exit(2); } return 0; }
int main(int argc, char *argv[], char *envp[]) { int msg_Q_id = 1; int proc_num = 2; struct MsgQue msgque; pid_t pid[50]={0}; int pid_count = 0; int key; int i, rc; char msg[50]; int msg_num = 1; int repeat = 1; int sleep_time = 0; int choice; if (argc>=3) { if ((atoi(argv[1])>0)&&(atoi(argv[2])>0)&&(atoi(argv[2])<50)) { key = atoi(argv[1]); proc_num = atoi(argv[2]); if (argc>=4) repeat = atoi(argv[3]); if (argc>=5) sleep_time = atoi(argv[4]); } else { printUsage(); return -1; } } else { printUsage(); return -1; } minit(key, &msgque); printf("Process[%d] registered to queue[%d,0x%x]\n", getpid(), msgque.token, msgque.queue); if (sleep_time>0) sleep(sleep_time); while(repeat>0) { if((proc_num<1)||(proc_num>2)) { printf("\nEnter choice[1-recv, 2-send]"); scanf("%d",&choice); } else { choice = proc_num; } if(choice==1){ rc = mrecv(&msgque, msg, 50); if ( rc != MQ_SUCCESS) printf("Process[%d] %d:Error while receiving\n",getpid(), rc); else printf("Process[%d] Recved:%d %s\n", getpid(), rc, msg); } else if(choice==2) { sprintf(msg,"Process[%d] MsgNo %d", getpid(), msg_num++); rc = msend(&msgque, msg, 50); if (rc != MQ_SUCCESS) printf("Process[%d] Sender: %d Error while sending\n", getpid(), rc); else printf("Process[%d] Sender got:%d\n",getpid(), rc); } repeat--; mclean(&msgque); if (sleep_time>0) sleep(sleep_time); } mclose(&msgque); return 0; }
int worker(int csock) { char buffer[BUFSIZ+1]; bzero(&buffer, sizeof buffer); int rec,sen; /*****Select******/ printf("Recving select message...\n"); if((rec = mrecv(csock, buffer, sizeof(SELECT)))<=0){ close(csock); return -1; } printf("Recved.\n"); pSELECT select = (pSELECT)&buffer; //Do something like checking if the version is 5 pSELECT_RESPONSE selectRes = (pSELECT_RESPONSE)malloc(sizeof(SELECT_RESPONSE)); selectRes->ver=0x5; //Socks Version 5 selectRes->method=0x0; //NO AUTHENTICATION REQUIRED if(select->ver!=0x5){ selectRes->method=0xFF; } sen = msend(csock, selectRes, sizeof(SELECT_RESPONSE)); printf("Select done,rec/send:%d/%d\n",rec,sen); free(selectRes); /*****Request******/ printf("Recving request...\n"); rec = recv(csock, buffer, BUFSIZ,0); printf("Recved %d bytes\n",rec); pREQUEST request = (pREQUEST)&buffer; //Parse the target addr struct sockaddr_in taddr; taddr.sin_family = AF_INET; if(request->atyp==0x3){ //Domain name //char domainlen=*(&request->atyp+sizeof(request->atyp)); char domainlen=*(&request->addr); char domain[256]={0}; strncpy(domain,&request->atyp+2,(unsigned int)domainlen); struct hostent *phost = gethostbyname(domain); if(phost==NULL){ printf("Cannot Resolv the Domain name:%s\n",(char *)&domain); close(csock); return -1; } memcpy(&taddr.sin_addr,phost->h_addr_list[0],phost->h_length); memcpy(&taddr.sin_port,&request->atyp+sizeof(request->atyp)+1+(unsigned int)domainlen,2); } else if(request->atyp==0x1){ //IPv4 Addr memcpy(&taddr.sin_addr.s_addr,&request->atyp+1,4); memcpy(&taddr.sin_port,&request->atyp+1+4,2); } else{ printf("Not implemented\n"); close(csock); return -1; } //Connect to the target host pREQUEST_RESPONSE requestRes = (pREQUEST_RESPONSE)malloc(sizeof(REQUEST_RESPONSE)); requestRes->ver=0x5; requestRes->rep=0x0; requestRes->rsv=0x0; requestRes->atyp=0x1; memset(requestRes+4, 0, 6); /* if(request->cmd=0x03){ uint32_t tmpaddr = htonl("127.0.0.1"); uint16_t tmpport = htons(8081); memcpy(requestRes+4,&tmpaddr,sizeof(uint32_t)); //XXX wtf? memcpy(requestRes+8,&tmpport,sizeof(uint16_t)); } */ printf("Connecting to port %d on %s\n",ntohs(taddr.sin_port),inet_ntoa(taddr.sin_addr)); int tsock; //Check its a tcp or udp request if(request->cmd==0x04){ //UDP ASSOCIATE X'03' //Never use udp printf("Hey, its a udp request!\n"); tsock = socket(AF_INET, SOCK_DGRAM, 0); } else{ tsock=socket(AF_INET, SOCK_STREAM, 0); } if(connect(tsock, (struct sockaddr *) &taddr, sizeof(taddr))==-1){ requestRes->rep=0x5; sen = msend(csock, requestRes, sizeof(REQUEST_RESPONSE)); close(csock); return -1; } printf("Done\n"); sen = msend(csock, requestRes, sizeof(REQUEST_RESPONSE)); printf("Request done,rec/send:%d/%d\n",rec,sen); free(requestRes); if(request->cmd==0x03){ //UDP ASSOCIATE printf("Recving... #1\n"); rec = recv(csock, buffer, BUFSIZ,0); /* struct sockaddr_in tmpaddr; tmpaddr.sin_family = AF_INET; memcpy(&tmpaddr.sin_addr.s_addr,buffer+4,4); //XXX memcpy(&tmpaddr.sin_port,buffer+4+4,2); printf("Recv Ascii:%s:%d\n",inet_ntoa(tmpaddr.sin_addr),ntohs(tmpaddr.sin_port)); */ printf("Done:%d\nSending... #1\n",rec); sen = send(tsock, buffer, rec,0); printf("Done:%d\nRecving... #2\n",sen); rec = recv(tsock, buffer, BUFSIZ,0); printf("Done:%d\nSending... #2\n",rec); sen = send(csock, buffer, rec,0); printf("Done:%d",sen); return 0; } /*****Forward******/ forwarder(csock,tsock); printf("worker exit"); close(csock); close(tsock); return 0; }
int main(int argc) { char message[MESSAGE_LEN]; char movie_title[MOVIE_TITLE_LEN]; int len, check_sock, found_sock, cnt; int stream_port; char *stream_addr; int stream_sock, n; unsigned int length; struct sockaddr_in server, from; struct hostent *hp; char buffer[1440]; char *stream_hostname; printf("Nutella Client Started\n"); while(1) { printf("Enter Movie Name: "); scanf("%s", movie_title); printf("Sending search request for the movie %s\n", movie_title); /* set up socket */ if ((check_sock=msockcreate(SEND, CHECK_ADDR, CHECK_PORT)) < 0) { perror("msockcreate"); exit(1); } /* multicast message */ cnt = msend(check_sock, movie_title, strlen(movie_title)+1); if (cnt < 0) { perror("msend"); exit(1); } printf("Waiting for response\n"); /* set up socket */ if ((found_sock=msockcreate(RECV, FOUND_ADDR, FOUND_PORT)) < 0) { perror("msockcreate"); exit(1); } char found_message[FOUND_MSG_LEN]; /* get multicasted message */ cnt = mrecv(found_sock, found_message, FOUND_MSG_LEN); if (cnt < 0) { perror("mrecv"); exit(1); } else if (cnt==0) { return 0; } stream_port = atoi(strtok(found_message," ")); stream_addr = strtok (NULL, " "); stream_hostname = strtok (NULL, " "); printf("Received port(%d), IP(%s) and hostname(%s) from server\n", stream_port, stream_addr, stream_hostname); stream_sock = socket(AF_INET, SOCK_DGRAM, 0); if (stream_sock < 0) printf("socket error"); server.sin_family = AF_INET; /* bcopy((char *)stream_addr, (char *)&server.sin_addr, strlen(stream_addr)); */ //hp = gethostbyaddr(stream_addr); /* if (inet_aton(stream_addr, &server.sin_addr) == 0) { printf("inet_aton\n"); exit(EXIT_FAILURE); } /* hp = gethostbyaddr( (char *)&server.sin_addr.s_addr, sizeof(server.sin_addr.s_addr),AF_INET); if (hp==0) error("Unknown host"); */ hp = gethostbyname(stream_hostname); bcopy((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length); server.sin_port = htons(stream_port); length=sizeof(struct sockaddr_in); bzero(buffer,1440); sprintf(buffer, "stream_request:%s", movie_title); n=sendto(stream_sock,buffer, strlen(buffer),0,(const struct sockaddr *)&server,length); if (n < 0) printf("Sendto error"); while (1) { n = recvfrom(stream_sock,buffer,1440,0,(struct sockaddr *)&from, &length); if (n < 0) { printf("recvfrom error"); break; } if (strcmp(buffer, "End Movie") == 0) { printf("\033[2J"); printf("\033[0;0f"); break; } printf("\033[2J"); printf("\033[0;0f"); printf("%s", buffer); memset(&buffer[0], 0, sizeof(buffer)); //write(1,"Got an ack: ",12); //write(1,buffer,n); } msockdestroy(check_sock); msockdestroy(found_sock); close(stream_sock); } }
int player(int id) { char message[512]; char input[512]; int sock; struct sockaddr_in info; char address[INET_ADDRSTRLEN]; char *token; char *port; int i; char *name; int bytes; int sender_id; while(1){ fgets(input, sizeof input, stdin); if(strcmp(input, "exit\n") == 0){ msockdestroy(sock); exit(0); } if ((sock = msockcreate(SEND, MULTICAST_ADDR, MULTICAST_PORT)) < 0) { perror("msockcreate"); exit(1); } sprintf(message, "%d\t%s\t%d", REQUEST_KVK, input, id); if(msend(sock, message, strlen(message) + 1) < 0){ perror("msend"); exit(1); } i = 0; while(1){ printf("waiting for response from peers %d\n", i); if((bytes = mrecv(sock, &info, message, sizeof message)) < 0){ perror("mrecv"); } printf("received response:\n%s\n", message); inet_ntop(AF_INET, &(info.sin_addr), address, INET_ADDRSTRLEN); printf("\nsender address: %s\n", address); token = strtok(message, "\t"); if(atoi(token) == RESPONSE_KVK){ printf("response:\n"); token = strtok(NULL, "\t\n"); name = token; token = strtok(NULL, "\t"); port = token; token = strtok(NULL, "\t"); sender_id = atoi(token); if(atoi(token) == id){ break; } printf("NAME: %s\nPORT: %s\nINPUT: %s\nID: %d\n", name, port, input, sender_id); if(strcmp(name, strtok(input, "\n")) == 0){ watch_movie(address, port); break; } } if(i++ > 2){ break; } sleep(1); } } return 0; }
int main() { int rc; ssize_t sz; char buf[200]; const char key[] = "01234567890123456789012345678901"; int h1[2]; rc = unix_pair(h1); assert(rc == 0); int h2_0 = btrace_start(h1[0]); assert(h2_0 >= 0); int h2_1 = btrace_start(h1[1]); assert(h2_1 >= 0); int h3_0 = bthrottler_start(h2_0, 1000, 10, 1000, 10); assert(h3_0 >= 0); int h3_1 = bthrottler_start(h2_1, 1000, 10, 1000, 10); assert(h3_1 >= 0); int h4_0 = nagle_start(h3_0, 2000, 100); assert(h4_0 >= 0); int h4_1 = nagle_start(h3_1, 2000, 100); assert(h4_0 >= 0); int h5_0 = pfx_start(h4_0); assert(h5_0 >= 0); int h5_1 = pfx_start(h4_1); assert(h5_1 >= 0); int h6_0 = keepalive_start(h5_0, 50, 150); assert(h6_0 >= 0); int h6_1 = keepalive_start(h5_1, 50, 150); assert(h6_0 >= 0); int h7_0 = nacl_start(h6_0, key, 32, -1); assert(h7_0 >= 0); int h7_1 = nacl_start(h6_1, key, 32, -1); assert(h7_1 >= 0); int h8_0 = lz4_start(h7_0); assert(h8_0 >= 0); int h8_1 = lz4_start(h7_1); assert(h8_1 >= 0); rc = msend(h8_0, "ABC", 3, -1); assert(rc == 0); rc = msend(h8_0, "DEF", 3, -1); assert(rc == 0); sz = mrecv(h8_1, buf, 3, -1); assert(sz == 3); assert(buf[0] == 'A' && buf[1] == 'B' && buf[2] == 'C'); sz = mrecv(h8_1, buf, 3, -1); assert(sz == 3); assert(buf[0] == 'D' && buf[1] == 'E' && buf[2] == 'F'); rc = msend(h8_1, "GHI", 3, -1); assert(rc == 0); /* Allow some keepalives to be sent. */ rc = msleep(500); assert(rc == 0); sz = mrecv(h8_0, buf, 3, -1); assert(sz == 3); assert(buf[0] == 'G' && buf[1] == 'H' && buf[2] == 'I'); rc = hclose(h8_1); assert(rc == 0); rc = hclose(h8_0); assert(rc == 0); return 0; }
int main() { ipaddr addr; int rc = ipaddr_local(&addr, NULL, 5555, 0); assert(rc == 0); int ls = tcp_listen(&addr, 10); assert(ls >= 0); go(client()); int as = tcp_accept(ls, NULL, -1); int cs = crlf_start(as); assert(cs >= 0); char buf[16]; ssize_t sz = mrecv(cs, buf, sizeof(buf), -1); assert(sz == 3); assert(buf[0] == 'A' && buf[1] == 'B' && buf[2] == 'C'); rc = msend(cs, "GHI", 3, -1); assert(rc == 0); sz = mrecv(cs, buf, sizeof(buf), -1); assert(sz == 3); assert(buf[0] == 'D' && buf[1] == 'E' && buf[2] == 'F'); int ts = crlf_stop(cs, -1); assert(ts >= 0); rc = hclose(ts); assert(rc == 0); int h[2]; rc = unix_pair(h); assert(rc == 0); int s0 = crlf_start(h[0]); assert(s0 >= 0); int s1 = crlf_start(h[1]); assert(s1 >= 0); rc = msend(s0, "First", 5, -1); assert(rc == 0); rc = msend(s0, "Second", 6, -1); assert(rc == 0); rc = msend(s0, "Third", 5, -1); assert(rc == 0); rc = crlf_done(s0, -1); assert(rc == 0); sz = mrecv(s1, buf, sizeof(buf), -1); assert(sz == 5 && memcmp(buf, "First", 5) == 0); sz = mrecv(s1, buf, sizeof(buf), -1); assert(sz == 6 && memcmp(buf, "Second", 5) == 0); sz = mrecv(s1, buf, sizeof(buf), -1); assert(sz == 5 && memcmp(buf, "Third", 5) == 0); sz = mrecv(s1, buf, sizeof(buf), -1); assert(sz < 0 && errno == EPIPE); rc = msend(s1, "Red", 3, -1); assert(rc == 0); rc = msend(s1, "Blue", 4, -1); assert(rc == 0); rc = crlf_stop(s1, -1); assert(rc == h[1]); sz = mrecv(s0, buf, sizeof(buf), -1); assert(sz == 3 && memcmp(buf, "Red", 3) == 0); sz = mrecv(s0, buf, sizeof(buf), -1); assert(sz == 4 && memcmp(buf, "Blue", 4) == 0); sz = mrecv(s0, buf, sizeof(buf), -1); assert(sz < 0 && errno == EPIPE); rc = crlf_stop(s0, -1); assert(rc == h[0]); rc = hclose(h[1]); assert(rc == 0); rc = hclose(h[0]); assert(rc == 0); return 0; }
void NutellaSearch::run() { std::string title, recv_title; std::string host, port; struct itimerval timer; char buffer[BUFSIZE]; int bytes_recv; // set up timer values to reset timer timer.it_value.tv_sec = 1; // trigger after 1 second timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 0; // don't reset the timer after expiration timer.it_interval.tv_usec = 0; while (1) { // prompt the user for input std::cout << "Enter movie title, or 'quit' to exit: " << std::flush; std::cin.clear(); std::getline(std::cin, title); if (title.size() <= 0) { std::cout << "Title invalid" << std::endl; continue; } else if (title.compare("quit") == 0) { // send SIGINT to all NutellaServer processes killpg(0, SIGINT); break; } // add .txt title += ".txt"; // multicast the title if (msend(this->q_msock, title.c_str(), title.size()) == -1) { perror("msend()"); continue; } int received_response = 0; // set up timeout timer setitimer(ITIMER_REAL, &timer, NULL); // wait for a reply or timeout do { if ((bytes_recv = mrecv(this->r_msock, buffer, BUFSIZE, WNOHANG)) > 0) { // parse the received value to ensure it is a response to // this query std::stringstream received(std::string(buffer, bytes_recv)); std::getline(received, recv_title); if (title.compare(recv_title) != 0) { // title didn't match continue; } std::getline(received, host); std::getline(received, port); if (this->vflag) { std::cout << "Received response:" << std::endl; std::cout << "\tTitle: " << recv_title << std::endl; std::cout << "\tHost: " << host << std::endl; std::cout << "\tPort: " << port << std::endl; } received_response = 1; break; } } while (NutellaSearch::check_mcast); if (vflag) std::cout << "NutellaSearch: Creating NutellaPlayer" << std::endl; if (received_response) { // create the Nutella Player NutellaPlayer *np = new NutellaPlayer(recv_title, host, atoi(port.c_str()), this->fps, this->fps_flag, this->tflag, this->vflag); np->run(); } } }