//! Starts the socket thread void SocketThread::run() { std::string p_socketFile = "/tmp/isis_qview_" + Isis::Application::UserName(); struct sockaddr_un p_socketName; p_socketName.sun_family = AF_UNIX; strcpy(p_socketName.sun_path,p_socketFile.c_str()); int p_socket; // Create a socket if ((p_socket = socket(PF_UNIX,SOCK_STREAM,0)) < 0) { std::string msg = "Unable to create socket"; std::cerr << msg << std::endl; return; } //const long unsigned int timeout = 1; timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; if(setsockopt(p_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)) != 0) { std::string msg = "Unable set socket timeout"; std::cerr << msg << std::endl; return; } // Bind the file to the socket int status = bind(p_socket,(struct sockaddr *)&p_socketName, sizeof(p_socketName)); if (status < 0) { std::string msg = "Unable to bind to socket [" + p_socketFile + "]"; std::cerr << msg << std::endl; return; } // Set up to listen to the socket if (listen(p_socket,5) < 0) { std::string msg = "Unable to listen to socket [" + p_socketFile + "]"; std::cerr << msg << std::endl; return; } p_done = false; while(!p_done) { // Accept Socket socklen_t len; int childSocket = accept(p_socket, (struct sockaddr *)&p_socketName, &len); if (childSocket < 0) { continue; // probably timed out, we cant do anything about this anyways } // Receive Data int bytes; char buf[1024*1024]; if ((bytes = recv(childSocket,&buf,1024*1024,0)) < 0) { std::string msg = "Unable to read from socket [" + p_socketFile + "]"; std::cerr << msg << std::endl; return; } // Push everything onto our string buffer Isis::iString buffer; for (int i=0; i<bytes; i++) buffer += buf[i]; while (buffer.size() > 0) { Isis::iString token = buffer.Token(" "); if (token == "raise") { emit focusApp(); } else emit newImage(token.c_str()); } }; }
static int dnsReplyHandler(int abort, FdEventHandlerPtr event) { int fd = event->fd; char buf[2048]; int len, rc; ObjectPtr object; unsigned ttl = 0; AtomPtr name, value, message = NULL; int id; int af; DnsQueryPtr query; AtomPtr cname = NULL; if(abort) { dnsSocketHandler = NULL; rc = establishDnsSocket(); if(rc < 0) { do_log(L_ERROR, "Couldn't reestablish DNS socket.\n"); /* At this point, we should abort all in-flight DNS requests. Oh, well, they'll timeout anyway. */ } return 1; } len = recv(fd, buf, 2048, 0); if(len <= 0) { if(errno == EINTR || errno == EAGAIN) return 0; /* This is where we get ECONNREFUSED for an ICMP port unreachable */ do_log_error(L_ERROR, errno, "DNS: recv failed"); dnsGethostbynameFallback(-1, message); return 0; } /* This could be a late reply to a query that timed out and was resent, a reply to a query that timed out, or a reply to an AAAA query when we already got a CNAME reply to the associated A. We filter such replies straight away, without trying to parse them. */ rc = dnsReplyId(buf, 0, len, &id); if(rc < 0) { do_log(L_WARN, "Short DNS reply.\n"); return 0; } if(!findQuery(id, NULL)) { return 0; } rc = dnsDecodeReply(buf, 0, len, &id, &name, &value, &af, &ttl); if(rc < 0) { assert(value == NULL); /* We only want to fallback on gethostbyname if we received a reply that we could not understand. What about truncated replies? */ if(rc < 0) { do_log_error(L_WARN, -rc, "DNS"); if(dnsUseGethostbyname >= 2 || (dnsUseGethostbyname && (rc != -EDNS_HOST_NOT_FOUND && rc != -EDNS_NO_RECOVERY && rc != -EDNS_FORMAT))) { dnsGethostbynameFallback(id, message); return 0; } else { message = internAtom(pstrerror(-rc)); } } else { assert(name != NULL && id >= 0 && af >= 0); } } query = findQuery(id, name); if(query == NULL) { /* Duplicate id ? */ releaseAtom(value); releaseAtom(name); return 0; } /* We're going to use the information in this reply. If it was an error, construct an empty atom to distinguish it from information we're still waiting for. */ if(value == NULL) value = internAtom(""); again: if(af == 4) { if(query->inet4 == NULL) { query->inet4 = value; query->ttl4 = current_time.tv_sec + ttl; } else releaseAtom(value); } else if(af == 6) { if(query->inet6 == NULL) { query->inet6 = value; query->ttl6 = current_time.tv_sec + ttl; } else releaseAtom(value); } else if(af == 0) { /* Ignore errors in this case. */ if(query->inet4 && query->inet4->length == 0) { releaseAtom(query->inet4); query->inet4 = NULL; } if(query->inet6 && query->inet6->length == 0) { releaseAtom(query->inet6); query->inet6 = NULL; } if(query->inet4 || query->inet6) { do_log(L_WARN, "Host %s has both %s and CNAME -- " "ignoring CNAME.\n", scrub(query->name->string), query->inet4 ? "A" : "AAAA"); releaseAtom(value); value = internAtom(""); af = query->inet4 ? 4 : 6; goto again; } else { cname = value; } } if(rc >= 0 && !cname && ((dnsQueryIPv6 < 3 && query->inet4 == NULL) || (dnsQueryIPv6 > 0 && query->inet6 == NULL))) return 0; /* This query is complete */ cancelTimeEvent(query->timeout_handler); object = query->object; if(object->flags & OBJECT_INITIAL) { assert(!object->headers); if(cname) { assert(query->inet4 == NULL && query->inet6 == NULL); object->headers = cname; object->expires = current_time.tv_sec + ttl; } else if((!query->inet4 || query->inet4->length == 0) && (!query->inet6 || query->inet6->length == 0)) { releaseAtom(query->inet4); releaseAtom(query->inet6); object->expires = current_time.tv_sec + dnsNegativeTtl; abortObject(object, 500, retainAtom(message)); } else if(!query->inet4 || query->inet4->length == 0) { object->headers = query->inet6; object->expires = query->ttl6; releaseAtom(query->inet4); } else if(!query->inet6 || query->inet6->length == 0) { object->headers = query->inet4; object->expires = query->ttl4; releaseAtom(query->inet6); } else { /* need to merge results */ char buf[1024]; if(query->inet4->length + query->inet6->length > 1024) { releaseAtom(query->inet4); releaseAtom(query->inet6); abortObject(object, 500, internAtom("DNS reply too long")); } else { if(dnsQueryIPv6 <= 1) { memcpy(buf, query->inet4->string, query->inet4->length); memcpy(buf + query->inet4->length, query->inet6->string + 1, query->inet6->length - 1); } else { memcpy(buf, query->inet6->string, query->inet6->length); memcpy(buf + query->inet6->length, query->inet4->string + 1, query->inet4->length - 1); } object->headers = internAtomN(buf, query->inet4->length + query->inet6->length - 1); if(object->headers == NULL) abortObject(object, 500, internAtom("Couldn't allocate DNS atom")); } object->expires = MIN(query->ttl4, query->ttl6); } object->age = current_time.tv_sec; object->flags &= ~(OBJECT_INITIAL | OBJECT_INPROGRESS); } else { do_log(L_WARN, "DNS object ex nihilo for %s.\n", scrub(query->name->string)); } removeQuery(query); free(query); releaseAtom(name); releaseAtom(message); releaseNotifyObject(object); return 0; }
static void exe_cgi( int sock, const char *method, const char *path, const char *query_string ) { char buf[SIZE]; int content_length = -1; //pipe named by child side int cgi_input[2]; int cgi_output[2]; char method_env[SIZE]; char query_string_env[SIZE]; char content_length_env[SIZE]; char tmpc; memset(buf, '\0', sizeof(buf)); // ! ! ! ! ! M U S T I N I T A R R A Y ! ! ! memset(method_env, '\0', sizeof(method_env)); memset(query_string_env, '\0', sizeof(query_string)); memset(content_length_env, '\0', sizeof(content_length_env)); if(strcasecmp(method, "GET") == 0 ) { clear_header(sock); //"GET" send val by url ,already get } int ret = 0; if(strcasecmp(method, "POST") == 0 ) //different { do { memset(buf, '\0', sizeof(buf)); ret = get_line(sock, buf, sizeof(buf)); if( strncasecmp(buf, "Content-Length: ", 16) == 0) { content_length = atoi(&buf[16]); } }while( (ret > 0) && strcmp(buf, "\n") != 0 ); printf("content_length = %d\n", content_length); if( content_length == -1 ) { echo_errno(sock); return; } } ///////////// (8.11) ///////////////////////////// sprintf(buf, "HTTP/1.0 200 OK\r\n\r\n"); send(sock, buf, strlen(buf), 0); if( pipe(cgi_input) < 0 ) { echo_errno(sock); return; } if( pipe(cgi_output) < 0 ) { echo_errno(sock); return; } pid_t id = fork(); if(id == 0) //child { close(cgi_input[1]); close(cgi_output[0]); dup2(cgi_input[0], 0); dup2(cgi_output[1], 1); sprintf(method_env, "REQUEST_METHOD=%s", method); putenv(method_env); if( strcasecmp(method, "GET") == 0 ) //GET { sprintf(query_string_env, "QUERY_STRING=%s", query_string); putenv(query_string_env); } else //POST { sprintf(content_length_env, "CONTENT_LENGTH=%d", content_length); putenv(content_length_env); } execl(path, path, NULL); //run here , execl wrong exit(1); } else //father { close(cgi_input[0]); close(cgi_output[1]); // dup2(cgi_input[1], 1); // dup2(cgi_output[0], 0); char c = '\0'; int i =0; if( strcasecmp(method, "POST") == 0 ) { for(; i < content_length; ++i) { recv(sock, &c, 1, 0); printf("%c", c); write(cgi_input[1], &c, 1); } } int ret = 0; while( read(cgi_output[0], &c, 1) > 0) { send(sock, &c, 1, 0); } waitpid(id, NULL, 0); } }
int epFUI_OnRecv(struct ep_t *pep, struct ep_con_t *pnode) { // static int rtimes = 0; // printf("\r--------!!!!!! OnRecv !!!!! --------%8.8x\r",rtimes++); int ret; // char rbuf[100]; struct tmsxx_app *pss; int32_t retRecv, retFramelen, recvTotal; int32_t reserved; char *pdata; // printf("epFUI_OnRecv()\n"); if (pnode->ptr == NULL) { printf("wait \n"); sleep(1); return 1; } #ifdef CONFIG_TEST_NET_STRONG struct tms_context *ptms_context = &(((struct tmsxx_app *)(pnode->ptr))->context); ptms_context->net_pack_id++; #endif pss = (struct tmsxx_app *)pnode->ptr; //pss->morebyte = 100; if (pss->enable_lbb == 0) { pdata = bipbuffer_Reserve(&pss->bb, pss->morebyte, &reserved); } else { // printf("bipbuffer_Reserve lbb "); pdata = bipbuffer_Reserve(&pss->lbb, pss->lbyte, &reserved); int size; bipbuffer_GetContiguousBlock(&pss->lbb, &size); // printf("size %d\n",size); } // printf("1-1 "); // sleep(1); if (pdata == NULL) { retRecv = 1;//无用,必须大于0 // printf("2-0 "); } // 固定环形缓存 else if (pss->enable_lbb == 0) { // printf("want to recv %d\n",reserved); retRecv = recv(pnode->sockfd, pdata, reserved, 0); // printf("retRecv %d\n", retRecv); // printf("recv count = %d\n", retRecv); // printf("2-1 %d ", retRecv); // printf("this times recv %d\n",retRecv); bipbuffer_Commit(&pss->bb, retRecv); } // 大型环形缓存,只够存储一帧数据,填满缓存前不找合法帧, // 填满后无论是否找到合法帧均释放 else { retRecv = recv(pnode->sockfd, pdata, reserved, 0); // printf("recv count = %d\n", retRecv); // printf("2-2 %d ", retRecv); bipbuffer_Commit(&pss->lbb, retRecv); pss->lbyte -= retRecv; if (pss->enable_lbb == 1 && pss->lbyte > 0) { // printf("end 2-3\n"); return retRecv; } else { // printf("e-4 "); struct bipbuffer tbb; tbb = pss->lbb; pss->lbb = pss->bb; pss->bb = tbb; } } //bipbuffer_PrintMemory(&pss->bb); _Again: ; // printf("_Again:"); pdata = bipbuffer_GetContiguousBlock(&pss->bb, &recvTotal); if (bipbuffer_GetUsedSize(&pss->bb) >= 40 && recvTotal < 40) { int unuse; // printf("a -1 "); bipbuffer_GetUnContiguousBlock(&pss->bb, &unuse); } if (recvTotal >= 40) { // printf("a -2 "); ret = glink_FindFrame((int8_t *)pdata, &recvTotal, &retFramelen); } else { // printf("a -3 "); ret = -6; retFramelen = 0; } // printf("ret %d retRecv %d %recvTotal %d retFramelen %d\n", // ret,retRecv,recvTotal,retFramelen); if (ret == 0) { // printf("a -4 "); bipbuffer_DecommitBlock(&pss->bb, retFramelen); // tms_Analyse(pnode->sockfd, (int8_t*)pdata, retFramelen); tms_Analyse( &(((struct tmsxx_app *)(pnode->ptr))->context), (int8_t *)pdata, retFramelen); pss->morebyte = 40; if (pss->enable_lbb == 0) { goto _Again; } //if (reserved > 0) { //} } else if (ret == -2) { // printf("frame err Decommit %d %d\n",retFramelen,reserved); bipbuffer_DecommitBlock(&pss->bb, retFramelen); // printf("a -5 %d\n", retFramelen); pss->morebyte = 40; //if (reserved > 0) { goto _Again; //} } else if (ret == -3) { // #ifdef CONFIG_TEST_NET_STRONG // struct tms_context *ptms_context = &(((struct tmsxx_app*)(pnode->ptr))->context); // ptms_context->net_pack_id++; // #endif // printf("a -6 \n"); // printf("recvTotal %d retFramelen %d used %d\n",recvTotal,retFramelen,bipbuffer_GetUsedSize(&pss->bb)); if (recvTotal + retFramelen <= bipbuffer_GetUsedSize(&pss->bb)) { int unuse; bipbuffer_GetUnContiguousBlock(&pss->bb, &unuse); printf("a-k\n"); } pss->morebyte = 40;//retFramelen; bipbuffer_GetContiguousBlock(&pss->bb, &reserved); // printf("after copy recvTotal %d reserved %d retFramelen %d\n", // recvTotal,reserved,retFramelen); bipbuffer_PrintMemory(&pss->bb); if (reserved >= recvTotal + retFramelen) { printf("a -7 \n "); goto _Again; } if (retFramelen + recvTotal > BIPBUFFER_LEN) { // 初始化大块临时缓存 printf("large bipbuffer\n"); char *pbb_buf, *plbb_buf; int pbb_len, plbb_unuselen; pss->lbyte = recvTotal + retFramelen; bipbuffer_Init(&pss->lbb); bipbuffer_AllocateBuffer(&pss->lbb, pss->lbyte); pbb_buf = bipbuffer_GetContiguousBlock(&pss->bb, &pbb_len); //plbb_buf = bipbuffer_GetContiguousBlock(&pss->lbb, &plbb_unuselen); plbb_buf = bipbuffer_Reserve(&pss->lbb, pbb_len, &plbb_unuselen); memcpy(plbb_buf, pbb_buf, pbb_len); bipbuffer_Commit(&pss->lbb, pbb_len); bipbuffer_DecommitBlock(&pss->bb, pbb_len); pss->lbyte -= pbb_len; pss->enable_lbb = 1; } } if (pss->enable_lbb == 1 && pss->lbyte <= 0) { // printf("free....\n"); struct bipbuffer tbb; pss->enable_lbb = 0; tbb = pss->lbb; pss->lbb = pss->bb; pss->bb = tbb; bipbuffer_FreeBuffer(&pss->lbb); } //printf("end \n"); return retRecv; // ret = recv(pnode->sockfd, rbuf, sizeof(rbuf), 0); // // printf("recv data %s",rbuf); // // 返回值必须是recv函数的返回值 // return ret; }
int internal__hydra_connect(unsigned long int host, int port, int protocol, int type) { int s, ret = -1; struct sockaddr_in target; char *buf, *tmpptr = NULL; struct sockaddr_in sin; #ifndef CYGWIN char out[16]; #endif if ((s = socket(PF_INET, protocol, type)) >= 0) { if (src_port != 0) { int bind_ok=0; sin.sin_family = PF_INET; sin.sin_port = htons(src_port); sin.sin_addr.s_addr = INADDR_ANY; //we will try to find a free port down to 512 while (!bind_ok && src_port >= 512) { if (bind(s, (struct sockaddr *)&sin, sizeof(sin))==-1) { if (verbose) perror("error:"); if (errno == EADDRINUSE) { src_port--; sin.sin_port = htons(src_port); } else { if (errno == EACCES && (getuid() > 0)) { printf("You need to be root to test this service\n"); return -1; } } } else bind_ok=1; } } if (use_proxy > 0) { target.sin_port = htons(proxy_string_port); memcpy(&target.sin_addr.s_addr, &proxy_string_ip, 4); } else { target.sin_port = htons(port); memcpy(&target.sin_addr.s_addr, &host, 4); } target.sin_family = AF_INET; signal(SIGALRM, alarming); do { if (fail > 0) sleep(WAIT_BETWEEN_CONNECT_RETRY); alarm_went_off = 0; alarm(waittime); ret = connect(s, (struct sockaddr *) &target, sizeof(target)); alarm(0); if (ret < 0 && alarm_went_off == 0) { fail++; if (verbose && fail <= MAX_CONNECT_RETRY) fprintf(stderr, "Process %d: Can not connect [unreachable], retrying (%d of %d retries)\n", (int) getpid(), fail, MAX_CONNECT_RETRY); } } while (ret < 0 && fail <= MAX_CONNECT_RETRY); if (ret < 0 && fail > MAX_CONNECT_RETRY) { if (debug) printf("DEBUG_CONNECT_UNREACHABLE\n"); /* we wont quit here, thats up to the module to decide what to do * fprintf(stderr, "Process %d: Can not connect [unreachable], process exiting\n", (int)getpid()); * hydra_child_exit(1); */ extern_socket = -1; ret = -1; return ret; } ret = s; extern_socket = s; if (debug) printf("DEBUG_CONNECT_OK\n"); if (use_proxy == 2) { buf = malloc(4096); memset(&target, 0, sizeof(target)); memcpy(&target.sin_addr.s_addr, &host, 4); target.sin_family = AF_INET; #ifdef CYGWIN if (proxy_authentication == NULL) snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port); else snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port, proxy_authentication); #else if (proxy_authentication == NULL) snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port); else snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port, proxy_authentication); #endif send(s, buf, strlen(buf), 0); recv(s, buf, 4096, 0); if (strncmp("HTTP/", buf, strlen("HTTP/")) == 0 && (tmpptr = index(buf, ' ')) != NULL && *++tmpptr == '2') { if (debug) printf("DEBUG_CONNECT_SSL_OK\n"); } else { if (debug) printf("DEBUG_CONNECT_SSL_FAILED (Code: %c%c%c)\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2)); if (verbose) fprintf(stderr, "Error: CONNECT call to proxy failed with code %c%c%c\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2)); close(s); extern_socket = -1; ret = -1; free(buf); return ret; } free(buf); } fail = 0; return ret; } return ret; }
static void * seq_response(void * arg) { prctl(PR_SET_NAME, "ccnfd_seq", 0, 0, 0); int sock; memcpy(&sock, (int * )arg, sizeof(int)); free(arg); uint32_t payload_size; uint32_t name_len; char str[MAX_NAME_LENGTH]; struct content_name * name = NULL; int chunks; int file_len; int rv = -1; struct segment seg; if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } if (name_len > MAX_NAME_LENGTH) name_len = MAX_NAME_LENGTH - 1; if (recv(sock, str, name_len, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } str[name_len] = '\0'; if (recv(sock, &chunks, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } if (recv(sock, &file_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } name = content_name_create(str); /* if ((seg.obj = CS_getSegment(name)) != NULL) { log_error(g_log, "seq_response: found segment %s in CS", name->full_name); rv = 0; goto RETURN_CONTENT; } */ log_print(g_log, "seq_response: retrieving %d chunks with base: %s", chunks, name->full_name); /* tell the broadcaster not to query the strategy layer to lower overhead */ ccnfdnb_opt_t opts; opts.mode = 0; /* we add a dummy component of maximum length to make sure all the segment * names willl be valid. */ snprintf(str, MAX_NAME_LENGTH - name->len - 1, "%d", chunks); if (content_name_appendComponent(name, str) != 0) { log_error(g_log, "could not append component to name (too long?)"); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } int chunk_size = (chunks > 1) ? ccnf_max_payload_size(name) : file_len; content_name_removeComponent(name, name->num_components - 1); completed_jobs_t dld_segments; pthread_mutex_init(&dld_segments.mutex, NULL); pthread_cond_init(&dld_segments.cond, NULL); dld_segments.completed = linked_list_init(free); seg.name = name; seg.num_chunks = chunks; seg.opts = &opts; seg.chunk_size = chunk_size - 1; seg.obj = malloc(sizeof(struct content_obj)); seg.obj->name = name; seg.obj->data = malloc(file_len); if (!seg.obj->data) { log_error(g_log, "retrieve_segment: failed to allocated %d bytes!", file_len); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } seg.obj->size = file_len; if ((rv = retrieve_segment(&seg)) < 0) { log_error(g_log, "retrieve_segment: failed to get %s!", name->full_name); send(sock, &rv, sizeof(uint32_t), 0); goto END_SEQ_RESP; } /* return the content */ if (send(sock, &rv, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } if (send(sock, &seg.obj->publisher, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } if (send(sock, &name->len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } if (send(sock, name->full_name, name_len, 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } if (send(sock, &seg.obj->timestamp, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } if (send(sock, &seg.obj->size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_SEQ_RESP; } int total = 0; int left = seg.obj->size; int n = -1; while (total < seg.obj->size) { log_debug(g_log, "total = %d", total); n = send(sock, seg.obj->data+total, left, 0); if (n == -1) break; total += n; left -= n; log_debug(g_log, "seq_response: sent %d bytes, %d bytes to go", n, left); } if (n == -1 || left != 0 || total != seg.obj->size) { log_error(g_log, "encountered error, sending segment, sent %d bytes!", total); } else { log_debug(g_log, "seq_response: returned %d bytes", total); } content_obj_destroy(seg.obj); END_SEQ_RESP: close(sock); return NULL; }
wchar_t * badSource(wchar_t * data) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } return data; }
int receive_data (int fd) { char buf[MSG_BUF_SIZE]; int ret = 0; while (1) { ret = recv(fd, buf, MSG_BUF_SIZE, 0); if ((-1 == ret) && (errno == EWOULDBLOCK || errno == EAGAIN)) { continue; } else if(-1 == ret) { syslog(LOG_ERR, "recv error is failed ! : %s\n" , strerror(errno)); goto err_exit; } break; } command_t *recv_data; recv_data = (command_t *)buf; printf("CMD : %c \n", recv_data->cmd ); if (recv_data->cmd == M_CMD_L) { response_t *login_rsp; login_rsp = constr_send_rsp(recv_data); if (login_rsp == NULL) { syslog(LOG_ERR, "constr_send_rsp() is failed !\n"); return -1; } ret = send(fd, login_rsp, LOG_RSP_LEN, 0); if (ret == -1) { syslog(LOG_ERR, "send() login_rsp is failed !\n"); return -1; } free(login_rsp); } else if (recv_data->cmd == M_CMD_S) { //parser cfg data ,call funtion sim_trader_t *sim_data; trad_sim_cfg_t *cfg; cfg = (trad_sim_cfg_t *)recv_data->data; sim_data = sim_trader_init(cfg); if (sim_data == NULL) { syslog(LOG_ERR,"sim_trader_init() IS failed \n"); return -1; } int size = sim_trader_size(sim_data); ret = sim_trader_start(sim_data, fd); if (ret == -1) { syslog(LOG_ERR,"sim_trader_start() IS failed \n"); return -1; } sim_trader_destroy(sim_data); } else { syslog(LOG_ERR , "unexpected cmd %c , ID : %d , len : %d \n", recv_data->cmd, recv_data->id, recv_data->len); return -1; } err_exit: if (fd > 0) { close(fd); syslog(LOG_ERR, " recv_data() fd is close ! \n"); } return -1; }
void main() { int ret; int i, j, k, maxfd, listenfd, connfd; // int sockfd[LISTENQ]; int reuse = 1; fd_set rset, wset; char buf[WAN_MSG_MAX_SIZE]; char cmd_buf[WAN_MSG_MAX_SIZE]; char tmp_buf[WAN_MSG_MAX_SIZE]; char * tmp_buf_pointer; char * endptr; char opt[64]; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; uint16_t csum; uint16_t msg_size_net; uint16_t msg_size; signal(SIGPIPE, sig_pipe_handler); listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd < 0) { perror("socket"); exit(1); } if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { perror("setsockopet"); exit(1); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(WAN_PORT); if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind"); exit(1); } listen(listenfd, LISTENQ); maxfd = listenfd; /* initialize */ do { clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); socket_alive = 1; while(socket_alive) { FD_ZERO(&rset); FD_SET(connfd, &rset); maxfd = connfd; switch(select(maxfd+1, &rset, NULL, NULL, NULL)) { case -1: socket_alive = 0; close(connfd); break; case 0: break; default: #ifdef WANP if(recv(connfd, buf, WAN_HEADER_SIZE, MSG_WAITALL) != WAN_HEADER_SIZE) { perror("recv"); close(connfd); break; } Wan_GetSize(buf, &msg_size); if(recv(connfd, buf + WAN_HEADER_SIZE, msg_size - WAN_HEADER_SIZE, MSG_WAITALL) != msg_size - WAN_HEADER_SIZE) { perror("recv"); close(connfd); break; } if(Wan_CheckMsg(buf, msg_size) < 0) { perror("wan message check error"); close(connfd); break; } #else for(i = 0; i < WAN_MSG_MAX_SIZE; i++) { if(recv(connfd, buf+i, 1, 0) != 1) { perror("recv"); close(connfd); break; } if('\n' == buf[i]) { msg_size = i + 1; break; } } #endif buf[msg_size] = '\0'; GetCmd(buf, cmd_buf); // printf("cmd: %s\n", cmd_buf); // printf("cmd(buf): %s\n", buf); *tmp_buf = '\0'; if(strcmp(cmd_buf, Hello.Name) == 0) { ret = DoHello(buf); if(0 == ret) { RespOK(buf, cmd_buf, NULL); } else if(HELP_HELLO == ret) { tmp_buf_pointer = tmp_buf; tmp_buf_pointer += sprintf(tmp_buf_pointer, "hello: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " a test message to confirm connection.\r\n"); RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "hello err"); } } else if(strcmp(cmd_buf, Burn.Name) == 0) { ret = DoBurn(buf, kernel_name, addr, kernel_size, crc); if(ret == 0) { if('0' == addr[0] && ('x' == addr[1] || 'X' == addr[1])) { i_addr = strtol((const char *)addr, &endptr, 16); } else { i_addr = atoi((const char *)addr); } if('0' == kernel_size[0] && ('x' == kernel_size[1] || 'X' == kernel_size[1])) { i_kernel_size = strtol((const char *)kernel_size, &endptr, 16); } else { i_kernel_size = atoi((const char *)kernel_size); } if('0' == crc[0] && ('x' == crc[1] || 'X' == crc[1])) { i_crc = strtol((const char *)crc, &endptr, 16); } else { i_crc = atoi((const char *)crc); } // i_addr = atoi(addr); // i_kernel_size = atoi(kernel_size); // i_crc = atoi(crc); // printf("i_addr: %d\n", i_addr); // printf("i_kernel_size: %d\n", i_kernel_size); // printf("i_crc: %d\n", i_crc); printf("u_addr:u_kernel_size:u_crc=%08x:%08x:%08x\r\n", i_addr, i_kernel_size, i_crc); RespOK(buf, cmd_buf, NULL); } else if(HELP_BURN == ret) { tmp_buf_pointer = tmp_buf; tmp_buf_pointer += sprintf(tmp_buf_pointer, "burn: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " burn kernel to specific address.\r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " -f\r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, " -a\r\n"); RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "paramter err"); } } else if(strcmp(cmd_buf, Startos.Name) == 0) { ret = DoStartos(buf); if(0 == ret) { RespOK(buf, cmd_buf, NULL); } else if(HELP_STARTOS == ret) { tmp_buf_pointer = tmp_buf; // j = sprintf(tmp_buf_pointer, "startos: \r\n"); tmp_buf_pointer += sprintf(tmp_buf_pointer, "startos: \r\n"); // tmp_buf_pointer += j; tmp_buf_pointer += sprintf(tmp_buf_pointer, " launch the OS kernel.\r\n"); *tmp_buf_pointer = '\0'; RespOK(buf, cmd_buf, tmp_buf); } else { RespErr(buf, cmd_buf, "startos err"); } } else { RespErr(buf, cmd_buf, "Command not found"); } if((msg_size = SealPacket(buf)) < 0) { printf("SealPacket error\r\n"); break; } printf("send: "); for(i = 0; i < msg_size; i++) { printf("%c", buf[i]); } printf("###\n"); if(send(connfd, buf, msg_size, 0) < 0) { perror("send"); close(connfd); break; } printf("\n"); } } }while(1); }
double capacityEstimation_pairs(int tcpsock) { extern int udpsock0; char buf[2000]; int ret1 = 0, ret2 = 0; struct timeval t1, t2, tout; double gap = 0; double cap = -1, mindcap = -1; pcapestack pcapack; pcapack.header.ptype = P_CAP_ACK; pcapack.header.length = 4; int ret = 0; int niters = 0, nfound = 0; double mindelay1 = INT_MAX; double mindelay2 = INT_MAX; double mindelaysum = INT_MAX; double owd1 = 0, owd2 = 0; int mindflag1, mindflag2, mindsumflag; fd_set readset; int maxfd = (udpsock0 > tcpsock) ? udpsock0+1 : tcpsock+1; while(1) { niters++; mindflag1 = mindflag2 = mindsumflag = 0; cap = ret1 = ret2 = -1; FD_ZERO(&readset); FD_SET(udpsock0, &readset); tout.tv_sec = 1; tout.tv_usec = 0; ret = select(maxfd, &readset, NULL, NULL, &tout); if(ret < 0) { fprintf(stderr, "select error\n"); return -1; } else if(ret == 0) { goto noudp; } if(FD_ISSET(udpsock0, &readset)) { ret1 = recv(udpsock0, buf, 2000, 0); if(ret1 == -1) { fprintf(stderr, "recv error on UDP\n"); return -1; } #ifndef OSX if (ioctl(udpsock0, SIOCGSTAMP, &t1) < 0) { perror("ioctl-SIOCGSTAMP"); gettimeofday(&t1,NULL); } #else gettimeofday(&t1, NULL); #endif owd1 = fabs(-1e3*(*(double *)buf - (t1.tv_sec + t1.tv_usec/1.0e6))); mindflag1 = (mindelay1 > owd1) ? 1 : 0; mindelay1 = (mindelay1 > owd1) ? owd1 : mindelay1; } FD_ZERO(&readset); FD_SET(udpsock0, &readset); tout.tv_sec = 10; tout.tv_usec = 0; ret = select(maxfd, &readset, NULL, NULL, &tout); if(ret < 0) { fprintf(stderr, "select error\n"); return -1; } else if(ret == 0) { goto noudp; } if(FD_ISSET(udpsock0, &readset)) { ret2 = recv(udpsock0, buf, 2000, 0); if(ret2 == -1) { fprintf(stderr, "recv error on UDP\n"); return -1; } #ifndef OSX if (ioctl(udpsock0, SIOCGSTAMP, &t2) < 0) { perror("ioctl-SIOCGSTAMP"); gettimeofday(&t2,NULL); } #else gettimeofday(&t2,NULL); #endif owd2 = fabs(-1e3*(*(double *)buf - (t2.tv_sec + t2.tv_usec/1.0e6))); mindflag2 = (mindelay2 > owd2) ? 1 : 0; mindelay2 = (mindelay2 > owd2) ? owd2 : mindelay2; } if(ret1 != ret2 || ret1 == -1 || ret2 == -1) { fprintf(stderr, "sizes %d %d not same OR timeout\n", ret1, ret2); } else { //mindsumflag = (mindelaysum > owd1+owd2) ? 1 : 0; mindelaysum = (mindelaysum > owd1+owd2) ? owd1+owd2 : mindelaysum; mindsumflag = (fabs(owd1+owd2 - (mindelay1+mindelay2)) < 0.01/*0.01*(owd1+owd2)*/) ? 1 : 0; //TODO gap = timeval_diff(t2, t1); //s cap = 1.0e-3*ret1*8.0/gap; //Kbps if(mindsumflag) { mindcap = cap; printf("FOUND!\n"); nfound++; } printf("cap: %.2f Kbps d1:%f d2:%f sum:%f diff:%f\n", cap, owd1, owd2, mindelaysum,fabs(owd1+owd2 - (mindelay1+mindelay2))); } noudp: pcapack.capacity = htonl(cap); pcapack.finalflag = 0; if(niters % 100 == 0 && nfound > 1) { pcapack.finalflag = htonl(1); pcapack.capacity = htonl(mindcap); } ret = writewrapper(tcpsock, (char *)&pcapack, sizeof(struct _capestack)); if(ret == -1) { fprintf(stderr, "SERV: error writing to client: %d\n", tcpsock); close(tcpsock); return -1; } pcapack.finalflag = ntonl(pcapack.finalflag); if(pcapack.finalflag == 1) break; if(niters > 1000) break; } return mindcap; }
/** * Principal */ int main(int argc, char * argv[]) { //sockfd refere-se à escuta, new_fd a novas conexoes int sockfd, new_fd; struct addrinfo hints, *servinfo, *p; //informacao de endereco dos conectores struct sockaddr_storage their_addr; socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; int ativo; // Booleano que indica se a conexao deve continuar ativa // Vetor que contera a opcao do cliente (mais o id do filme, se for o // caso) char opt[4]; loadBooksFromDB(); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; // Stream socket hints.ai_flags = AI_PASSIVE; if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // Percorre a lista ligada e realiza 'bind' ao primeiro que for possivel // Cria todos os file descriptors dos sockets, dando nome a eles for(p = servinfo; p != NULL; p = p->ai_next) { //Função SOCKET: cria um socket, dando acesso ao serviço da camada de transporte if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } //Função bind: atribui um nome ao socket if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } // Debug de erro if (p == NULL) { fprintf(stderr, "servidor: falha ao realizar 'bind'\n"); return 2; } // Necessario devido à chamada 'getaddrinfo' acima freeaddrinfo(servinfo); // Anuncia que está apto para receber conexões if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("servidor: aguardando conexoes...\n"); // Loop de aceitacao principal while(1) { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { // perror("accept"); continue; } inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("servidor: conexao obtida de %s\n", s); // Processo filho if (!fork()) { // Processo filho nao precisa da escuta close(sockfd); ativo = 1; while(ativo){ // Recebe a opcao do client if(recv(new_fd,opt, 4, 0) == -1); perror("recv"); switch(opt[0]){ case '1': // Listar todos os Ids dos filmes com seus respectivos // titulos getAllMovieTitles(new_fd); break; case '2': // Dado o Id de um filme, retornar a sinopse getMovieSynById(new_fd, opt); break; case '3': // Dado o Id de um filme, retornar todas as informações // desse filme getMovieById(new_fd, opt); break; case '4': // Listar todas as informações de todos os filmes; getAllMovies(new_fd); break; case '5': // Finaliza conexao ativo = 0; break; default: printf("Opcao nao valida. Tente novamente\n"); break; } } close(new_fd); exit(0); } // processo pai nao precisa da nova conexao close(new_fd); } return 0; }
int * envia_pacote_modulo_03(int pacote[]) { int sockfd = 0; /* File Description do Socket */ int numbytes = 0; /* Numero de bytes recebidos */ int i = 0; int sin_size = sizeof(struct sockaddr_in); /* Tamanho da estrutura */ struct sockaddr_in serv_addr; /* informação de endereço de informação */ #ifdef COMENTARIOS_M1 //Criando o socket printf("Cria Socket\n"); #endif if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } //printf("Pacote sendo enviado para o modulo 03 - %d - %d\n", sizeof(pacote), (TAM_PKG * sizeof(int))); // printf("ENVIADO: \n"); // for(i=0; i<TAM_PKG; i++) // printf("%d ",pacote[i]); serv_addr.sin_family = AF_INET; /* host byte order */ serv_addr.sin_port = htons(TCP_PORT_MOD3); // Porta onde o Servidor TCP estará ouvindo serv_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(serv_addr.sin_zero), 8);/* zera o resto da estrutura */ #ifdef COMENTARIOS_M1 printf("\nConecta Socket\n"); #endif if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); close(sockfd); printf("Tentando nova conexao em alguns segundos ...\n"); sleep(5); pacote = envia_pacote_modulo_03(pacote); return pacote; } /* * Enviando o pacote para o módulo 03 */ #ifdef COMENTARIOS_M1_SOCKET printf("Envia Socket\n"); for(int i = 0; i < TAM_PKG; i++) printf("Enviando_pkg_para_M3[%d] = %d\n",i,pacote[i]); #endif if (send(sockfd, pacote, (TAM_PKG * sizeof(int)), 0) == -1) { perror("send"); exit(0); } /* * Recebendo o pacote do o módulo 03 */ #ifdef COMENTARIOS_M1_SOCKET printf("Recebe Socket\n"); #endif if ((numbytes=recv(sockfd, pacote, (TAM_PKG * sizeof(int)), 0)) == -1) { perror("recv"); exit(1); } #ifdef COMENTARIOS_M1_SOCKET printf("Recebe Socket2\n"); for(int i = 0; i < TAM_PKG; i++) printf("Recebi_pkg_no_m3[%d] = %d\n",i,pacote[i]); #endif /* * Imprimindo os dados obtidos na transmissão do pacote */ // printf("\n\nRECEBENDO\n"); // for(int i = 0; i < TAM_PKG; i++) // printf("%d ",pacote[i]); close(sockfd); return pacote; }
static int ssl_connect(struct stream *stream) { struct ssl_stream *sslv = ssl_stream_cast(stream); int retval; switch (sslv->state) { case STATE_TCP_CONNECTING: retval = check_connection_completion(sslv->fd); if (retval) { return retval; } sslv->state = STATE_SSL_CONNECTING; setsockopt_tcp_nodelay(sslv->fd); /* Fall through. */ case STATE_SSL_CONNECTING: /* Capture the first few bytes of received data so that we can guess * what kind of funny data we've been sent if SSL negotiation fails. */ if (sslv->n_head <= 0) { sslv->n_head = recv(sslv->fd, sslv->head, sizeof sslv->head, MSG_PEEK); } retval = (sslv->type == CLIENT ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl)); if (retval != 1) { int error = SSL_get_error(sslv->ssl, retval); if (retval < 0 && ssl_wants_io(error)) { return EAGAIN; } else { int unused; interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect" : "SSL_accept"), retval, error, &unused); shutdown(sslv->fd, SHUT_RDWR); stream_report_content(sslv->head, sslv->n_head, STREAM_SSL, THIS_MODULE, stream_get_name(stream)); return EPROTO; } } else if (bootstrap_ca_cert) { return do_ca_cert_bootstrap(stream); } else if (verify_peer_cert && ((SSL_get_verify_mode(sslv->ssl) & (SSL_VERIFY_NONE | SSL_VERIFY_PEER)) != SSL_VERIFY_PEER)) { /* Two or more SSL connections completed at the same time while we * were in bootstrap mode. Only one of these can finish the * bootstrap successfully. The other one(s) must be rejected * because they were not verified against the bootstrapped CA * certificate. (Alternatively we could verify them against the CA * certificate, but that's more trouble than it's worth. These * connections will succeed the next time they retry, assuming that * they have a certificate against the correct CA.) */ VLOG_INFO("rejecting SSL connection during bootstrap race window"); return EPROTO; } else { return 0; } } OVS_NOT_REACHED(); }
int main() { int sock; int client_sock; int yes = 1; int fifo; // char * audio_fifo = "/tmp/audio_fifo"; int mode = 0; // 0 = Wait, 1 = Video, 2 = Audio uint32_t remain_bytes = 0; struct sockaddr_in addr; struct sockaddr_in client; addr.sin_family = AF_INET; addr.sin_port = htons(62309); addr.sin_addr.s_addr = INADDR_ANY; sock = socket(AF_INET, SOCK_STREAM, 0); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes)); bind(sock, (struct sockaddr *)&addr, sizeof(addr)); if (listen(sock, 5) != 0) { printf("Listen failed.\n"); } uint32_t row; char *video; video = (char *) malloc(16588800); if (video == NULL) { printf("malloc failed.\n"); exit(EXIT_FAILURE); } char buf[65535]; // sock = socket(AF_INET, SOCK_DGRAM, 0); // // addr.sin_family = AF_INET; // addr.sin_port = htons(62308); // addr.sin_addr.s_addr = INADDR_ANY; // // bind(sock, (struct sockaddr *) &addr, sizeof(addr)); // fprintf(stderr, "res: %d\n", res); // mkfifo("/tmp/audio_fifo", 0666); // fifo = open("/tmp/audio_fifo", O_WRONLY); // fprintf(stderr, "fifo: %d\n", fifo); // printf("Waiting\n"); socklen_t len = sizeof(client); client_sock = accept(sock, (struct sockaddr *)&client, &len); // write(sock, "HELLO", 5); while (1) { int buf_size = remain_bytes != 0 && sizeof(buf) > remain_bytes ? remain_bytes : sizeof(buf); int recv_bytes = recv(client_sock, buf, buf_size, 0); // fprintf(stderr, "Receive: %i, mode: %i\n", recv_bytes, mode); if (mode == 0) { struct stream_info info; memcpy(&info, buf, sizeof(stream_info)); if (info.type == T_STREAM_VIDEO) { mode = 1; } if (info.type == T_STREAM_AUDIO) { mode = 2; } remain_bytes = info.bytes; } else { if (recv_bytes != -1) { remain_bytes -= recv_bytes; // fprintf(stderr, "remain_bytes: %u\n", remain_bytes); write(mode, buf, recv_bytes); // if (mode == 1) { // write(1, buf, recv_bytes); // } else { // write(fifo, buf, recv_bytes); // } if (remain_bytes == 0) { remain_bytes = sizeof(stream_info); // fprintf(stderr, "remain_bytes zero: %u\n", remain_bytes); mode = 0; } } } // fprintf(stderr, "remain_bytes: %i\n", remain_bytes); // recv(sock, video, sizeof(video), 0); // struct stream_header header; // memcpy(&header, buf, sizeof(stream_header)); // // memcpy(&row, buf, sizeof(uint32_t)); // memcpy(video + rowbytes * header.row + chunk_size * header.chunk, buf + sizeof(stream_header), chunk_size); // memcpy(video, ) // if (header.row == height - 1) { // write(1, video, rowbytes * height); // } // printf("Frame received (#%4u)\n", row); } // printf("%s\n", buf); //close(sock); return 0; }
static void * seq_publish(void * arg) { prctl(PR_SET_NAME, "ccnfd_pubseq", 0, 0, 0); log_print(g_log, "seq_publish: handling publish request"); int sock; memcpy(&sock, (int * )arg, sizeof(int)); free(arg); struct content_obj * index_chunk; index_chunk = (struct content_obj *) malloc(sizeof(struct content_obj)); /* finish rcving the summary request packet */ /* structure of publish msg: * publisher : int * name_len : int * name : char[name_len] * timestamp : int * size : int * data : byte[size] */ uint32_t publisher; uint32_t payload_size; uint32_t name_len; uint8_t name[MAX_NAME_LENGTH]; uint32_t timestamp; uint32_t size; uint8_t * data = NULL; int rv = 0; if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &publisher, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (name_len > MAX_NAME_LENGTH) name_len = MAX_NAME_LENGTH - 1; if (recv(sock, name, name_len, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } name[name_len] = '\0'; if (recv(sock, ×tamp, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } data = (uint8_t *) malloc(size); if (recv(sock, data, size, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); free(data); rv = -1; goto END_PUBLISH_RESP; } index_chunk->name = content_name_create((char * )name); index_chunk->publisher = publisher; index_chunk->size = size; index_chunk->timestamp = timestamp; index_chunk->data = data; int num_chunks = 0; if (recv(sock, &num_chunks, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); free(data); rv = -1; goto END_PUBLISH_RESP; } struct linked_list * chunks = linked_list_init(NULL); int i; for (i = 0; i < num_chunks; i++) { if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &publisher, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (name_len > MAX_NAME_LENGTH) name_len = MAX_NAME_LENGTH - 1; if (recv(sock, name, name_len, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } name[name_len] = '\0'; if (recv(sock, ×tamp, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } if (recv(sock, &size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; goto END_PUBLISH_RESP; } data = (uint8_t *) malloc(size); if (recv(sock, data, size, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); rv = -1; free(data); goto END_PUBLISH_RESP; } struct content_obj * chunk = malloc(sizeof(struct content_obj)); chunk->name = content_name_create((char * )name); chunk->publisher = publisher; chunk->size = size; chunk->timestamp = timestamp; chunk->data = data; linked_list_append(chunks, chunk); } CS_putSegment(index_chunk, chunks); linked_list_delete(chunks); if (send(sock, &rv, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } log_print(g_log, "Successfully published segment:\n" "\t\t\t\t\t\tname = %s\n" "\t\t\t\t\t\ttimestamp = %d\n" "\t\t\t\t\t\tnum chunks = %d", index_chunk->name->full_name, timestamp , num_chunks); END_PUBLISH_RESP: close(sock); return NULL; }
int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_in echoServAddr; /* Echo server address */ unsigned short echoServPort; /* Echo server port */ char *servIP; /* Server IP address (dotted quad) */ char *echoString; /* String to send to echo server */ char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ unsigned int echoStringLen; /* Length of string to echo */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ echoString = argv[2]; /* Second arg: string to echo */ if (argc == 4) echoServPort = atoi(argv[3]); /* Use given port, if any */ else echoServPort = 7; /* 7 is the well-known port for the echo service */ /* Create a reliable, stream socket using TCP */ if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */ echoServAddr.sin_port = htons(echoServPort); /* Server port */ /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); echoStringLen = strlen(echoString); /* Determine input length */ /* Send the string to the server */ if (send(sock, echoString, echoStringLen, 0) != echoStringLen) DieWithError("send() sent a different number of bytes than expected"); /* Receive the same string back from the server */ totalBytesRcvd = 0; printf("Received: "); /* Setup to print the echoed string */ while (totalBytesRcvd < echoStringLen) { /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ printf("%s", echoBuffer); /* Print the echo buffer */ } printf("\n"); /* Print a final linefeed */ close(sock); exit(0); }
static void * retrieve_response(void * arg) { prctl(PR_SET_NAME, "ccnfd_ret", 0, 0, 0); int sock; memcpy(&sock, (int * )arg, sizeof(int)); free(arg); uint32_t payload_size; uint32_t name_len; char str[MAX_NAME_LENGTH]; struct content_name * name = NULL; struct content_obj * content = NULL; if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (name_len > MAX_NAME_LENGTH) name_len = MAX_NAME_LENGTH - 1; if (recv(sock, str, name_len, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } str[name_len] = '\0'; log_print(g_log, "retrieve_response: handling retrieve request for %s", str); name = content_name_create(str); /* we check the CS for the content first */ content = CS_get(name); int rv = 0; if (!content) { log_print(g_log, "retreive_response: CS miss, expressing interest for content %s", str); /* we don't have the content, we need to express an intrest for it */ rv = ccnfdnb_express_interest(name, &content, 0, NULL); content_name_delete(name); } if (send(sock, &rv, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (rv != 0) goto END_RETRIEVE_RESP; /* return the content */ uint32_t publisher = content->publisher; name_len = content->name->len; uint32_t timestamp = content->timestamp; uint32_t size = content->size; uint8_t * data = content->data; if (send(sock, &publisher, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (send(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (send(sock, content->name->full_name, name_len, 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (send(sock, ×tamp, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (send(sock, &size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } if (send(sock, data, size, 0) == -1) { log_error(g_log, "send: %s.", strerror(errno)); goto END_RETRIEVE_RESP; } END_RETRIEVE_RESP: close(sock); return NULL; }
static int httprecv(int sfd, struct string* buf, int* httpres) { char* b; ssize_t bl, bptr = 0; size_t i; struct string oneline; int retval = HTTP_EOK; int BUFSIZE = 8192; int isfirsthdr = 1; if ((b = malloc(BUFSIZE)) == NULL) return HTTP_ENOMEM; string_init(&oneline, 512, 512); while(1) { bl = recv(sfd, b + bptr, BUFSIZE - bptr, 0); if (bl == 0) { if (bptr == 0) { break; } } else if (bl < 0) { retval = HTTP_ENETERR; goto bail_out; } bptr += bl; if ((*b == '\n') || (*b == '\r')) goto finished; for (i = 0; i < bptr; i++) { if (b[i] == '\n') { string_clear(&oneline); if (string_concatb(&oneline, b, i)) { retval=HTTP_ENOMEM; goto bail_out; } if (oneline.s[oneline._u._s.length - 1] == '\r') --oneline._u._s.length; if (++i >= bptr) { retval=HTTP_ESRVERR; goto bail_out; } if (bptr != i) { memmove(b, b + i, bptr - i); } bptr -= i; if (isfirsthdr) { if (handle_header(&oneline, httpres)) { retval=HTTP_ESRVERR; goto bail_out; } isfirsthdr = 0; } break; } } } finished: if (isfirsthdr) { retval=HTTP_ESRVERR; goto bail_out; } bl = 0; if (bptr > 2) { if ((b[0] == '\r') || (b[0] == '\n')) { ++bl; if ((b[1] == '\r') || (b[1] == '\n')) { ++bl; } } } if (string_concatb(buf, b + bl, bptr - bl)) { retval=HTTP_ENOMEM; goto bail_out; } while(1) { bl = recv(sfd, b, BUFSIZE, 0); if (bl == 0) break; if (bl < 0) { retval=HTTP_ENETERR; goto bail_out; } if (string_concatb(buf, b, bl)) { retval=HTTP_ENOMEM; goto bail_out; } } if (retval == HTTP_EOK) if (*httpres != 200) retval = HTTP_ESRVERR; bail_out: close(sfd); string_free(&oneline); free(b); return retval; }
// Game::Next step void Game::NextStep() { char tmp[256]; int choice; if( enemy == NULL ) { if( (GameMode == 1 || NextPlayer == 1 && GameMode != MODE_NET_CLIENT) || (GameMode == MODE_NET_CLIENT && NextPlayer == 2) ) { printf("Player %d (1-9): ", NextPlayer); memset(tmp,0,256); #ifdef _WIN32 scanf_s("%s", tmp); #else scanf("%s", tmp); #endif choice = atoi(tmp); if(choice<1 || choice>9 || Board[choice-1] != 3) return; Board[choice-1] = (char) (NextPlayer - 1); } } switch(GameMode) { case 1: if(NextPlayer == 1) { NextPlayer = 2; } else { NextPlayer = 1; } break; case 2: if(NextPlayer == 2) { printf("Enemy is thinkin'...\n"); Board[enemy->Analyze(Board)] = 1; NextPlayer = 1; } else { NextPlayer = 2; } break; case MODE_NET_HOST: if( NextPlayer == 2 ) { printf("Waiting for Player 2...\n"); recv(this->Server->GetClient(), tmp, 1, 0); Board[atoi(tmp)-1] = 1; NextPlayer = 1; } else { send(this->Server->GetClient(), Board, 9,0); NextPlayer = 2; } break; case MODE_NET_CLIENT: if( NextPlayer == 1 ) { printf("Waiting for Player 1...\n"); recv(this->Client->GetClient(), Board, 9, 0); NextPlayer = 2; } else { Board[atoi(tmp)-1] = 1; send(this->Client->GetClient(), tmp, 1, 0); NextPlayer = 1; } break; default: break; } }
static ssize_t recv_buffer(int fd, int fds[3]) { struct iovec iov = { .iov_base = buffer, .iov_len = sizeof(buffer) }; struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_controllen = CMSG_SPACE(3 * sizeof(int)), }; msg.msg_control = alloca(msg.msg_controllen); memset(msg.msg_control, 0, msg.msg_controllen); ssize_t recvd; NO_EINTR(recvd, recvmsg(fd, &msg, 0)); if (recvd == -1) { perror("recvmsg"); return -1; } if (recvd < 4) { ssize_t recvd_; do { NO_EINTR(recvd_, recv(fd, buffer + recvd, sizeof(buffer) - recvd, 0)); if (recvd_ > 0) recvd += recvd_; } while (recvd_ > 0 && recvd < 4); } size_t target = -1; if (recvd > 4) { target = unbyte(buffer[0],0) | unbyte(buffer[1],1) | unbyte(buffer[2],2) | unbyte(buffer[3],3); if (recvd < target) { ssize_t recvd_; do { NO_EINTR(recvd_, recv(fd, buffer + recvd, sizeof(buffer) - recvd, 0)); if (recvd_ > 0) recvd += recvd_; } while (recvd_ > 0 && recvd < target); } } struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); int *fds0 = (int*)CMSG_DATA(cm); int nfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int); /* Check malformed packet */ if (nfds != 3 || recvd != target || buffer[recvd-1] != '\0') { int i; for (i = 0; i < nfds; ++i) close(fds0[i]); return -1; } fds[0] = fds0[0]; fds[1] = fds0[1]; fds[2] = fds0[2]; return recvd; } value ml_merlin_server_setup(value path, value strfd) { CAMLparam2(path, strfd); CAMLlocal2(payload, ret); char *endptr = NULL; int fd = strtol(String_val(strfd), &endptr, 0); if (endptr && *endptr == '\0') { /* (path, fd) */ payload = caml_alloc(2, 0); Store_field(payload, 0, path); Store_field(payload, 1, Val_int(fd)); /* Some payload */ ret = caml_alloc(1, 0); Store_field(ret, 0, payload); } else { fprintf(stderr, "ml_merlin_server_setup(\"%s\",\"%s\"): invalid argument\n", String_val(path), String_val(strfd)); unlink(String_val(path)); /* None */ ret = Val_unit; } CAMLreturn(ret); } value ml_merlin_server_accept(value server, value val_timeout) { CAMLparam2(server, val_timeout); CAMLlocal4(ret, client, args, context); // Compute timeout double timeout = Double_val(val_timeout); struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = (timeout - tv.tv_sec) * 1000000; // Select on server int serverfd = Int_val(Field(server, 1)); int selectres; fd_set readset; do { FD_ZERO(&readset); FD_SET(serverfd, &readset); selectres = select(serverfd + 1, &readset, NULL, NULL, &tv); } while (selectres == -1 && errno == EINTR); int fds[3], clientfd; ssize_t len = -1; if (selectres > 0) { NO_EINTR(clientfd, accept(serverfd, NULL, NULL)); len = recv_buffer(clientfd, fds); } if (len == -1) ret = Val_unit; /* None */ else { context = caml_alloc(4, 0); /* (clientfd, stdin, stdout, stderr) */ Store_field(context, 0, Val_int(clientfd)); Store_field(context, 1, Val_int(fds[0])); Store_field(context, 2, Val_int(fds[1])); Store_field(context, 3, Val_int(fds[2])); ssize_t i, j; int argc = 0; for (i = 4; i < len; ++i) if (buffer[i] == '\0') argc += 1; args = caml_alloc(argc, 0); argc = 0; for (i = 4, j = 4; i < len; ++i) { if (buffer[i] == '\0') { Store_field(args, argc, caml_copy_string((const char *)&buffer[j])); j = i + 1; argc += 1; } } client = caml_alloc(2, 0); /* (context, args) */ Store_field(client, 0, context); Store_field(client, 1, args); ret = caml_alloc(1, 0); /* Some client */ Store_field(ret, 0, client); } CAMLreturn(ret); }
int bluetooth_read(int fd, __ptr_t bytes, int size, struct gn_statemachine *state) { return recv((SOCKET)fd, bytes, size, 0); }
int receive_tcp(char *bind_ip, char *bind_port) { int sock, cli_sock; char *buf; struct sockaddr_in remote, local; int ret = -1; int select_return; fd_set read_set, err_set; struct timeval timeout; buf = (char *) malloc(255); memset(buf, '\0', 255); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Socket error:"); return(-1); } local.sin_family = AF_INET; local.sin_port = htons(atoi(bind_port)); inet_aton(bind_ip, &local.sin_addr); if (bind(sock, (struct sockaddr *) &local, sizeof(local)) < 0) { perror("Could not bind."); return (-1); } if (listen(sock, 5) == -1) { perror("Could not listen: "); return(-1); } FD_ZERO(&read_set); FD_SET(sock, &read_set); FD_ZERO(&err_set); FD_SET(sock, &err_set); timeout.tv_sec = 10; timeout.tv_usec = 0; select_return = select(sock + 1, &read_set, NULL, &err_set, &timeout); if (select_return < 0) { perror("Select failed: "); ret = -1; } if ((select_return > 0) && (FD_ISSET(sock, &read_set)) && (!FD_ISSET(sock, &err_set))) { if ((cli_sock = accept(sock, NULL, NULL)) < 0) { perror("Accept failed: "); ret = -1; } else { if (recv(cli_sock, buf, 255, 0) >= 1) { printf("MESSAGE: %s\n", buf); ret = 0; } else { perror("recv failure: "); ret = -1; } } } else { perror("There were select failures: "); ret = -1; } free(buf); return(ret); }
/* Receive the HTTP/1.1 response preceded by a call to sendHttpRequest(). Function is called recursively until error or succesfully retreived full or partial document. returnedWebpageHtml: Pointer to be filled with HTML document. htmlDocumentSize: Size of the HTML document to be set. checkDocumentSizeOnly: If true, will only set the document's size and not store the HTML document. */ bool HTTPClient::receiveHttpResponse(char* tempReturnedWebpageHtml, int& htmlDocumentSize) const{ char recvBuffer[RECV_BUFFER_SIZE]; fd_set rfds; struct timeval tv; int retval; while (true){ //Clear FD's and add sockets FD_ZERO(&rfds); FD_SET(sockFd, &rfds); //Set timeout tv.tv_sec = SELECT_WAIT_SEC; tv.tv_usec = SELECT_WAIT_MSEC; //Select retval = select(sockFd + 1, &rfds, NULL, NULL, &tv); if (retval == -1){ //printf("select() returned with error\n"); break; } else{ if (FD_ISSET(sockFd, &rfds)) { // If maximum length exceeded for webpage if ((htmlDocumentSize + 1)>MAXIMUM_WEBPAGE_LENGTH) return false; int recvSize = recv(sockFd, recvBuffer, sizeof(recvBuffer), 0); //printf("recvSize: %d \n", recvSize); if (recvSize == 0) break; strcpy(tempReturnedWebpageHtml + htmlDocumentSize, recvBuffer); htmlDocumentSize += recvSize; } else { //printf("Select()->Recv() timed out. \n"); //Connection closed, done receiving document if (htmlDocumentSize != 0) break; //If no document was received and timed out, retry if (!receiveHttpResponse(tempReturnedWebpageHtml, htmlDocumentSize)) { throw HTTPClientException("httpRequestWebpage(const char*, int, char**)", "Unable to retreive html document.\n"); } break; } } } //If failed to receive anything, else successfully retrieved webpage if (htmlDocumentSize == 0) return false; tempReturnedWebpageHtml[htmlDocumentSize + 1] = '\0'; return true; }
int _eXosip_recvfrom (int s, char *buf, int len, unsigned int flags, struct sockaddr *from, socklen_t * fromlen) { int message_size = 0; int length_done = 0; int real_size = 0; int i; int extra_data_discarded; if (!eXosip.http_port) { return recvfrom (s, buf, len, flags, from, fromlen); } /* we get the size of the HTTP data */ i = recv (eXosip.net_interfaces[0].net_socket, (char *) &(message_size), 4, 0); real_size = message_size; if (message_size < 0) { return -1; /* Connection error? */ } if (message_size == 0) { buf[0] = '\0'; return 0; } if (message_size > len - 1) message_size = len - 1; length_done = 0; i = recv (eXosip.net_interfaces[0].net_socket, buf, message_size, 0); length_done = i; if (length_done == real_size) { return length_done; } if (length_done < message_size) { /* continue reading up to message_size */ while (length_done < message_size) { i = recv (eXosip.net_interfaces[0].net_socket, buf + length_done, message_size - length_done, 0); length_done = length_done + i; } } extra_data_discarded = length_done; while (extra_data_discarded < real_size) { char buf2[2048]; /* We have to discard the end of data... up to the next message */ i = recv (eXosip.net_interfaces[0].net_socket, buf2, 2048, 0); extra_data_discarded = extra_data_discarded + i; } return length_done; }
int Socket::Recv(char *buff, int len, int flags) { int n; n = recv(m_sockfd, buff, len, flags); return (n); }
static int ccnfdl_accept(struct ccnfd_msg * msg) { if (!msg) { log_error(g_log, "ccnfd_accept: msg ptr NULL -- IGNORING"); return -1; } int sock2, n; struct sockaddr_un remote; socklen_t t = sizeof(struct sockaddr_un); if ((sock2 = accept(_listener.sock, (struct sockaddr *) &remote, &t)) == -1) { log_error(g_log, "accept: %s.", strerror(errno)); return -1; } if ((n = recv(sock2, &msg->type, sizeof(uint8_t), 0)) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); return -1; } /* see if we should process the message right now */ if (msg->type == MSG_IPC_CS_SUMMARY_REQ || msg->type == MSG_IPC_PUBLISH || msg->type == MSG_IPC_SEQ_PUBLISH || msg->type == MSG_IPC_RETRIEVE || msg->type == MSG_IPC_SEQ_RETRIEVE) { void * func = NULL; switch (msg->type) { case MSG_IPC_CS_SUMMARY_REQ: func = create_summary_response; break; case MSG_IPC_PUBLISH: func = publish_response; break; case MSG_IPC_SEQ_PUBLISH: func = seq_publish; break; case MSG_IPC_RETRIEVE: func = retrieve_response; break; case MSG_IPC_SEQ_RETRIEVE: func = seq_response; break; } msg->payload = NULL; int * child_sock = malloc(sizeof(int)); *child_sock = sock2; tpool_add_job(&_listener.interest_pipeline, func, child_sock, TPOOL_NO_RV, NULL, NULL); return 0; } if ((n = recv(sock2, &msg->payload_size, sizeof(uint32_t), 0)) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); return -1; } msg->payload = (uint8_t * ) malloc(msg->payload_size); n = recv(sock2, msg->payload, msg->payload_size, 0); if (n < msg->payload_size) { log_warn(g_log, "recv: got %d bytes, expected %d bytes!", n, msg->payload_size); return -1; } else if (n < 0) { log_error(g_log, "recv: %s.", strerror(errno)); return -1; } close(sock2); log_print(g_log, "ccnfd_accept: recieved a message of type: %d and size: %d", msg->type, n); return 0; }
Connection* ConnectionInit(Connection* connection) { ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER; #ifndef AIO4C_WIN32 if ((connection->socket = socket(PF_INET, SOCK_STREAM, 0)) == -1) { code.error = errno; #else /* AIO4C_WIN32 */ if ((connection->socket = socket(PF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) { code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_SOCKET_ERROR, &code); } #ifndef AIO4C_WIN32 if (fcntl(connection->socket, F_SETFL, O_NONBLOCK) == -1) { code.error = errno; #else /* AIO4C_WIN32 */ unsigned long ioctl = 1; if (ioctlsocket(connection->socket, FIONBIO, &ioctl) == SOCKET_ERROR) { code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_FCNTL_ERROR, &code); } ConnectionState(connection, AIO4C_CONNECTION_STATE_INITIALIZED); return connection; } Connection* ConnectionConnect(Connection* connection) { ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER; ConnectionState newState = AIO4C_CONNECTION_STATE_CONNECTING; if (connection->state != AIO4C_CONNECTION_STATE_INITIALIZED) { code.expected = AIO4C_CONNECTION_STATE_INITIALIZED; return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_DEBUG, AIO4C_CONNECTION_STATE_ERROR, &code); } if (connect(connection->socket, AddressGetAddr(connection->address), AddressGetAddrSize(connection->address)) == -1) { #ifndef AIO4C_WIN32 code.error = errno; if (errno == EINPROGRESS) { #else /* AIO4C_WIN32 */ int error = WSAGetLastError(); code.source = AIO4C_ERRNO_SOURCE_WSA; if (error == WSAEINPROGRESS || error == WSAEALREADY || error == WSAEWOULDBLOCK) { #endif /* AIO4C_WIN32 */ newState = AIO4C_CONNECTION_STATE_CONNECTING; } else { return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_CONNECT_ERROR, &code); } } else { newState = AIO4C_CONNECTION_STATE_CONNECTED; } ConnectionState(connection, newState); return connection; } Connection* ConnectionFinishConnect(Connection* connection) { ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER; int soError = 0; socklen_t soSize = sizeof(int); #ifdef AIO4C_HAVE_POLL aio4c_poll_t polls[1] = { { .fd = connection->socket, .events = POLLOUT, .revents = 0 } }; #ifndef AIO4C_WIN32 if (poll(polls, 1, -1) == -1) { code.error = errno; #else /* AIO4C_WIN32 */ if (WSAPoll(polls, 1, -1) == SOCKET_ERROR) { code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_POLL_ERROR, &code); } if (polls[0].revents > 0) { #else /* AIO4C_HAVE_POLL */ fd_set writeSet; fd_set errorSet; FD_ZERO(&writeSet); FD_ZERO(&errorSet); FD_SET(connection->socket, &writeSet); FD_SET(connection->socket, &errorSet); #ifndef AIO4C_WIN32 if (select(connection->socket + 1, NULL, &writeSet, &errorSet, NULL) == -1) { code.error = errno; #else /* AIO4C_WIN32 */ if (select(connection->socket + 1, NULL, &writeSet, &errorSet, NULL) == SOCKET_ERROR) { code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_SELECT_ERROR, &code); } if (FD_ISSET(connection->socket, &writeSet) || FD_ISSET(connection->socket, &errorSet)) { #endif /* AIO4C_HAVE_POLL */ #ifndef AIO4C_WIN32 if (getsockopt(connection->socket, SOL_SOCKET, SO_ERROR, &soError, &soSize) != 0) { code.error = errno; #else /* AI4OC_WIN32 */ if (getsockopt(connection->socket, SOL_SOCKET, SO_ERROR, (char*)&soError, &soSize) == SOCKET_ERROR) { code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_GETSOCKOPT_ERROR, &code); } if (soError != 0) { #ifndef AIO4C_WIN32 code.error = soError; #else /* AIO4C_WIN32 */ code.source = AIO4C_ERRNO_SOURCE_SOE; code.soError = soError; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_FINISH_CONNECT_ERROR, &code); } } return connection; } Connection* ConnectionRead(Connection* connection) { Buffer* buffer = NULL; ssize_t nbRead = 0; ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER; aio4c_byte_t* data = NULL; buffer = connection->readBuffer; if (!BufferHasRemaining(buffer)) { code.buffer = buffer; return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_BUFFER_OVERFLOW_ERROR, &code); } data = BufferGetBytes(buffer); if ((nbRead = recv(connection->socket, (void*)&data[BufferGetPosition(buffer)], BufferRemaining(buffer), 0)) < 0) { #ifndef AIO4C_WIN32 code.error = errno; #else /* AIO4C_WIN32 */ code.source = AIO4C_ERRNO_SOURCE_WSA; #endif /* AIO4C_WIN32 */ return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_ERROR, AIO4C_READ_ERROR, &code); } ProbeSize(AIO4C_PROBE_NETWORK_READ_SIZE, nbRead); if (nbRead == 0) { if (connection->state == AIO4C_CONNECTION_STATE_PENDING_CLOSE) { ConnectionState(connection, AIO4C_CONNECTION_STATE_CLOSED); return connection; } else { return _ConnectionHandleError(connection, AIO4C_LOG_LEVEL_INFO, AIO4C_CONNECTION_DISCONNECTED, &code); } } if (!connection->canRead) { Log(AIO4C_LOG_LEVEL_WARN, "received data on connection %s when reading is not allowed", connection->string); BufferReset(buffer); return connection; } BufferPosition(buffer, BufferGetPosition(buffer) + nbRead); _ConnectionEventHandle(connection, AIO4C_INBOUND_DATA_EVENT); return connection; }
static void * publish_response(void * arg) { prctl(PR_SET_NAME, "ccnfd_pub", 0, 0, 0); log_print(g_log, "publish_response: handling publish request"); int sock; memcpy(&sock, (int * )arg, sizeof(int)); free(arg); struct content_obj * content; content = (struct content_obj *) malloc(sizeof(struct content_obj)); /* finish rcving the summary request packet */ /* structure of publish msg: * publisher : int * name_len : int * name : char[name_len] * timestamp : int * size : int * data : byte[size] */ uint32_t publisher; uint32_t payload_size; uint32_t name_len; uint8_t name[MAX_NAME_LENGTH]; uint32_t timestamp; uint32_t size; uint8_t * data = NULL; if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } if (recv(sock, &publisher, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } if (name_len > MAX_NAME_LENGTH) name_len = MAX_NAME_LENGTH - 1; if (recv(sock, name, name_len, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } name[name_len] = '\0'; if (recv(sock, ×tamp, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } if (recv(sock, &size, sizeof(uint32_t), 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } data = (uint8_t *) malloc(size); if (recv(sock, data, size, 0) == -1) { log_error(g_log, "recv: %s.", strerror(errno)); free(data); goto END_PUBLISH_RESP; } content->name = content_name_create((char * )name); content->publisher = publisher; content->size = size; content->timestamp = timestamp; content->data = data; int rv = CS_put(content); if (send(sock, &rv, sizeof(uint32_t), 0) == -1) { log_print(g_log, "recv: %s.", strerror(errno)); goto END_PUBLISH_RESP; } log_print(g_log, "Successfully published content:\n" "\t\t\t\t\t\tname = %s\n" "\t\t\t\t\t\ttimestamp = %d\n" "\t\t\t\t\t\tsize = %d", name, timestamp , size); END_PUBLISH_RESP: close(sock); return NULL; }
void Socket::socketThread() { Json::Reader reader; bool running = true; int addrinfo_status, connect_status, socket_status = 0; while ( running ) { if ( !socketfd || socket_status ) { struct addrinfo host_info; struct addrinfo *host_info_list; // Close the existing socket, if it has been left open. if ( socketfd ) { close( socketfd ); socketfd = NULL; } // Establish connection memset( &host_info, 0, sizeof host_info ); host_info.ai_family = AF_UNSPEC; host_info.ai_socktype = SOCK_STREAM; addrinfo_status = getaddrinfo( hostname, port, &host_info, &host_info_list ); if ( addrinfo_status ) { std::cout << "couldn't get address" << std::endl ; sleep(1); continue; } socketfd = socket( host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol ); if ( socketfd == -1 ) { socket_status = -1; std::cout << "socket error" << std::endl ; sleep(1); continue; } connect_status = connect( socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen ); if ( connect_status ) { socket_status = -1; std::cout << "connect error" << std::endl ; sleep(1); continue; } socket_status = 0; } int max_message_size = 1000000; ssize_t bytes_recieved; struct hss_header header; string buffer; bytes_recieved = recv( socketfd, &header, sizeof header, 0 ); //std::cout << "received " << bytes_recieved << std::endl; if ( bytes_recieved == sizeof header ) { // Parse the header ( what there is of it ) header.string_bytes = ntohl( header.string_bytes ); if ( header.string_bytes > max_message_size ) { // Bad header, f**k it. socket_status = -3; std::cout << "bad header, disconnecting"; continue; } buffer.resize( header.string_bytes ); size_t b = recv( socketfd, (void * ) buffer.c_str(), header.string_bytes, MSG_WAITALL ); if ( b != header.string_bytes ) { } Json::Value msg; //std::cout << buffer << std::endl; reader.parse( buffer, msg ); Json::Value set = msg["set"]; if ( set.isObject() ) { Json::Value set = msg["set"]; for ( Json::ValueIterator i = set.begin(); i != set.end(); i ++ ) { string k = (string) i.memberName(); horten->set( set[k], k, flags ); } } } else if (bytes_recieved == 0) { std::cout << "host shut down." << std::endl ; socket_status = -3; sleep(1); } else if (bytes_recieved == -1 ) { std::cout << "receive error! " << errno << std::endl ; socket_status = -4; sleep(1); } } }
static int xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) { #ifdef HAVE_POLL_H struct pollfd p; #else fd_set rfd; struct timeval tv; #endif while (ctxt->state & XML_NANO_HTTP_READ) { if (ctxt->in == NULL) { ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char)); if (ctxt->in == NULL) { xmlHTTPErrMemory("allocating input"); ctxt->last = -1; return (-1); } ctxt->inlen = 65000; ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in; } if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) { int delta = ctxt->inrptr - ctxt->in; int len = ctxt->inptr - ctxt->inrptr; memmove(ctxt->in, ctxt->inrptr, len); ctxt->inrptr -= delta; ctxt->content -= delta; ctxt->inptr -= delta; } if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) { int d_inptr = ctxt->inptr - ctxt->in; int d_content = ctxt->content - ctxt->in; int d_inrptr = ctxt->inrptr - ctxt->in; char *tmp_ptr = ctxt->in; ctxt->inlen *= 2; ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen); if (ctxt->in == NULL) { xmlHTTPErrMemory("allocating input buffer"); xmlFree(tmp_ptr); ctxt->last = -1; return (-1); } ctxt->inptr = ctxt->in + d_inptr; ctxt->content = ctxt->in + d_content; ctxt->inrptr = ctxt->in + d_inrptr; } ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0); if (ctxt->last > 0) { ctxt->inptr += ctxt->last; return (ctxt->last); } if (ctxt->last == 0) { return (0); } if (ctxt->last == -1) { switch (socket_errno()) { case EINPROGRESS: case EWOULDBLOCK: #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK case EAGAIN: #endif break; case ECONNRESET: case ESHUTDOWN: return (0); default: __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n"); return (-1); } } #ifdef HAVE_POLL_H p.fd = ctxt->fd; p.events = POLLIN; if ((poll(&p, 1, timeout * 1000) < 1) #if defined(EINTR) && (errno != EINTR) #endif ) return (0); #else /* !HAVE_POLL_H */ #ifndef _WINSOCKAPI_ if (ctxt->fd > FD_SETSIZE) return 0; #endif tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&rfd); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4018) #endif FD_SET(ctxt->fd, &rfd); #ifdef _MSC_VER #pragma warning(pop) #endif if ((select(ctxt->fd + 1, &rfd, NULL, NULL, &tv) < 1) #if defined(EINTR) && (errno != EINTR) #endif ) return (0); #endif /* !HAVE_POLL_H */ } return (0); }