void start_connect(struct connection *c) { c->read = 0; c->bread = 0; c->keepalive = 0; c->cbx = 0; c->gotheader = 0; c->fd = socket(AF_INET, SOCK_STREAM, 0); if(c->fd<0) err("socket"); nonblock(c->fd); gettimeofday(&c->start,0); if(connect(c->fd, (struct sockaddr *) &server, sizeof(server))<0) { if(errno==EINPROGRESS) { c->state = STATE_CONNECTING; FD_SET(c->fd, &writebits); return; } else { close(c->fd); err_conn++; if(bad++>10) { printf("\nTest aborted after 10 failures\n\n"); exit(1); } start_connect(c); } } /* connected first time */ write_request(c); }
int TcpClient::run(Request& req, std::ostream& out) { int returnCode = -1; try { std::ostringstream request_stream; write_request(req, request_stream); this->send(request_stream.str()); this->receive(rcvBuffer_); std::stringstream response_stream; response_stream.write((char*)rcvBuffer_.data(), rcvBuffer_.size()); string line; while (response_stream) { std::getline(response_stream, line); if(endsWith(line,"__JANOSH_EOF")) { out << line.substr(0, line.size() - string("__JANOSH_EOF").size()); std::getline(response_stream, line); returnCode = std::stoi(line); if (returnCode == 0) { LOG_DEBUG_STR("Successful"); } else { LOG_INFO_MSG("Failed", returnCode); } break; } out << line << '\n'; } } catch (std::exception& ex) { LOG_ERR_MSG("Caught in tcp_client run", ex.what()); } return returnCode; }
void dispatch_request(char* from, char* to, int accept_socket, int* keep_alive){ char* req_str = (char*) malloc(sizeof(char) * (to - from + 1)); char* char_i; int int_i; int _ = 0; for(char_i = from, int_i = 0; char_i < to; char_i++, int_i++){ *(req_str + int_i) = *(char_i); } *(req_str + int_i) = '\0'; struct request* req = malloc_request(); parse_request(req, req_str); struct response* resp = malloc_response(req); //free(req_str); write_request(resp, accept_socket); if(resp->html == 0){ read_file(req->resource_name, accept_socket); } else{ _ = write(accept_socket, resp->html, strlen(resp->html)); } if(_ == -1){ printf("scream write %d\n", _); } *keep_alive = req->keep_alive; free(req_str); free_request(req); print_response(resp); free_response(resp); }
static void protocol_test(FILE *bei, FILE *beo) { Json::Value req; Json::Value res; req["command"] = "initialize"; req["debug"] = true; write_request(req, bei); read_response(res, beo); if (res["version"].asString() != WEB_EXTENSION_VERSION) { std::cerr << "Version mismatch" << std::endl; exit(EXIT_FAILURE); } req.clear(); res.clear(); req["command"] = "get_certificates"; write_request(req, bei); read_response(res, beo); if (!res["certificates"][0].isMember("der")) { std::cerr << "Failed to get certificate" << std::endl; exit(EXIT_FAILURE); } std::string der = res["certificates"][0]["der"].asString(); req.clear(); res.clear(); req["command"] = "sign_data"; req["certificate"] = der; req["data"] = "SGVsbG8sIHdvcmxkIQo="; write_request(req, bei); read_response(res, beo); static const char ERROR[] = "error:"; if (!res["result"].asString().compare(0, strlen(ERROR), ERROR)) { std::cerr << "Signature error" << std::endl; exit(EXIT_FAILURE); } std::cout << "Test passed" << std::endl; }
int main(int argc, char* argv[]){ int msg_id = shmget(MSG_NAME(0), 0, 0); volatile int* msg0 = shmat(msg_id, 0, 0); msg_id = shmget(MSG_NAME(1), 0, 0); volatile int* msg1 = shmat(msg_id, 0, 0); read_request(msg0, 6, 1); read_request(msg1, 3, 1); read_request(msg0, 8, 1); read_request(msg1, 9, 1); write_request(msg0, 1, 1, 1); write_request(msg0, 4, 3, 1); write_request(msg0, 2, 4, 1); write_request(msg1, 8, 3, 1); write_request(msg1, 7, 0, 1); int ans = read_request(msg0, 8, 1); printf("%d\n", ans); return 0; }
int smtp_client::detail::command(buffered_file& conn, const string_ref *vec, int cnt, string_ref& resp_r, posix_error_callback& ec) { conn.reset_cursor(); int r; if ((r = write_request(conn.get_file(), vec, cnt, ec)) <= 0) { return r; /* unexpected eof or error */ } r = read_response(conn, resp_r, ec); return r; }
void main_loop(void) { int i, n, timeout = 250; struct connection *conn; ufds = must_calloc(thread_limit, sizeof(struct pollfd)); for (i = 0; i < thread_limit; ++i) ufds[i].fd = -1; while (head || outstanding) { start_next_comic(); n = poll(ufds, thread_limit, timeout); if (n < 0) { my_perror("poll"); continue; } if (n == 0) { timeout_connections(); if (!start_next_comic()) /* Once we have all the comics * started, increase the timeout * period. */ timeout = 1000; continue; } for (conn = comics; conn; conn = conn->next) if (!conn->poll) continue; else if (conn->poll->revents & POLLOUT) { if (!conn->connected) check_connect(conn); else { time(&conn->access); write_request(conn); } } else if (conn->poll->revents & POLLIN) { /* This check is needed for openssl */ if (!conn->connected) check_connect(conn); else read_conn(conn); } } free(ufds); }
void client_poll(reg fd, enum event_types t) { switch (client.event) { case READ: closed_socket(client.socket,"Read failed") ? disconnect() : read_request(); break; case WRITE: closed_socket(client.socket,"Write failed") ? disconnect() : send_response(); break; case REQ: closed_socket(client.socket,"Request failed") ? disconnect() : write_request(); break; case RESP: closed_socket(client.socket,"Response failed") ? disconnect() : read_response(); break; default: debug("UNKNOWN EVENT"); } }
static void test(struct global * registry) { struct timeval timeout, now; fd_set sel_read, sel_except, sel_write; int i; registry->con = calloc(registry->concurrency, sizeof(struct connection)); memset(registry->con, 0, registry->concurrency * sizeof(struct connection)); #ifdef AB_DEBUG printf("AB_DEBUG: start of test()\n"); #endif for (i = 0; i < registry->concurrency; i++) { registry->con[i].url = registry->ready_to_run_queue[i].url; registry->con[i].run = registry->ready_to_run_queue[i].run; registry->con[i].state = STATE_READY; registry->con[i].thread = registry->ready_to_run_queue[i].thread; } #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 1\n"); #endif registry->stats = calloc(registry->number_of_urls, sizeof(struct data *)); for (i = 0; i < registry->number_of_runs; i++) { int j; for (j = registry->position[i]; j < registry->position[i+1]; j++) registry->stats[j] = calloc(registry->repeats[i], sizeof(struct data)); } #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 2\n"); #endif FD_ZERO(®istry->readbits); FD_ZERO(®istry->writebits); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 3\n"); #endif /* ok - lets start */ gettimeofday(®istry->starttime, 0); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 4\n"); #endif /* initialise lots of requests */ registry->head = registry->concurrency; for (i = 0; i < registry->concurrency; i++) start_connect(registry, ®istry->con[i]); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5\n"); #endif while (registry->done < registry->need_to_be_done) { int n; #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.1, registry->done = %d\n", registry->done); #endif /* setup bit arrays */ memcpy(&sel_except, ®istry->readbits, sizeof(registry->readbits)); memcpy(&sel_read, ®istry->readbits, sizeof(registry->readbits)); memcpy(&sel_write, ®istry->writebits, sizeof(registry->writebits)); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.2, registry->done = %d\n", registry->done); #endif /* Timeout of 30 seconds, or minimum time limit specified by config. */ timeout.tv_sec = registry->min_tlimit.tv_sec; timeout.tv_usec = registry->min_tlimit.tv_usec; n = select(FD_SETSIZE, &sel_read, &sel_write, &sel_except, &timeout); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.3, registry->done = %d\n", registry->done); #endif if (!n) myerr(registry->warn_and_error, "Server timed out"); if (n < 1) myerr(registry->warn_and_error, "Select error."); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.4, registry->done = %d\n", registry->done); #endif /* check for time limit expiry */ gettimeofday(&now, 0); if (registry->tlimit && timedif(now, registry->starttime) > (registry->tlimit * 1000)) { char *warn = malloc(256 * sizeof(char)); sprintf(warn, "Global time limit reached (%.2f sec), premature exit", registry->tlimit); myerr(registry->warn_and_error, warn); free(warn); registry->need_to_be_done = registry->done; /* break out of loop */ } for (i = 0; i < registry->concurrency; i++) { int s = registry->con[i].fd; #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.5, registry->done = %d, i = %d\n", registry->done, i); #endif if (registry->started[registry->con[i].url] > registry->finished[registry->con[i].url]) { struct connection * c = ®istry->con[i]; struct timeval url_now; /* check for per-url time limit expiry */ gettimeofday(&url_now, 0); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.5.4, Time taken for current request = %d ms; Per-url time limit = %.4f sec; for run %d, url %d\n", timedif(url_now, c->start_time), registry->url_tlimit[c->url], c->run, c->url - registry->position[c->run]); printf("AB_DEBUG: test() - stage 5.5.5, registry->done = %d, i = %d\n", registry->done, i); #endif if (registry->url_tlimit[c->url] && timedif(url_now, c->start_time) > (registry->url_tlimit[c->url] * 1000)) { char *warn = malloc(256 * sizeof(char)); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.5.5.3, registry->done = %d, i = %d\n", registry->done, i); #endif sprintf(warn, "Per-url time limit reached (%.3f sec) for run %d, url %d, iteration %d; connection closed prematurely", registry->url_tlimit[c->url], c->run, c->url - registry->position[c->run], c->thread); myerr(registry->warn_and_error, warn); free(warn); registry->failed[c->url]++; close_connection(registry, c); continue; } } if (registry->con[i].state == STATE_DONE) continue; #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.6, registry->done = %d, i = %d\n", registry->done, i); #endif if (FD_ISSET(s, &sel_except)) { registry->failed[registry->con[i].url]++; start_connect(registry, ®istry->con[i]); continue; } #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.7, registry->done = %d, i = %d\n", registry->done, i); #endif if (FD_ISSET(s, &sel_read)) { read_connection(registry, ®istry->con[i]); continue; } #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.8, registry->done = %d, i = %d\n", registry->done, i); #endif if (FD_ISSET(s, &sel_write)) write_request(registry, ®istry->con[i]); #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 5.9, registry->done = %d, i = %d\n", registry->done, i); #endif } } #ifdef AB_DEBUG printf("AB_DEBUG: test() - stage 6\n"); #endif gettimeofday(®istry->endtime, 0); if (strlen(registry->warn_and_error) == 28) myerr(registry->warn_and_error, "None.\n"); else myerr(registry->warn_and_error, "Done.\n"); }
void check_connections(void) { fd_set fds_write; fd_set fds_read; int i; struct timeval timeout; time_t now; FD_ZERO(&fds_write); /* These are for connection being established */ FD_ZERO(&fds_read); /* These are for a reply being ready */ /* FD_SET(0, &fds_read);*/ for (i = 0 ; i < MAX_IDENTS_IN_PROGRESS ; i++) { if (idents_in_progress[i].local_port) { if (idents_in_progress[i].flags & IDENT_CONNREFUSED) { process_result(i); } else if (!(idents_in_progress[i].flags & IDENT_CONNECTED)) { FD_SET(idents_in_progress[i].fd, &fds_write); } else { FD_SET(idents_in_progress[i].fd, &fds_read); } } else { /* Free slot, so lets try to fill it */ take_off_queue(i); } } #if defined(NOALARM) timeout.tv_sec = 1; timeout.tv_usec = 0; #else /* !NOALARM */ timeout.tv_sec = 0; timeout.tv_usec = 0; #endif /* NOALARM */ i = select(FD_SETSIZE, &fds_read, &fds_write, 0, &timeout); switch (i) { case -1: #if defined(DEBUG_IDENT_TOO) fprintf(stderr, "ident: select failed\n"); #endif /* DEBUG_IDENT_TOO */ break; case 0: break; default: for (i = 0 ; i < MAX_IDENTS_IN_PROGRESS ; i++) { if (FD_ISSET(idents_in_progress[i].fd, &fds_write)) { /* Has now connected, so send request */ idents_in_progress[i].flags |= IDENT_CONNECTED; write_request(&idents_in_progress[i]); } else if (FD_ISSET(idents_in_progress[i].fd, &fds_read)) { /* Reply is ready, so process it */ idents_in_progress[i].flags |= IDENT_REPLY_READY; process_result(i); } } } now = time(NULL); for (i = 0 ; i < MAX_IDENTS_IN_PROGRESS ; i++) { if (idents_in_progress[i].local_port) { if (now > (idents_in_progress[i].request_time + IDENT_TIMEOUT)) { /* Request has timed out, whether on connect or reply */ idents_in_progress[i].flags |= IDENT_TIMEDOUT; process_result(i); } } } }
int main(int argc, char *argv[]) { char *env; int i, n, timeout = 250; struct connection *conn; method = "HEAD"; while ((i = getopt(argc, argv, "hp:t:vT:")) != -1) switch ((char)i) { case 'h': usage(0); case 'p': set_proxy(optarg); break; case 't': thread_limit = strtol(optarg, NULL, 0); break; case 'v': verbose++; break; case 'T': read_timeout = strtol(optarg, NULL, 0); break; default: usage(1); } if (optind < argc) while (optind < argc) read_link_file(argv[optind++]); else read_urls(stdin); /* set_proxy will not use this if proxy already set */ env = getenv("COMICS_PROXY"); if (env) set_proxy(env); if (thread_limit == 0) { printf("You must allow at least one thread\n"); exit(1); } if (thread_limit > n_comics) thread_limit = n_comics; #ifdef _WIN32 win32_init(); #else signal(SIGTERM, dump_outstanding); signal(SIGHUP, dump_outstanding); #endif npoll = thread_limit + 1; /* add one for stdin */ ufds = must_calloc(npoll, sizeof(struct pollfd)); for (i = 0; i < npoll; ++i) ufds[i].fd = -1; while (head || outstanding) { start_next_comic(); n = poll(ufds, npoll, timeout); if (n < 0) { my_perror("poll"); continue; } if (n == 0) { timeout_connections(); if (!start_next_comic()) /* Once we have all the comics * started, increase the timeout * period. */ timeout = 1000; continue; } for (conn = comics; conn; conn = conn->next) if (!conn->poll) continue; else if (conn->poll->revents & POLLOUT) { if (!conn->connected) check_connect(conn); else { time(&conn->access); write_request(conn); } } else if (conn->poll->revents & POLLIN) { /* This check is needed for openssl */ if (!conn->connected) check_connect(conn); else read_conn(conn); } } out_results(comics, 0); return n_comics != gotit; }
static void *mainloop(void *thread_arg) { struct REQUEST *conns = NULL; int curr_conn = 0; struct REQUEST *req, *prev, *tmp; struct timeval tv; int max; socklen_t length; fd_set rd, wr; for (; !termsig;) { if (got_sighup) { got_sighup = 0; } FD_ZERO(&rd); FD_ZERO(&wr); max = 0; /* add listening socket */ if (curr_conn < max_conn) { FD_SET(slisten, &rd); max = slisten; } /* add connection sockets */ for (req = conns; req != NULL; req = req->next) { switch (req->state) { case STATE_KEEPALIVE: case STATE_READ_HEADER: FD_SET(req->fd, &rd); if (req->fd > max) { max = req->fd; } break; case STATE_WRITE_HEADER: case STATE_WRITE_BODY: case STATE_WRITE_FILE: case STATE_WRITE_RANGES: FD_SET(req->fd, &wr); if (req->fd > max) { max = req->fd; } break; } } /* go! */ tv.tv_sec = keepalive_time; tv.tv_usec = 0; if (-1 == select(max + 1, &rd, &wr, NULL, (curr_conn > 0) ? &tv : NULL)) { perror("select"); continue; } now = time(NULL); /* new connection ? */ if (FD_ISSET(slisten, &rd)) { req = malloc(sizeof(struct REQUEST)); if (NULL != req) { memset(req, 0, sizeof(struct REQUEST)); if (-1 == (req->fd = accept(slisten, NULL, NULL))) { if (EAGAIN != errno) { free(req); } } else { close_on_exec(req->fd); fcntl(req->fd, F_SETFL, O_NONBLOCK); req->bfd = -1; req->state = STATE_READ_HEADER; req->ping = now; req->next = conns; conns = req; curr_conn++; /* Make sure the request has not been cancelled! * Otherwise just ignore it. */ if (req) { length = sizeof(req->peer); if (-1 == getpeername(req->fd, (struct sockaddr *) & (req->peer), &length)) { req->state = STATE_CLOSE; } getnameinfo((struct sockaddr *)&req->peer, length, req->peerhost, MAX_HOST, req->peerserv, MAX_MISC, NI_NUMERICHOST | NI_NUMERICSERV); printf("%s:\tfd: %03d; connect from %s\n", get_time(), req->fd , req->peerhost); } } } } /* check active connections */ for (req = conns, prev = NULL; req != NULL;) { /* handle I/O */ switch (req->state) { case STATE_KEEPALIVE: case STATE_READ_HEADER: if (FD_ISSET(req->fd, &rd)) { req->state = STATE_READ_HEADER; read_request(req, 0); req->ping = now; } break; case STATE_WRITE_HEADER: case STATE_WRITE_BODY: case STATE_WRITE_FILE: case STATE_WRITE_RANGES: if (FD_ISSET(req->fd, &wr)) { write_request(req); req->ping = now; } break; } /* check timeouts */ if (req->state == STATE_KEEPALIVE) { if (now > req->ping + keepalive_time || curr_conn > max_conn * 9 / 10) { req->state = STATE_CLOSE; } } else if (req->state > 0) { if (now > req->ping + timeout) { if (req->state == STATE_READ_HEADER) { mkerror(req, 408, 0); } else { req->state = STATE_CLOSE; } } } /* header parsing */ header_parsing: if (req->state == STATE_PARSE_HEADER) { parse_request(req); if (req->state == STATE_WRITE_HEADER) { write_request(req); } } /* handle finished requests */ if (req->state == STATE_FINISHED && !req->keep_alive) { req->state = STATE_CLOSE; } if (req->state == STATE_FINISHED) { req->auth[0] = 0; req->if_modified = NULL; req->if_unmodified = NULL; req->if_range = NULL; req->range_hdr = NULL; req->ranges = 0; if (req->r_start) { free(req->r_start); req->r_start = NULL; } if (req->r_end) { free(req->r_end); req->r_end = NULL; } if (req->r_head) { free(req->r_head); req->r_head = NULL; } if (req->r_hlen) { free(req->r_hlen); req->r_hlen = NULL; } list_free(&req->header); memset(req->mtime, 0, sizeof(req->mtime)); if (req->bfd != -1) { close(req->bfd); req->bfd = -1; } req->body = NULL; req->written = 0; req->head_only = 0; req->rh = 0; req->rb = 0; if (req->dir) { free_dir(req->dir); req->dir = NULL; } req->hostname[0] = 0; req->path[0] = 0; req->query[0] = 0; if (req->hdata == req->lreq) { /* ok, wait for the next one ... */ req->state = STATE_KEEPALIVE; req->hdata = 0; req->lreq = 0; } else { /* there is a pipelined request in the queue ... */ req->state = STATE_READ_HEADER; memmove(req->hreq, req->hreq + req->lreq, req->hdata - req->lreq); req->hdata -= req->lreq; req->lreq = 0; read_request(req, 1); goto header_parsing; } } /* connections to close */ if (req->state == STATE_CLOSE) { close(req->fd); if (req->bfd != -1) { close(req->bfd); } if (req->dir) { free_dir(req->dir); } curr_conn--; printf("%s:\tfd: %03d; current connections: %d\n", get_time(), req->fd, curr_conn); /* unlink from list */ tmp = req; if (prev == NULL) { conns = req->next; req = conns; } else { prev->next = req->next; req = req->next; } /* free memory */ if (tmp->r_start) { free(tmp->r_start); } if (tmp->r_end) { free(tmp->r_end); } if (tmp->r_head) { free(tmp->r_head); } if (tmp->r_hlen) { free(tmp->r_hlen); } list_free(&tmp->header); free(tmp); } else { prev = req; req = req->next; } } } return NULL; }
/* handle a file descriptor event */ int httpd_handle_event(fd_set *rset, fd_set *wset, fd_sets_t *fds) { struct REQUEST *req, *prev, *tmp; int length; int opt = 0; now = time(NULL); /* new connection ? */ if ((rset != NULL) && FD_ISSET(slisten, rset)) { req = malloc(sizeof(struct REQUEST)); if (NULL == req) { /* oom: let the request sit in the listen queue */ #ifdef DEBUG fprintf(stderr,"oom\n"); #endif } else { memset(req,0,sizeof(struct REQUEST)); if ((req->fd = accept(slisten,NULL,&opt)) == -1) { if (EAGAIN != errno) { log_error_func(1, LOG_WARNING,"accept",NULL); } free(req); } else { fcntl(req->fd,F_SETFL,O_NONBLOCK); req->bfd = -1; req->state = STATE_READ_HEADER; req->ping = now; req->lifespan = -1; req->next = conns; conns = req; curr_conn++; #ifdef DEBUG fprintf(stderr,"%03d/%d: new request (%d)\n",req->fd,req->state,curr_conn); #endif #ifdef USE_SSL if (with_ssl) { open_ssl_session(req); } #endif length = sizeof(req->peer); if (getpeername(req->fd,(struct sockaddr*)&(req->peer),&length) == -1) { log_error_func(1, LOG_WARNING,"getpeername",NULL); req->state = STATE_CLOSE; } getnameinfo((struct sockaddr*)&req->peer,length, req->peerhost,64,req->peerserv,8, NI_NUMERICHOST | NI_NUMERICSERV); #ifdef DEBUG fprintf(stderr,"%03d/%d: connect from (%s)\n", req->fd,req->state,req->peerhost); #endif /* host auth callback */ if (access_check_func != NULL) { if (access_check_func(req->peerhost, NULL) < 0) { /* read request */ read_header(req,0); req->ping = now; /* reply with access denied and close connection */ mkerror(req,403,0); write_request(req); req->state = STATE_CLOSE; } } FD_SET(req->fd, &fds->rset); if (req->fd > fds->max) { fds->max = req->fd; } } } } /* check active connections */ for (req = conns, prev = NULL; req != NULL;) { /* I/O */ if ((rset != NULL) && FD_ISSET(req->fd, rset)) { if (req->state == STATE_KEEPALIVE) { req->state = STATE_READ_HEADER; } if (req->state == STATE_READ_HEADER) { while (read_header(req,0) > 0); } if (req->state == STATE_READ_BODY) { while (read_body(req, 0) >0); } req->ping = now; } if ((wset != NULL) && FD_ISSET(req->fd, wset)) { write_request(req); req->ping = now; } /* check timeouts */ if (req->state == STATE_KEEPALIVE) { if (now > req->ping + keepalive_time || curr_conn > max_conn * 9 / 10) { #ifdef DEBUG fprintf(stderr,"%03d/%d: keepalive timeout\n",req->fd,req->state); #endif req->state = STATE_CLOSE; } } else { if (now > req->ping + timeout) { if ((req->state == STATE_READ_HEADER) || (req->state == STATE_READ_BODY)) { mkerror(req,408,0); } else { log_error_func(0,LOG_INFO,"network timeout",req->peerhost); req->state = STATE_CLOSE; } } } /* parsing */ parsing: if (req->state == STATE_PARSE_HEADER) { parse_request(req, server_host); } /* body parsing */ if (req->state == STATE_PARSE_BODY) { parse_request_body(req); } if (req->state == STATE_WRITE_HEADER) { /* switch to writing */ FD_CLR(req->fd, &fds->rset); FD_SET(req->fd, &fds->wset); write_request(req); } /* handle finished requests */ if (req->state == STATE_FINISHED && !req->keep_alive) { req->state = STATE_CLOSE; } if (req->state == STATE_FINISHED) { /* access log hook */ if (log_request_func != NULL) { log_request_func(req, now); } /* switch to reading */ FD_CLR(req->fd, &fds->wset); FD_SET(req->fd, &fds->rset); /* cleanup */ req->auth[0] = 0; req->if_modified = 0; req->if_unmodified = 0; req->if_range = 0; req->range_hdr = NULL; req->ranges = 0; if (req->r_start) { free(req->r_start); req->r_start = NULL; } if (req->r_end) { free(req->r_end); req->r_end = NULL; } if (req->r_head) { free(req->r_head); req->r_head = NULL; } if (req->r_hlen) { free(req->r_hlen); req->r_hlen = NULL; } list_free(&req->header); if (req->bfd != -1) { close(req->bfd); req->bfd = -1; } /* free memory of response body */ if ((req->status<400) && (req->body != NULL)) { free(req->body); req->body = NULL; } req->written = 0; req->head_only = 0; req->rh = 0; req->rb = 0; req->hostname[0] = 0; req->path[0] = 0; req->query[0] = 0; req->lifespan = -1; if (req->hdata == (req->lreq + req->lbreq)) { /* ok, wait for the next one ... */ #ifdef DEBUG fprintf(stderr,"%03d/%d: keepalive wait\n",req->fd,req->state); #endif req->state = STATE_KEEPALIVE; req->hdata = 0; req->lreq = 0; req->lbreq = 0; #ifdef TCP_CORK if (req->tcp_cork == 1) { req->tcp_cork = 0; #ifdef DEBUG fprintf(stderr,"%03d/%d: tcp_cork=%d\n",req->fd,req->state,req->tcp_cork); #endif setsockopt(req->fd,SOL_TCP,TCP_CORK,&req->tcp_cork,sizeof(int)); } #endif } else { /* there is a pipelined request in the queue ... */ #ifdef DEBUG fprintf(stderr,"%03d/%d: keepalive pipeline\n",req->fd,req->state); #endif req->state = STATE_READ_HEADER; memmove(req->hreq,req->hreq + req->lreq + req->lbreq, req->hdata - (req->lreq + req->lbreq)); req->hdata -= req->lreq + req->lbreq; req->lreq = 0; read_header(req,1); goto parsing; } } /* connections to close */ if (req->state == STATE_CLOSE) { /* access log hook */ /*if (log_request_func != NULL) { log_request_func(req, now); }*/ FD_CLR(req->fd, &fds->rset); FD_CLR(req->fd, &fds->wset); /* leave max as is */ /* cleanup */ close(req->fd); #ifdef USE_SSL if (with_ssl) { SSL_free(req->ssl_s); } #endif if (req->bfd != -1) { close(req->bfd); #ifdef USE_SSL if (with_ssl) { BIO_vfree(req->bio_in); } #endif } curr_conn--; #ifdef DEBUG fprintf(stderr,"%03d/%d: done (%d)\n",req->fd,req->state,curr_conn); #endif /* unlink from list */ tmp = req; if (prev == NULL) { conns = req->next; req = conns; } else { prev->next = req->next; req = req->next; } /* free memory */ if (tmp->r_start) { free(tmp->r_start); } if (tmp->r_end) { free(tmp->r_end); } if (tmp->r_head) { free(tmp->r_head); } if (tmp->r_hlen) { free(tmp->r_hlen); } list_free(&tmp->header); free(tmp); } else { prev = req; req = req->next; } } return 0; }
static int opensoap_handler(request_rec *r) { apr_status_t rv = 0; char req_id[128]; char res_id[128]; int rc = 0; #ifdef DEBUG ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : start"); #endif if (strcmp(r->handler, "opensoap")) { return DECLINED; } if (r->header_only) return HTTP_BAD_REQUEST; if(r->method_number != M_POST) return HTTP_BAD_REQUEST; SetProcessInfo(); WriteLog(8,"mod_opensoap start"); /***** Read Request and Write to File ******/ rc = write_request(r, req_id); if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : write_request(r, req_id)"); return HTTP_INTERNAL_SERVER_ERROR; } else if (rc == DSO_TOO_BIG) { read_response(r, req_id); rc = delete_files(req_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(res_id)"); } return OK; } /****** Invoke Req_Id and Get Res_ID *******/ WriteLog(9,"invoke start"); rc = InvokeOpenSOAPServer(req_id, res_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : InvokeOpenSOAPServer(req_id, res_id)"); return HTTP_INTERNAL_SERVER_ERROR; } WriteLog(9,res_id); #ifdef DEBUG ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : InvokeOpenSOAPServer req_id = %s", req_id); ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : InvokeOpenSOAPServer res_id = %s", res_id); #endif /******** Load Response form File **********/ rc = read_response(r, res_id); if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : read_response(r, res_id)"); return HTTP_INTERNAL_SERVER_ERROR; } /****** Delete Files ******/ rc = delete_files(req_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(req_id)"); } rc = delete_files(res_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(res_id)"); } WriteLog(8,"mod_opensoap end"); return OK; }
/** * Handle a request. */ static int caucho_request(request_rec *r, config_t *config, resin_host_t *host, unsigned int now) { stream_t s; int retval; int code = -1; int session_index; int backup_index = 0; char *ip; srun_t *srun; if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK))) return retval; session_index = get_session_index(config, r, &backup_index); ip = r->connection->REMOTE_IP; if (host) { } else if (config->manual_host) { host = config->manual_host; } else { host = cse_match_host(config, ap_get_server_name(r), ap_get_server_port(r), now); } LOG(("%s:%d:caucho_request(): session index: %d\n", __FILE__, __LINE__, session_index)); if (! host) { ERR(("%s:%d:caucho_request(): no host: %p\n", __FILE__, __LINE__, host)); return HTTP_SERVICE_UNAVAILABLE; } else if (! cse_open_connection(&s, &host->cluster, session_index, backup_index, now, r->pool)) { ERR(("%s:%d:caucho_request(): no connection: cluster(%p)\n", __FILE__, __LINE__, &host->cluster)); return HTTP_SERVICE_UNAVAILABLE; } srun = s.cluster_srun->srun; apr_thread_mutex_lock(srun->lock); srun->active_sockets++; apr_thread_mutex_unlock(srun->lock); code = write_request(&s, r, config, session_index, backup_index); apr_thread_mutex_lock(srun->lock); srun->active_sockets--; apr_thread_mutex_unlock(srun->lock); /* on failure, do not failover but simply fail */ if (code == HMUX_QUIT) cse_free_idle(&s, now); else cse_close(&s, "no reuse"); if (code != HMUX_QUIT && code != HMUX_EXIT) { ERR(("%s:%d:caucho_request(): protocol failure code:%d\n", __FILE__, __LINE__, code)); return HTTP_SERVICE_UNAVAILABLE; } else if (r->status == HTTP_SERVICE_UNAVAILABLE) { cse_close(&s, "close from 503"); cse_srun_unavail(srun, now); return HTTP_SERVICE_UNAVAILABLE; } else { /* * See pages like jms/index.xtp int status = r->status; r->status = HTTP_OK; return status; */ return OK; } }
void read_connection(struct connection *c) { int r; r=read(c->fd,buffer,sizeof(buffer)); if(r==0 || (r<0 && errno!=EAGAIN)) { good++; close_connection(c); return; } if(r<0 && errno==EAGAIN) return; c->read += r; totalread += r; if(!c->gotheader) { char *s; int l=4; int space = CBUFFSIZE - c->cbx - 1; /* -1 to allow for 0 terminator */ int tocopy = (space<r)?space:r; memcpy(c->cbuff+c->cbx, buffer, space); c->cbx += tocopy; space -= tocopy; c->cbuff[c->cbx] = 0; /* terminate for benefit of strstr */ s = strstr(c->cbuff, "\r\n\r\n"); /* this next line is so that we talk to NCSA 1.5 which blatantly breaks the http specifaction */ if(!s) { s = strstr(c->cbuff,"\n\n"); l=2; } if(!s) { /* read rest next time */ if(space) return; else { /* header is in invalid or too big - close connection */ close(c->fd); if(bad++>10) { printf("\nTest aborted after 10 failures\n\n"); exit(1); } FD_CLR(c->fd, &writebits); start_connect(c); } } else { /* have full header */ if(!good) { /* this is first time, extract some interesting info */ char *p, *q; p = strstr(c->cbuff, "Server:"); q = server_name; if(p) { p+=8; while(*p>32) *q++ = *p++; } *q = 0; } c->gotheader = 1; *s = 0; /* terminate at end of header */ if(keepalive && (strstr(c->cbuff, "Keep-Alive") || strstr(c->cbuff, "keep-alive"))) /* for benefit of MSIIS */ { char *cl; cl = strstr(c->cbuff, "Content-Length:"); /* for cacky servers like NCSA which break the spec and send a lower case 'l' */ if(!cl) cl = strstr(c->cbuff, "Content-length:"); if(cl) { c->keepalive=1; c->length = atoi(cl+16); } } c->bread += c->cbx - (s+l-c->cbuff) + r-tocopy; totalbread += c->bread; } } else { /* outside header, everything we have read is entity body */ c->bread += r; totalbread += r; } if(c->keepalive && (c->bread >= c->length)) { /* finished a keep-alive connection */ good++; doneka++; /* save out time */ if(good==1) { /* first time here */ doclen = c->bread; } else if(c->bread!=doclen) { bad++; err_length++; } if(done < requests) { struct data s; gettimeofday(&c->done,0); s.read = c->read; s.ctime = timedif(c->connect, c->start); s.time = timedif(c->done, c->start); stats[done++] = s; } c->keepalive = 0; c->length = 0; c->gotheader=0; c->cbx = 0; c->read = c->bread = 0; write_request(c); c->start = c->connect; /* zero connect time with keep-alive */ } }
int test() { struct timeval timeout, now; fd_set sel_read, sel_except, sel_write; int i; { /* get server information */ struct hostent *he; he = gethostbyname(machine); if (!he) err("gethostbyname"); server.sin_family = he->h_addrtype; server.sin_port = htons(port); server.sin_addr.s_addr = ((unsigned long *)(he->h_addr_list[0]))[0]; } con = malloc(concurrency*sizeof(struct connection)); memset(con,0,concurrency*sizeof(struct connection)); stats = malloc(requests * sizeof(struct data)); FD_ZERO(&readbits); FD_ZERO(&writebits); /* setup request */ sprintf(request,"GET %s HTTP/1.0\r\nUser-Agent: ZeusBench/1.0\r\n" "%sHost: %s\r\nAccept: */*\r\n\r\n", file, keepalive?"Connection: Keep-Alive\r\n":"", machine ); reqlen = strlen(request); /* ok - lets start */ gettimeofday(&start,0); /* initialise lots of requests */ for(i=0; i<concurrency; i++) start_connect(&con[i]); while(done<requests) { int n; /* setup bit arrays */ memcpy(&sel_except, &readbits, sizeof(readbits)); memcpy(&sel_read, &readbits, sizeof(readbits)); memcpy(&sel_write, &writebits, sizeof(readbits)); /* check for time limit expiry */ gettimeofday(&now,0); if(tlimit && timedif(now,start) > (tlimit*1000)) { requests=done; /* so stats are correct */ output_results(); } /* Timeout of 30 seconds. */ timeout.tv_sec=30; timeout.tv_usec=0; n=select(256, &sel_read, &sel_write, &sel_except, &timeout); if(!n) { printf("\nServer timed out\n\n"); exit(1); } if(n<1) err("select"); for(i=0; i<concurrency; i++) { int s = con[i].fd; if(FD_ISSET(s, &sel_except)) { bad++; err_except++; start_connect(&con[i]); continue; } if(FD_ISSET(s, &sel_read)) read_connection(&con[i]); if(FD_ISSET(s, &sel_write)) write_request(&con[i]); } if(done>=requests) output_results(); } return 0; }
/** * Handle a request. */ static int caucho_request(request_rec *r) { config_t *config = cse_get_module_config(r); resin_host_t *host = 0; stream_t s; int retval; int keepalive = 0; int reuse; int session_index; int backup_index; char *ip; time_t now = r->request_time; char *session_id = 0; if (! config) return HTTP_SERVICE_UNAVAILABLE; if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK))) return retval; /* ap_soft_timeout("servlet request", r); */ if (r->request_config && ! *config->alt_session_url_prefix && ((session_id = ap_get_module_config(r->request_config, &caucho_module)) || r->prev && (session_id = ap_get_module_config(r->prev->request_config, &caucho_module)))) { /* *session_id = *config->session_url_prefix; */ } session_index = get_session_index(config, r, &backup_index); ip = r->connection->remote_ip; if (host) { } else if (config->manual_host) host = config->manual_host; else { host = cse_match_host(config, ap_get_server_name(r), ap_get_server_port(r), now); } if (! host || ! cse_open_connection(&s, &host->cluster, session_index, backup_index, now, r->pool)) { return HTTP_SERVICE_UNAVAILABLE; } reuse = write_request(&s, r, config, &host->cluster, &keepalive, session_index, backup_index, ip, session_id); /* ap_kill_timeout(r); */ ap_rflush(r); if (reuse == HMUX_QUIT) cse_recycle(&s, now); else cse_close(&s, "no reuse"); if (reuse == HTTP_SERVICE_UNAVAILABLE) return reuse; else return OK; }