QNetworkReply* NetworkAccessManager::createRequest(QNetworkAccessManager::Operation oparation, const QNetworkRequest &request, QIODevice * outgoingData = 0) {
  QNetworkRequest new_request(request);

  // emulate Firefox, allowing to disable certificate
  // verification using an environment variable
  if (!strcmp(getenv("IGNORECERT"), "1")) {
    QSslConfiguration config = request.sslConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1);
    QNetworkRequest new_request(request);
    new_request.setSslConfiguration(config);
  }

  QHashIterator<QString, QString> item(m_headers);
  while (item.hasNext()) {
      item.next();
      new_request.setRawHeader(item.key().toAscii(), item.value().toAscii());
  }
  QNetworkReply *reply = QNetworkAccessManager::createRequest(oparation, new_request, outgoingData);

  // not sure 100% if this is needed, but just in case
  if (!strcmp(getenv("IGNORECERT"), "1"))
    reply->ignoreSslErrors();

  return reply;
};
Exemple #2
0
QNetworkReply* NetworkAccessManager::createRequest(
    Operation op, const QNetworkRequest& request, QIODevice* outgoingData) {
  QByteArray user_agent = QString("%1 %2")
                              .arg(QCoreApplication::applicationName(),
                                   QCoreApplication::applicationVersion())
                              .toUtf8();

  if (request.hasRawHeader("User-Agent")) {
    // Append the existing user-agent set by a client library (such as
    // libmygpo-qt).
    user_agent += " " + request.rawHeader("User-Agent");
  }

  QNetworkRequest new_request(request);
  new_request.setRawHeader("User-Agent", user_agent);

  if (op == QNetworkAccessManager::PostOperation &&
      !new_request.header(QNetworkRequest::ContentTypeHeader).isValid()) {
    new_request.setHeader(QNetworkRequest::ContentTypeHeader,
                          "application/x-www-form-urlencoded");
  }

  // Prefer the cache unless the caller has changed the setting already
  if (request.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() ==
      QNetworkRequest::PreferNetwork) {
    new_request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                             QNetworkRequest::PreferCache);
  }

  return QNetworkAccessManager::createRequest(op, new_request, outgoingData);
}
Exemple #3
0
 Res call_sync(Args &&...args) {
     note_send();
     auto params = new_request();
     send_request<RPC>(params.source_id, params.request_id, std::forward<Args>(args)...);
     read_message_t reply(params.future.release());
     return serializer_t<Res>::read(&reply);
 }
Exemple #4
0
Request
open_request(Socket sc)
{
	Request retval = new_request(NULL,NULL,NULL);
	if (retval) retval->socket = sc;
	return retval;
}
Exemple #5
0
static int
message_begin_cb(http_parser *p)
{
    request *req = NULL;
    PyObject *environ = NULL;
    client_t *client = get_client(p);

    DEBUG("message_begin_cb");

    req = new_request();
    if(req == NULL){
        return -1;
    }
    req->start_msec = current_msec;
    client->current_req = req;
    environ = new_environ(client);
    client->complete = 0;
    /* client->bad_request_code = 0; */
    /* client->body_type = BODY_TYPE_NONE; */
    /* client->body_readed = 0; */
    /* client->body_length = 0; */
    req->environ = environ;
    push_request(client->request_queue, client->current_req);
    return 0;
}
Exemple #6
0
CJsonNode SNetStorageRPC::MkObjectRequest(const string& request_type,
        const string& object_loc) const
{
    CJsonNode new_request(MkStdRequest(request_type));

    new_request.SetString("ObjectLoc", object_loc);

    return new_request;
}
Exemple #7
0
void mpi_send_init_(void *buf, int* count, int* datatype, int* dst, int* tag,
                     int* comm, int* request, int* ierr) {
  MPI_Request req;

  *ierr = MPI_Send_init(buf, *count, get_datatype(*datatype), *dst, *tag,
                        get_comm(*comm), &req);
  if(*ierr == MPI_SUCCESS) {
    *request = new_request(req);
  }
}
Exemple #8
0
void mpi_irecv_(void *buf, int* count, int* datatype, int* src, int* tag,
                 int* comm, int* request, int* ierr) {
  MPI_Request req;

  *ierr = MPI_Irecv(buf, *count, get_datatype(*datatype), *src, *tag,
                    get_comm(*comm), &req);
  if(*ierr == MPI_SUCCESS) {
    *request = new_request(req);
  }
}
Exemple #9
0
void QQ::pre_sign_in_step_2()
{
	size_t req_size = 13;

	uint8_t* request = new_request(0x62, req_size);
	push_msg(request, req_size);
	delete[] request;

	set_state(QQ_WF_LOGINTOKEN);
}
Exemple #10
0
CJsonNode SNetStorageRPC::MkObjectRequest(const string& request_type,
        const string& unique_key, TNetStorageFlags flags) const
{
    CJsonNode new_request(MkStdRequest(request_type));

    CJsonNode user_key(CJsonNode::NewObjectNode());
    user_key.SetString("AppDomain", m_Config.app_domain);
    user_key.SetString("UniqueID", unique_key);
    new_request.SetByKey("UserKey", user_key);

    x_SetStorageFlags(new_request, flags);
    return new_request;
}
Exemple #11
0
std::shared_ptr<Request> Worker::getRequest(Outputable* output)
{
    auto clIdandReq = clientIdToRequest.find(output->getClientId());
    if(clIdandReq == clientIdToRequest.end())
    {
        std::shared_ptr<Request> new_request(new Request_impl(output->getOutputBuffer()));
        clientIdToRequest.insert({{output->getClientId(),new_request}});
        return new_request;
    }
    else
    {
        return (*clIdandReq).second;
    }
}
HttpRequest::Ptr HttpRequest::clone()
{
    HttpRequestPtr new_request(new HttpRequest);

    new_request->m_method = m_method;
    new_request->m_path = m_path;
    new_request->m_protocol_and_version = m_protocol_and_version;
    new_request->m_header_fields_map = m_header_fields_map;
    new_request->m_headers = m_headers;
    new_request->m_body = m_body;
    new_request->m_url = m_url;
    new_request->m_is_valid = m_is_valid;

    return new_request;
}
Exemple #13
0
QNetworkReply* NetworkAccessManager::createRequest(
    Operation op, const QNetworkRequest& request, QIODevice* outgoingData) {
  QNetworkRequest new_request(request);
  new_request.setRawHeader("User-Agent", QString("%1 %2").arg(
      QCoreApplication::applicationName(),
      QCoreApplication::applicationVersion()).toUtf8());

  // Prefer the cache unless the caller has changed the setting already
  if (request.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt()
      == QNetworkRequest::PreferNetwork) {
    new_request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                             QNetworkRequest::PreferCache);
  }

  return QNetworkAccessManager::createRequest(op, new_request, outgoingData);
}
Exemple #14
0
int main(int argc,char **argv){
	signal(SIGPIPE,SIG_IGN);
	engine *e = engine_new();
	sockaddr_ server;
	if(0 != easy_sockaddr_ip4(&server,argv[1],atoi(argv[2]))){
		printf("invaild address:%s\n",argv[1]);
	}
	int32_t fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	easy_addr_reuse(fd,1);
	if(0 == easy_bind(fd,&server)){
		dgram_socket_ *udpserver = new_datagram_socket(fd); 
		engine_associate(e,udpserver,datagram_callback);
		datagram_socket_recv(udpserver,(iorequest*)new_request(),IO_POST,NULL);
		engine_regtimer(e,1000,timer_callback,NULL);
		engine_run(e);
	}
	return 0;
}
Exemple #15
0
static client_t *
new_client_t(int client_fd, struct sockaddr_in client_addr){
  client_t *client;
    
  client = ruby_xmalloc(sizeof(client_t));
  memset(client, 0, sizeof(client_t));
    
  /* printf("size %d\n", sizeof(client_t)); */

  client->fd = client_fd;
    
  client->remote_addr = inet_ntoa(client_addr.sin_addr);
  client->remote_port = ntohs(client_addr.sin_port);
  client->req = new_request();
  client->body_type = BODY_TYPE_NONE;
  //printf("input_buf_size %d\n", client->input_buf_size);
  return client;
}
QNetworkReply* NetworkAccessManager::createRequest(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice * outgoingData = 0) {
  QNetworkRequest new_request(request);
  QByteArray url = new_request.url().toEncoded();
  if (this->isBlacklisted(new_request.url())) {
    return new NetworkReplyProxy(new NoOpReply(new_request), this);
  } else {
    if (operation != QNetworkAccessManager::PostOperation && operation != QNetworkAccessManager::PutOperation) {
      new_request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant());
    }
    QHashIterator<QString, QString> item(m_headers);
    while (item.hasNext()) {
        item.next();
        new_request.setRawHeader(item.key().toLatin1(), item.value().toLatin1());
    }
    QNetworkReply *reply = new NetworkReplyProxy(QNetworkAccessManager::createRequest(operation, new_request, outgoingData), this);
    emit requestCreated(url, reply);
    return reply;
  }
};
Exemple #17
0
/*
 * Non blocking communication function. The message is sent when possible. To check for the status of the message,
 * the mpi_wait and mpi_test should be used. Until mpi_wait is called, the memory allocated for the buffer containing 
 * the message is not released.
 *
 * mpi_isend(+Data, +Destination, +Tag, -Handle).
 */
static YAP_Bool 
mpi_isend(term_t YAP_ARG1,...) {
  YAP_Term t1 = YAP_Deref(YAP_ARG1), 
    t2 = YAP_Deref(YAP_ARG2), 
    t3 = YAP_Deref(YAP_ARG3), 
    t4 = YAP_Deref(YAP_ARG4);
  char *str=NULL;
  int dest,tag;
  size_t len=0;
  MPI_Request *handle=(MPI_Request*)malloc(sizeof(MPI_Request));

  CONT_TIMER();
  if ( handle==NULL ) return  false;

  if (YAP_IsVarTerm(t1) || !YAP_IsIntTerm(t2) || !YAP_IsIntTerm(t3) || !YAP_IsVarTerm(t4)) {
    PAUSE_TIMER();
    return false;
  }
  //
  dest = YAP_IntOfTerm(t2);
  tag  = YAP_IntOfTerm(t3);
  // 
  str=term2string(NULL,&len,t1);
  MSG_SENT(len);
  // send the data 
  if( MPI_CALL(MPI_Isend( str, len, MPI_CHAR, dest, tag, MPI_COMM_WORLD ,handle)) != MPI_SUCCESS ) {
    PAUSE_TIMER();
    return false;
  }

#ifdef DEBUG
  write_msg(__FUNCTION__,__FILE__,__LINE__,"%s(%s,%u, MPI_CHAR,%d,%d)\n",__FUNCTION__,str,len,dest,tag);
#endif
  USED_BUFFER(); //  informs the prologterm2c module that the buffer is now used and should not be messed
  // We must associate the string to each handle
  new_request(handle,str);
  PAUSE_TIMER();
  return(YAP_Unify(YAP_ARG4,YAP_MkIntTerm(HANDLE2INT(handle))));// it should always succeed
}
Exemple #18
0
/*
 * Implements a non-blocking receive operation. 
 * mpi_irecv(?Source,?Tag,-Handle).
 */
static YAP_Bool 
mpi_irecv(term_t YAP_ARG1,...) {
  YAP_Term t1 = YAP_Deref(YAP_ARG1), 
    t2 = YAP_Deref(YAP_ARG2), 
    t3 = YAP_Deref(YAP_ARG3);
  int tag, orig;
 MPI_Request *mpi_req=(MPI_Request*)malloc(sizeof(MPI_Request));

   // The third argument (data) must be unbound
  if(!YAP_IsVarTerm(t3)) {
    //Yap_Error(INSTANTIATION_ERROR, t_data, "mpi_receive");
    return false;
  }
  /* The first argument (Source) must be bound to an integer
     (the rank of the source) or left unbound (i.e. any source
     is OK) */
  if (YAP_IsVarTerm(t1)) orig = MPI_ANY_SOURCE;
  else if( !YAP_IsIntTerm(t1) ) return  false;
  else orig = YAP_IntOfTerm(t1);
  
  /* The third argument must be bound to an integer (the tag)
     or left unbound (i.e. any tag is OK) */
  if (YAP_IsVarTerm(t2)) tag = MPI_ANY_TAG;
  else if( !YAP_IsIntTerm(t2) ) return  false;
  else  tag  = YAP_IntOfTerm( t2 );

  CONT_TIMER();
  RESET_BUFFER();
  if(  MPI_CALL(MPI_Irecv( BUFFER_PTR, BLOCK_SIZE, MPI_CHAR, orig, tag,
			   MPI_COMM_WORLD, mpi_req )) != MPI_SUCCESS ) {
    PAUSE_TIMER();
    return false;
  }
  new_request(mpi_req,BUFFER_PTR);
  DEL_BUFFER();
  PAUSE_TIMER();
  return YAP_Unify(t3,YAP_MkIntTerm(HANDLE2INT(mpi_req)));
}
Exemple #19
0
CJsonNode SNetStorageRPC::MkStdRequest(const string& request_type) const
{
    CJsonNode new_request(CJsonNode::NewObjectNode());

    new_request.SetString("Type", request_type);
    new_request.SetInteger("SN", (Int8) m_RequestNumber.Add(1));

    CRequestContext& req = CDiagContext::GetRequestContext();

    if (req.IsSetClientIP()) {
        new_request.SetString("ClientIP", req.GetClientIP());
    }

    if (req.IsSetSessionID()) {
        new_request.SetString("SessionID", req.GetSessionID());
    }

    // TODO:
    // Remove sending this after all NetStorage servers are updated to v2.2.0
    // (ncbi_phid is sent inside ncbi_context).
    // GetNextSubHitID()/GetCurrentSubHitID()) must be still called though
    // (without using returned value) to set appropriate value for ncbi_phid.
    if (req.IsSetHitID()) {
        new_request.SetString("ncbi_phid", m_UseNextSubHitID ?
                req.GetNextSubHitID() : req.GetCurrentSubHitID());
    }

    const auto format = CRequestContext_PassThrough::eFormat_UrlEncoded;
    const CRequestContext_PassThrough context;
    const string ncbi_context(context.Serialize(format));

    if (!ncbi_context.empty()) {
        new_request.SetString("ncbi_context", ncbi_context);
    }

    return new_request;
}
Exemple #20
0
void notification_receive(Message *m, char *pattern)
{
    Message message;
    int ret;
    
    if (strstr(pattern,"REDIRECT_LOOKUP"))
    {
        char *funcname=m->data[0];
        char *libname=m->data[1];
        
        if (0 == strcmp(funcname,"strrchr") && 
            0 == strcmp(libname,"main"))
        {
            ret=new_request(rtr, &message, myhandle, SUCCESS, SYNC_MODE,
                            patternid[0], del_message_func);
            message.data_entries=4;
            message.data[0]="strrchr";
            message.data[1]="main";
            message.data[2]="_jt_jumptable";
            message.data[3]="libstringtable.so";
            //ret=send_message(rtr, &message);
        }
    }
}
/** @brief Parse and response to request from a client
 *
 *  @return 0 if the connection should be kept alive. -1 if the connection
 *          should be closed.
 */
int http_parse(http_client_t *client) {
    int ret, i;
    char line[MAXBUF];
    char* buf;

    if (client->status == C_IDLE) {  /* A new request, parse request line */
        ret = client_readline(client, line);
        if (strlen(line) == 0) return 0;

        log_msg(L_HTTP_DEBUG, "%s\n", line);

        if (ret == 0) return 0;

        /* The length of a line exceed MAXBUF */
        if (ret < 0) {
            log_error("A line in request is too long");
            return end_request(client, BAD_REQUEST);
        }

        if (client->req != NULL) free(client->req);
        client->req = new_request();

        /* parse request line and store information in client->req */
        if ((ret = parse_request_line(client->req, line)) > 0)
            return end_request(client, ret);

        /* Now start parsing header */
        client->status = C_PHEADER;
    }

    /*
     *  Read request headers. When finish reading request headers of a POST
     *  request without error, client->req->content_length will be set
     *  correspondingly. Thus client->req->content_length == -1 means the
     *  request header section has not ended.
     */
    while (client->status == C_PHEADER && client_readline(client, line) > 0) {
        log_msg(L_HTTP_DEBUG, "%s\n", line);

        if (strlen(line) == 0) {    //Request header ends

            if (client->req->method == M_POST) {
                buf = get_request_header(client->req, "Content-Length");
                if (buf == NULL)
                    return end_request(client, LENGTH_REQUIRED);
                //validate content-length
                if (strlen(buf) == 0) return BAD_REQUEST;
                for (i = 0; i < strlen(buf); ++i)
                    if (buf[i] < '0' || buf[i] >'9') //each char in range ['0', '9']
                        return end_request(client, BAD_REQUEST);

                client->req->content_length = atoi(buf);

                /* Now start receiving body */
                client->status = C_PBODY;
                break;
            }

            if (client->req->method == M_GET) ret = handle_get(client);
            if (client->req->method == M_HEAD) ret = handle_head(client);
            if (ret != 0)
                return end_request(client, ret);
            else {
                /* The client signal a "Connection: Close" */
                if (connection_close(client->req))
                    client->alive = 0;

                return ret;
            }
        }
        ret = parse_header(client->req, line);
        if (ret == -1) {
            log_msg(L_ERROR, "Bad request header format: %s\n", line);
            return end_request(client, BAD_REQUEST);
        }
    }

    /*
     * We've finished reading and parsing request header. Now, see if the body
     * of the request is ready. If so, copy data
     */
    if (client->status == C_PBODY) {
        // Reveive complete body?
        if (client->in->datasize - client->in->pos >= client->req->content_length) {
            /* Let body points to corresponding memory in the input buffer */
            client->req->body = client->in->buf + client->in->pos;
            client->in->pos += client->req->content_length;
            ret = handle_post(client);

            if (ret != 0)
                return end_request(client, ret);
            else {
                /* The client signal a "Connection: Close" */
                if (connection_close(client->req))
                    client->alive = 0;

                return ret;
            }
        }

        /* Body not ready, next time then */
        return 0;
    }

    return 0;
}
Exemple #22
0
request *get_sock_request(int sock_fd)
{
	int fd;						/* socket */
#ifdef INET6
	struct sockaddr_in6 remote_addr;
#else
	struct sockaddr_in remote_addr;		/* address */
#endif
	int remote_addrlen = sizeof(remote_addr);
	request *conn;				/* connection */

	if (max_connections != -1 && status.connections >= max_connections)
		return NULL;

#ifdef INET6
	remote_addr.sin6_family = 0xdead;
#else
  remote_addr.sin_family = 0xdead;
#endif
	fd = accept(sock_fd, (struct sockaddr *) &remote_addr, &remote_addrlen);

	if (fd == -1) {
		if (errno == EAGAIN || errno == EWOULDBLOCK)	/* no requests */
			return NULL;
		else {					/* accept error */
			log_error_time();
#if 0
			perror("accept");
#endif
			return NULL;
		}
	}
#ifdef DEBUGNONINET
	/*  This shows up due to race conditions in some Linux kernels 
	 *  when the client closes the socket sometime between 
	 *  the select() and accept() syscalls.
	 *  Code and description by Larry Doolittle <*****@*****.**>
	 */
#define HEX(x) (((x)>9)?(('a'-10)+(x)):('0'+(x)))
	if (remote_addr.sin_family != AF_INET) {
		struct sockaddr *bogus = (struct sockaddr *) &remote_addr;
		char *ap, ablock[44];
		int i;
		close(fd);
#ifdef BOA_TIME_LOG
		log_error_time();
#endif
		for (ap = ablock, i = 0; i < remote_addrlen && i < 14; i++) {
			*ap++ = ' ';
			*ap++ = HEX((bogus->sa_data[i] >> 4) & 0x0f);
			*ap++ = HEX(bogus->sa_data[i] & 0x0f);
		}
		*ap = '\0';
#ifdef BOA_TIME_LOG
		fprintf(stderr, "non-INET connection attempt: socket %d, "
				"sa_family = %hu, sa_data[%d] = %s\n",
				fd, bogus->sa_family, remote_addrlen, ablock);
#endif
		return NULL;
	}
#endif

	if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *) &sock_opt,
		sizeof(sock_opt))) == -1){
			die(NO_SETSOCKOPT);
			return NULL;
	}

	conn = new_request();
	conn->fd = fd;
	conn->status = READ_HEADER;
	conn->header_line = conn->client_stream;
	conn->time_last = time_counter;
#ifdef USE_CHARSET_HEADER
	conn->send_charset = 1;
#endif

	/* nonblocking socket */
	if (fcntl(conn->fd, F_SETFL, NOBLOCK) == -1) {
#ifdef BOA_TIME_LOG
		log_error_time();
		perror("request.c, fcntl");
#endif
	}
	/* set close on exec to true */
	if (fcntl(conn->fd, F_SETFD, 1) == -1) {
#ifdef BOA_TIME_LOG
		log_error_time();
		perror("request.c, fcntl-close-on-exec");
#endif
	}

	/* large buffers */
	if (setsockopt(conn->fd, SOL_SOCKET, SO_SNDBUF, (void *) &sockbufsize,
				   sizeof(sockbufsize)) == -1)
		die(NO_SETSOCKOPT);

	/* for log file and possible use by CGI programs */
#ifdef INET6
	if (getnameinfo((struct sockaddr *)&remote_addr, 
									NRL_SA_LEN((struct sockaddr *)&remote_addr), 
									conn->remote_ip_addr, 20,
								 	NULL, 0, NI_NUMERICHOST)) {
#if 0
			fprintf(stderr, "[IPv6] getnameinfo failed\n");
#endif
			conn->remote_ip_addr[0]=0;
		}
#else
	strncpy(conn->remote_ip_addr, (char *) inet_ntoa(remote_addr.sin_addr), 20);
#endif

	/* for possible use by CGI programs */
#ifdef INET6
	conn->remote_port = ntohs(remote_addr.sin6_port);
#else
	conn->remote_port = ntohs(remote_addr.sin_port);
#endif

	if (virtualhost) {
#ifdef INET6
		char host[20];
		struct sockaddr_in6 salocal;
		int dummy;
				
		dummy = sizeof(salocal);
		if (getsockname(conn->fd, (struct sockaddr *) &salocal, &dummy) == -1)
									      die(SERVER_ERROR);
			if (getnameinfo((struct sockaddr *)&salocal,
		              NRL_SA_LEN((struct sockaddr *)&salocal),
			          host, 20,
				      NULL, 0, NI_NUMERICHOST)) {
#if 0
				fprintf(stderr, "[IPv6] getnameinfo failed\n");
#endif
			}else
				conn->local_ip_addr = strdup(host);
#else		
		struct sockaddr_in salocal;
		int dummy;

		dummy = sizeof(salocal);
		if (getsockname(conn->fd, (struct sockaddr *) &salocal, &dummy) == -1){
			die(SERVER_ERROR);
			return NULL;
		}
		conn->local_ip_addr = strdup(inet_ntoa(salocal.sin_addr));
#endif
	}	
	status.requests++;
	status.connections++;

	/* Thanks to Jef Poskanzer <*****@*****.**> for this tweak */
	{
		int one = 1;
		if (setsockopt(conn->fd, IPPROTO_TCP, TCP_NODELAY, (void *) &one,
			sizeof(one)) == -1){
			die(NO_SETSOCKOPT);
			return NULL;
		}
	}
	enqueue(&request_ready, conn);
	return conn;
}
Exemple #23
0
void free_request(request ** list_head_addr, request * req)
{
	if (req->buffer_end)
		return;

	dequeue(list_head_addr, req);	/* dequeue from ready or block list */

	if (req->buffer_end)
		FD_CLR(req->fd, &block_write_fdset);
	else {
		switch (req->status) {
		case PIPE_WRITE:
		case WRITE:
			FD_CLR(req->fd, &block_write_fdset);
			break;
		case PIPE_READ:
			FD_CLR(req->data_fd, &block_read_fdset);
			break;
		case BODY_WRITE:
			FD_CLR(req->post_data_fd, &block_write_fdset);
			break;
		default:
			FD_CLR(req->fd, &block_read_fdset);
		}
	}

	if (req->logline)			/* access log */
		log_access(req);

	if (req->data_mem)
		munmap(req->data_mem, req->filesize);
	
	if (req->data_fd)
		close(req->data_fd);
	
	if (req->response_status >= 400)
		status.errors++;

	if ((req->keepalive == KA_ACTIVE) &&
		(req->response_status < 400) &&
		(++req->kacount < ka_max)) {

		request *conn;

		conn = new_request();
		conn->fd = req->fd;
		conn->status = READ_HEADER;
		conn->header_line = conn->client_stream;
		conn->time_last = time_counter;
		conn->kacount = req->kacount;
#ifdef SERVER_SSL
		conn->ssl = req->ssl; /*MN*/
#endif /*SERVER_SSL*/
		
		/* we don't need to reset the fd parms for conn->fd because
		   we already did that for req */
		/* for log file and possible use by CGI programs */
		
		strcpy(conn->remote_ip_addr, req->remote_ip_addr);

		/* for possible use by CGI programs */
		conn->remote_port = req->remote_port;
		
		if (req->local_ip_addr)
			conn->local_ip_addr = strdup(req->local_ip_addr);

		status.requests++;
		
		if (conn->kacount + 1 == ka_max)
			SQUASH_KA(conn);
				
		conn->pipeline_start = req->client_stream_pos - 
								req->pipeline_start;
		
		if (conn->pipeline_start) {
			memcpy(conn->client_stream,
				req->client_stream + req->pipeline_start,
				conn->pipeline_start);			
			enqueue(&request_ready, conn);				
		} else
			block_request(conn);
	} else{
		if (req->fd != -1) {
			status.connections--;
			safe_close(req->fd);
		}
		req->fd = -1;
#ifdef SERVER_SSL
		SSL_free(req->ssl);
#endif /*SERVER_SSL*/
	}

	if (req->cgi_env) {
		int i = COMMON_CGI_VARS;
		req->cgi_env[req->cgi_env_index]=0;
		while (req->cgi_env[i])
		{
			free(req->cgi_env[i++]);
		}
		free(req->cgi_env);
	}
	if (req->pathname)
		free(req->pathname);
	if (req->path_info)
		free(req->path_info);
	if (req->path_translated)
		free(req->path_translated);
	if (req->script_name)
		free(req->script_name);
	if (req->query_string)
		free(req->query_string);
	if (req->local_ip_addr)
		free(req->local_ip_addr);
/*
 *	need to clean up if anything went wrong
 */
	if (req->post_file_name) {
		unlink(req->post_file_name);
		free(req->post_file_name);
		close(req->post_data_fd);
		req->post_data_fd = -1;
		req->post_file_name = NULL;
	}

	enqueue(&request_free, req);	/* put request on the free list */

	return;
}
Exemple #24
0
 future_t<Res> call_async(Args &&...args) {
     note_send();
     auto params = new_request();
     send_request<RPC>(params.source_id, params.request_id, std::forward<Args>(args)...);
     return params.future.then_release(&target_t::parse_result<Res>);
 }
Exemple #25
0
void
on_new_mi_activate (GtkMenuItem * menuitem, gpointer user_data)
{
  new_request();
}
Exemple #26
0
void notification_socket_cb(int fd, short event, void *arg)
{
	(void)fd; /* unused */
	(void)event; /* unused */
	const async_http_worker_t *worker = (async_http_worker_t *) arg;

	int received;
	int i, len;
	async_query_t *aq;

	http_m_params_t query_params;

	str query;

	if ((received = recvfrom(worker->notication_socket[0],
			&aq, sizeof(async_query_t*),
			0, NULL, 0)) < 0) {
		LM_ERR("failed to read from socket (%d: %s)\n", errno, strerror(errno));
		return;
	}

	if(received != sizeof(async_query_t*)) {
		LM_ERR("invalid query size %d\n", received);
		return;
	}

	query = ((str)aq->query);

	query_params.timeout = aq->query_params.timeout;
	query_params.tls_verify_peer = aq->query_params.tls_verify_peer;
	query_params.tls_verify_host = aq->query_params.tls_verify_host;
	query_params.authmethod = aq->query_params.authmethod;

	query_params.headers = NULL;
	for (i = 0 ; i < aq->query_params.headers.len ; i++) {
		query_params.headers = curl_slist_append(query_params.headers, aq->query_params.headers.t[i]);
	}
	query_params.method  = aq->query_params.method;

	query_params.tls_client_cert.s = NULL;
	query_params.tls_client_cert.len = 0;
	if (aq->query_params.tls_client_cert.s && aq->query_params.tls_client_cert.len > 0) {
		if (shm_str_dup(&query_params.tls_client_cert, &(aq->query_params.tls_client_cert)) < 0) {
			LM_ERR("Error allocating query_params.tls_client_cert\n");
			goto done;
		}
	}

	query_params.tls_client_key.s = NULL;
	query_params.tls_client_key.len = 0;
	if (aq->query_params.tls_client_key.s && aq->query_params.tls_client_key.len > 0) {
		if (shm_str_dup(&query_params.tls_client_key, &(aq->query_params.tls_client_key)) < 0) {
			LM_ERR("Error allocating query_params.tls_client_key\n");
			goto done;
		}
	}

	query_params.tls_ca_path.s = NULL;
	query_params.tls_ca_path.len = 0;
	if (aq->query_params.tls_ca_path.s && aq->query_params.tls_ca_path.len > 0) {
		if (shm_str_dup(&query_params.tls_ca_path, &(aq->query_params.tls_ca_path)) < 0) {
			LM_ERR("Error allocating query_params.tls_ca_path\n");
			goto done;
		}
	}

	query_params.body.s = NULL;
	query_params.body.len = 0;
	if (aq->query_params.body.s && aq->query_params.body.len > 0) {
		if (shm_str_dup(&query_params.body, &(aq->query_params.body)) < 0) {
			LM_ERR("Error allocating query_params.body\n");
			goto done;
		}
	}
  
	query_params.username = NULL;
	if (aq->query_params.username) {
		len = strlen(aq->query_params.username);
		query_params.username = shm_malloc(len+1);
	
		if(query_params.username == NULL) {
			LM_ERR("error in shm_malloc\n");
			goto done;
		}

		strncpy(query_params.username, aq->query_params.username, len);
		query_params.username[len] = '\0';
	}
	
	query_params.password = NULL;
	if (aq->query_params.password) {
		len = strlen(aq->query_params.password);
		query_params.password = shm_malloc(len+1);
	
		if(query_params.password == NULL) {
			LM_ERR("error in shm_malloc\n");
			goto done;
		}

		strncpy(query_params.password, aq->query_params.password, len);
		query_params.password[len] = '\0';
	}

	LM_DBG("query received: [%.*s] (%p)\n", query.len, query.s, aq);

	if (new_request(&query, &query_params, async_http_cb, aq) < 0) {
		LM_ERR("Cannot create request for %.*s\n", query.len, query.s);
		free_async_query(aq);
	}

done:
	if (query_params.tls_client_cert.s && query_params.tls_client_cert.len > 0) {
		shm_free(query_params.tls_client_cert.s);
		query_params.tls_client_cert.s = NULL;
		query_params.tls_client_cert.len = 0;
	}
	if (query_params.tls_client_key.s && query_params.tls_client_key.len > 0) {
		shm_free(query_params.tls_client_key.s);
		query_params.tls_client_key.s = NULL;
		query_params.tls_client_key.len = 0;
	}
	if (query_params.tls_ca_path.s && query_params.tls_ca_path.len > 0) {
		shm_free(query_params.tls_ca_path.s);
		query_params.tls_ca_path.s = NULL;
		query_params.tls_ca_path.len = 0;
	}
	if (query_params.body.s && query_params.body.len > 0) {
		shm_free(query_params.body.s);
		query_params.body.s = NULL;
		query_params.body.len = 0;
	}

	if (query_params.username) {
		shm_free(query_params.username);
		query_params.username = NULL;
	}
	
	if (query_params.password) {
		shm_free(query_params.password);
		query_params.password = NULL;
	}

	return;
}
Exemple #27
0
void QQ::dispatch_msg()
{	
	uint8_t msg[messenger::BUF_SIZE] = {0};

	int len = 0;
	int i = 0;
	size_t j = 0;

	bool match = false;
	char msg_info[128] = {0};
	uint8_t* compare = NULL;
	size_t count = 0;

	qq_state_enum state = get_state();

	if (msgr == NULL || msgr->get_incoming_msg_queue_size() == 0)
	{
		return;
	}

	pthread_mutex_lock(&srv_ip_mtx);

	switch (state)
	{
	case QQ_WF_PREFIRST:
	case QQ_WF_REDIRECT:
		if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
		{		
			break;
		}
		
		if (len < 10)
		{
			break;
		}

		// count = hex_string_to_bytes("02030000310004010003" , &compare);
		count = hex_string_to_bytes("02000000310004010003" , &compare); //2009-08-06		
		
		if (memcmp((char*)msg, compare, count) == 0)
		{
			delay(200);
			set_state(QQ_LOGINTOKEN);
		}

		delete[] compare;
		break;		

	case QQ_WF_LOGINTOKEN:
		if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
		{		
			cout << "Read NONE!" << endl;
			break;
		}

		if (len >= 34)
		{
			// 请求登录令牌的命令号 0x0062
			count = hex_string_to_bytes("020e35006200000018", &compare); 
			match = true;

			for (j = 0; j < count; j++)
			{
				if (j == 5 || j == 6)
					continue;
				if (msg[j] != compare[j])
				{
					match = false;
					break;
				}
			}

			delete[] compare;
		}
		if (match)
		{
			pthread_mutex_lock(&login_token_mtx);
			for (j = 0; j < 24; j++)
				login_token[j] = msg[j + 9];	
			pthread_mutex_unlock(&login_token_mtx);
			delay(200);
			set_state(QQ_LOGIN_IN);
		}
		break;

	case QQ_WF_LOGIN_IN:
		{
			if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
			{		
				break;
			}
			
			if (len < 32)
			{
				printf("QQ_WF_LOGIN_IN: len == %d < 32, break.\n", len);
				break;
			}
			count = hex_string_to_bytes("020e350022", &compare);

			if (memcmp((char*)msg, compare, count) != 0)
			{
				delete[] compare; 
				break;
			}
			delete[] compare; 			

			if (len == 32)
			{
				delay(200);
				set_state(QQ_REDIRECT);
				//cout << "QQ_REDIRECT" << endl;
				pthread_mutex_lock(&rand_key_mtx);
				TEA tea(rand_key);
				pthread_mutex_unlock(&rand_key_mtx);

				unsigned char * plain_msg = NULL;
				if (tea.qq_decrypt((msg + 7), 24, &plain_msg) != 11)
				{
					cout << "Decrypt Failed!" << endl;
					delay(200);
					set_state(QQ_ZERO);
					break;
				}
				unsigned int   n_ip = *((unsigned int *) (plain_msg + 5));
				unsigned short n_port = *((unsigned short *) (plain_msg + 9));
				unsigned short h_port = ntohs(n_port);
				unsigned int h_ip = ntohl(n_ip);

				memset(srv_ip, 0, IPADDR_LEN);
				sprintf(srv_ip, "%d.%d.%d.%d", 
					(h_ip >> 24) % 0x100,
					(h_ip >> 16) % 0x100, 
					(h_ip >> 8) % 0x100,
					h_ip % 0x100);

				srv_port = h_port;
				delete[] plain_msg;
				break;
			}

			if (len == 88)
			{
				printf("QQ_WF_LOGIN_IN: recieved 88 bytes.\n");	
			}

			if (len != 192)
			{
				printf("QQ_WF_LOGIN_IN: len == %d != 192, login failed, try again.\n", len);
				set_state(QQ_ZERO);
				break;
			}

			uint8_t * pwhash2 = NULL;
			hex_string_to_bytes(qq_pw, &pwhash2);		

			TEA tea(pwhash2);
			uint8_t * plain_msg = NULL;

			try
			{
				tea.qq_decrypt((msg + 7), 184, &plain_msg);
			}
			catch (out_of_range e)
			{
				cout << e.what() << endl;
			}

			uint32_t my_qq_id = 0;
			uint32_t my_ip = 0;
			uint16_t my_port = 0;
			uint32_t srv_listen_ip = 0;
			uint16_t srv_listen_port = 0;
			time_t login_time = 0;
			struct tm* tm_ptr;
			uint32_t unknown_ip = 0;

			switch (plain_msg[0])
			{
			case 0x00:
				memcpy(session_key, plain_msg + 1, 16);				
				delay(200);
				set_state(QQ_PRE_ONLINE_FIR);

				my_qq_id = ntohl(*((uint32_t *) (plain_msg + 17)));
				my_ip = ntohl(*((uint32_t *) (plain_msg + 21)));
				my_port = ntohs(*((uint16_t *) (plain_msg + 25)));
				srv_listen_ip = ntohl(*((uint32_t *) (plain_msg + 27)));
				srv_listen_port = ntohs(*((uint16_t *) (plain_msg + 31)));
				login_time = (time_t)
					ntohl(*((uint32_t *) (plain_msg + 33)));
				unknown_ip = ntohl(*((uint32_t *) (plain_msg + 63)));

				tm_ptr = localtime(&login_time);					

				sprintf(client_ip_port, "%d.%d.%d.%d:%d",
					(my_ip >> 24) % 0x100, (my_ip >> 16) % 0x100,
					(my_ip >> 8) % 0x100, my_ip % 0x100, my_port);		

				sprintf(signin_time, "%02d:%02d:%02d", tm_ptr->tm_hour,
					tm_ptr->tm_min, tm_ptr->tm_sec);

				sprintf(msg_info, "QQ ID:\t%d\r\nIP Addr:\t%s\r\nTime:\t\t%s",
					my_qq_id, client_ip_port, signin_time);
				log_event(msg_info);

				break;

			default:
				delay(200);
				set_state(QQ_ZERO);
				break;
			}

			delete[] plain_msg;	
			delete[] pwhash2;

			break;
		}

	case QQ_WF_PRE_ONLINE_FIR:
		{
			if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
			{		
				break;
			}

			cout << "Server IP:\t" << srv_ip << ":" << srv_port << endl;

			if (msg[0] == 0x02 &&
				msg[1] == 0x0e &&
				msg[2] == 0x35)
			{
				TEA tea(session_key);
				unsigned char * plain_msg = NULL;
				tea.qq_decrypt((msg + 7), len - 8, &plain_msg);
				unsigned short order = msg[3] * 0x100 + msg[4];

				switch (order)
				{
				case 0x6:
					{
						my_profile_gotten = true;
						set_state(QQ_PRE_ONLINE_SEC);
						break;
					}
				}

				delete[] plain_msg;
			}

			break;
		}

	case QQ_WF_PRE_ONLINE_SEC:
		{
			if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
			{		
				break;
			}

			if (msg[0] == 0x02 &&
				msg[1] == 0x0e &&
				msg[2] == 0x35)
			{
				TEA tea(session_key);
				unsigned char * plain_msg = NULL;
				int msg_len = tea.qq_decrypt((msg + 7), len - 8,
					&plain_msg);
				unsigned short order = msg[3] * 0x100 + msg[4];

				switch (order)
				{
				case 0x26:
					{
						memcpy(friend_id, plain_msg, 2);

						if (plain_msg[0] * 0x100 + plain_msg[1] == 0xffff)
						{
							set_state(QQ_ONLINE);							
							delay(200);
						}
						else
						{
							delay(200);
							set_state(QQ_PRE_ONLINE_SEC);
						}

						i = 2;

						while (i < msg_len)
						{
							int* pint = (int*) (plain_msg + i);
							int buddy_id = ntohl(*pint);
							unsigned char ssize = *(plain_msg + i + 8);
							char* nickname = new char[ssize + 1];
							memset(nickname, 0, ssize + 1);
							memcpy(nickname, plain_msg + i + 9, ssize);
							char ss[20];
							sprintf(ss, "<%d>", buddy_id);
							char* listchars = new char[ssize + 1 + 20];
							strcpy(listchars, nickname);
							strcat(listchars, ss);

							string buddy_nickname = nickname;
							contact.insert(pair<int, string>(buddy_id,
								buddy_nickname));

							delete[] nickname;
							delete[] listchars;
							i = i + 9 + ssize + 4;
						}

						break;
					}
				}

				delete[] plain_msg;
			}

			break;
		}

	case QQ_ONLINE:
		{
			if (msgr->read_msg_queue(msgr->INCOMING, (char*)msg, this->srv_ip, this->srv_port, len) <= 0)
			{		
				break;
			}
			if (msg[0] == 0x02)
			{
				TEA tea(session_key);
				unsigned char * plain_msg = NULL;
				int msg_len = tea.qq_decrypt((msg + 7), len - 8,
					&plain_msg);

				unsigned short order = msg[3] * 0x100 + msg[4];
				char signature[128];

				switch (order)
				{
				case 0x02:
					pthread_mutex_lock(&drop_flag_mtx);
					drop_flag = 0;
					pthread_mutex_unlock(&drop_flag_mtx);
					break;
	
				case 0x17:
					{
						int sender_qq = ntohl(*((int*) plain_msg));      //发送者QQ号	
						int mlong = msg_len - 65 - plain_msg[msg_len - 1];

						if (mlong > 0)
						{
							char* received_msg = new char[mlong + 1];
							memset(received_msg, 0, mlong + 1);
							memcpy(received_msg, plain_msg + 65, mlong);

							if (config.set_received_msg_as_personal_msg)
							{
								strncpy((char *) signature, received_msg, 100);
								set_personal_msg((const char *) signature);
							}

							process_msg(sender_qq, received_msg);

							delete[] received_msg;
							/*
							 * 回复 收到了消息
							 * 1. 消息发送者QQ号,4字节
							 * 2. 消息接收者QQ号,4字节,也就是我
							 * 3. 消息序号,4字节
							 * 4. 发送者IP,4字节
							 */
							unsigned char * plaintext = new unsigned char[16];
							memcpy(plaintext, plain_msg, 16);
							unsigned char * ciphertext = NULL;
			
							size_t miSize = tea.qq_encrypt(plaintext, 16,
								&ciphertext);

							size_t msg_size = miSize + 12;

							uint8_t* request = new_request(0x17, msg_size);

							request[5] = msg[5]; // TEA::Rand();
							request[6] = msg[6]; // TEA::Rand();
							memcpy(request + 11, ciphertext, miSize);

							push_msg(request, msg_size, false);
				
							delete[] plaintext;
							delete[] ciphertext;
							delete[] request;
						}
						break;
					}
				}
				delete [] plain_msg;
			}

			break;
		}

	default:
		break;
	}
Exemple #28
0
void
on_new_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
  new_request();
}
Exemple #29
0
static void do_meta_request(kdev_t device)
{
    struct ud_driver *driver = get_driver(major);
    struct ud_request *udr;
    struct request *req;
    char *buff;
    int major = MAJOR(device);

    printk("do_meta_request %d %x\n", major, blk_dev[major].current_request);
    if (NULL == driver) {
        end_request(0, req->rq_dev);
        return;
    }
    printk("1");
    while (1) {
        req = blk_dev[major].current_request;
        printk("2");
        if (!req || req->rq_dev < 0 || req->rq_sector == -1)
            return;
        printk("5");
        udr = new_request();
        udr->udr_type = UDR_BLK + req->rq_cmd;
        udr->udr_ptr = req->rq_sector;
        udr->udr_minor = MINOR(req->rq_dev);
        printk("6");
        post_request(driver, udr);
        printk("7");

        /* Should really check here whether we have a request */
        if (req->rq_cmd == WRITE) {
            /* Can't do this, copies to the wrong task */
#if 0
            verified_memcpy_tofs(driver->udd_data, buff, BLOCK_SIZE);
            /* FIXME FIXME	*/
            fmemcpy(driver->udd_task->mm.dseg, driver->udd_data, get_ds(),
                    buff, 1024);
#endif
        }
        printk("8");

        /* Wake up the driver so it can deal with the request */
        wake_up(&driver->udd_wait);
        printk("request init: wake driver, sleeping\n");
        sleep_on(&udr->udr_wait);
        printk("request continue\n");

        /* REQUEST HAS BEEN RETURNED BY USER PROGRAM */
        /* request must be dealt with and ended */
        if (udr->udr_status == 1) {
            end_request(0, req->rq_dev);
            udr->udr_status = 0;
            continue;
        }
        udr->udr_status = 0;
        buff = req->rq_buffer;
        if (req->rq_cmd == READ) {
            /* Can't do this, copies from the wrong task */
#if 0
            verified_memcpy_fromfs(buff, driver->udd_data, BLOCK_SIZE);
            /* FIXME FIXME */
            fmemcpy(get_ds(), buff, driver->udd_task->mm.dseg,
                    driver->udd_data, 1024);
#endif
        }
        end_request(1, req->rq_dev);
        wake_up(&udr->udr_wait);
    }
}
Exemple #30
0
void get_request(int server_sock)
{
    int fd;                     /* socket */
    struct SOCKADDR remote_addr; /* address */
    struct SOCKADDR salocal;
    unsigned int remote_addrlen = sizeof (struct SOCKADDR);
    request *conn;              /* connection */
    size_t len;

#ifndef INET6
    remote_addr.S_FAMILY = (sa_family_t) 0xdead;
#endif
    fd = accept(server_sock, (struct sockaddr *) &remote_addr,
                &remote_addrlen);

    if (fd == -1) {
        if (errno != EAGAIN && errno != EWOULDBLOCK) {
            /* abnormal error */
            WARN("accept");
        } else
            /* no requests */
            ;
        pending_requests = 0;
        return;
    }
    if (fd >= FD_SETSIZE) {
        log_error("Got fd >= FD_SETSIZE.");
        close(fd);
        return;
    }
#ifdef DEBUGNONINET
    /* This shows up due to race conditions in some Linux kernels
       when the client closes the socket sometime between
       the select() and accept() syscalls.
       Code and description by Larry Doolittle <*****@*****.**>
     */
#define HEX(x) (((x)>9)?(('a'-10)+(x)):('0'+(x)))
    if (remote_addr.sin_family != PF_INET) {
        struct sockaddr *bogus = (struct sockaddr *) &remote_addr;
        char *ap, ablock[44];
        int i;
        close(fd);
        log_error_time();
        for (ap = ablock, i = 0; i < remote_addrlen && i < 14; i++) {
            *ap++ = ' ';
            *ap++ = HEX((bogus->sa_data[i] >> 4) & 0x0f);
            *ap++ = HEX(bogus->sa_data[i] & 0x0f);
        }
        *ap = '\0';
        fprintf(stderr, "non-INET connection attempt: socket %d, "
                "sa_family = %hu, sa_data[%d] = %s\n",
                fd, bogus->sa_family, remote_addrlen, ablock);
        return;
    }
#endif

/* XXX Either delete this, or document why it's needed */
/* Pointed out 3-Oct-1999 by Paul Saab <*****@*****.**> */
#ifdef REUSE_EACH_CLIENT_CONNECTION_SOCKET
    if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *) &sock_opt,
                    sizeof (sock_opt))) == -1) {
        DIE("setsockopt: unable to set SO_REUSEADDR");
    }
#endif

    len = sizeof (salocal);

    if (getsockname(fd, (struct sockaddr *) &salocal, &len) != 0) {
        WARN("getsockname");
        close(fd);
        return;
    }

    conn = new_request();
    if (!conn) {
        close(fd);
        return;
    }
    conn->fd = fd;
    conn->status = READ_HEADER;
    conn->header_line = conn->client_stream;
    conn->time_last = current_time;
    conn->kacount = ka_max;

    if (ascii_sockaddr
        (&salocal, conn->local_ip_addr,
         sizeof (conn->local_ip_addr)) == NULL) {
        WARN("ascii_sockaddr failed");
        close(fd);
        enqueue(&request_free, conn);
        return;
    }

    /* nonblocking socket */
    if (set_nonblock_fd(conn->fd) == -1) {
        WARN("fcntl: unable to set new socket to non-block");
        close(fd);
        enqueue(&request_free, conn);
        return;
    }

    /* set close on exec to true */
    if (fcntl(conn->fd, F_SETFD, 1) == -1) {
        WARN("fctnl: unable to set close-on-exec for new socket");
        close(fd);
        enqueue(&request_free, conn);
        return;
    }

#ifdef TUNE_SNDBUF
    /* Increase buffer size if we have to.
     * Only ask the system the buffer size on the first request,
     * and assume all subsequent sockets have the same size.
     */
    if (system_bufsize == 0) {
        len = sizeof (system_bufsize);
        if (getsockopt
            (conn->fd, SOL_SOCKET, SO_SNDBUF, &system_bufsize, &len) == 0
            && len == sizeof (system_bufsize)) {
            ;
        } else {
            WARN("getsockopt(SNDBUF)");
            system_bufsize = 1;
        }
    }
    if (system_bufsize < sockbufsize) {
        if (setsockopt
            (conn->fd, SOL_SOCKET, SO_SNDBUF, (void *) &sockbufsize,
             sizeof (sockbufsize)) == -1) {
            WARN("setsockopt: unable to set socket buffer size");
#ifdef DIE_ON_ERROR_TUNING_SNDBUF
            exit(errno);
#endif /* DIE_ON_ERROR_TUNING_SNDBUF */
        }
    }
#endif                          /* TUNE_SNDBUF */

    /* for log file and possible use by CGI programs */
    if (ascii_sockaddr
        (&remote_addr, conn->remote_ip_addr,
         sizeof (conn->remote_ip_addr)) == NULL) {
        WARN("ascii_sockaddr failed");
        close(fd);
        enqueue(&request_free, conn);
        return;
    }

    /* for possible use by CGI programs */
    conn->remote_port = net_port(&remote_addr);

    status.requests++;

#ifdef USE_TCPNODELAY
    /* Thanks to Jef Poskanzer <*****@*****.**> for this tweak */
    {
        int one = 1;
        if (setsockopt(conn->fd, IPPROTO_TCP, TCP_NODELAY,
                       (void *) &one, sizeof (one)) == -1) {
            DIE("setsockopt: unable to set TCP_NODELAY");
        }

    }
#endif

    total_connections++;
    /* gotta have some breathing room */
    if (total_connections > max_connections) {
        pending_requests = 0;
#ifndef NO_RATE_LIMIT
        /* have to fake an http version */
        conn->http_version = HTTP10;
        conn->method = M_GET;
        send_r_service_unavailable(conn);
        conn->status = DONE;
#endif                          /* NO_RATE_LIMIT */
    }

    enqueue(&request_ready, conn);
}