예제 #1
0
int http_open(file_source_t* src, file_handle_t* handler, char* filename, int flags){
	http_file_handler_t* ofh = (http_file_handler_t*)handler;
	request_rec* req_r = (request_rec*)src->context;
	size_t size;
	int error_code;
	hls_cache_line_t cl;

	if (filename[0] == 0)
		return 0;

	ap_log_error(APLOG_MARK, APLOG_WARNING, get_log_level(), req_r->server, "HLS file: trying to open HTTP data source %s", filename);

	strncpy(ofh->link, filename, sizeof(ofh->link));

	ofh->r = req_r;
	ofh->content_length = 0;
	ofh->last_error_code = 0;

	ap_log_error(APLOG_MARK, APLOG_WARNING, get_log_level(), req_r->server, "HLS file: trying to read first %d bytes to and cache it", (int)(sizeof(cl.buffer)));

	http_read(ofh, cl.buffer, sizeof(cl.buffer), 0, flags);

	ap_log_error(APLOG_MARK, APLOG_WARNING, get_log_level(), req_r->server, "HLS file: got content length %d bytes", (int)ofh->content_length);

	return ofh->content_length != 0;
}
예제 #2
0
파일: http.c 프로젝트: intelrsasw/intelRSD
static int8 *get_request_line(struct http_request *req)
{
	if (NULL == req)
		return NULL;

	int32 r = 0;
	int32 i = req->pos;
	int8 *buf = NULL;
	int8 ch, *line = NULL;

	buf = req->buff;


again:
	for (; req->pos < req->sz; req->pos++) {
		ch = buf[req->pos];

		if (ch == '\r') {
			buf[req->pos] = '\0';
		} else if (ch == '\n') {
			buf[req->pos++] = '\0';
			line = &buf[i];
			break;
		}
	}

	if ((line == NULL)
		&& (r = http_read(req->fd, buf + req->sz, req->buff_size - req->sz)) > 0) {
		req->sz += r;
		get_http_head_sz(req);
		goto again;
	}

	return line;
}
static int connection_event(struct connection *c)
{
	int amnt;
	char buff[BUFF_SZ+1];
	buff[BUFF_SZ] = '\0';

	amnt = read(c->evt_id, buff, BUFF_SZ);
	if (0 == amnt) return 1;
	if (amnt < 0) {
		printf("read from fd %ld, ret %d\n", c->evt_id, amnt);
		perror("read from session");
		return -1;
	}
	buff[amnt] = '\0';

	/* The work: */
	if (amnt != http_write(c->conn_id, buff, amnt)) {
		printf("Error writing.\n");
		return 1;
	}
	while (1) {
		if ((amnt = http_read(c->conn_id, buff, BUFF_SZ)) < 0) {
			printf("Error reading (%d)\n", amnt);
			return -1;
		}
		if (0 == amnt) break;
		if (write(c->evt_id, buff, amnt) != amnt) {
			perror("writing");
			return -1;
		}
	}

	return 0;
}
예제 #4
0
void * conn_handler(void * arr)
{
    int client_fd = *((int*)arr);
    int keep_alive = 1;
    while (keep_alive)
    {


	http_t req;
	if (http_read(&req,client_fd) == -1)
	{
	    http_free(&req);
	    break;
	}
	const char * rh = http_get_status(&req);
	char * uri = process_http_header_request(rh);
	const char * conn_type = http_get_header(&req, "Connection");
	if (conn_type)
	{
	    if (strcasecmp("keep-alive",conn_type))
		keep_alive = 0;
	    //free(conn_type);
	}
	else
	{
	    keep_alive = 0;
	}
	char * output = NULL;
	if (uri)
	{
	    size_t size;
	    const char * body = http_get_body(&req,&size);
            jsonreq_t request;
            request.key = NULL;
            request.value = NULL;
            parsereq(body,&request);

            jsonres_t response = process_request(uri,request);

	    
            generateres(&output,&response,uri);
            if (request.key) free(request.key);
            if (request.value) free(request.value);
            //if (request) free(request);
	    free(uri);
	}
	char * ret_str = "";
        asprintf(&ret_str,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %zu\r\n\r\n",strlen(output));
	send(client_fd,ret_str,strlen(ret_str),0);
	send(client_fd,output,strlen(output),0);
	if (output) free(output);
        if (ret_str) free(ret_str);
	http_free(&req);
    }
    free(arr);
    close(client_fd);
    return NULL;
}
예제 #5
0
파일: mp3_play.c 프로젝트: GCrean/wmamp
/*
 *   input
 */
static enum mad_flow input(void *data, struct mad_stream *stream)
{
    http_t *p = (http_t *) data;
    static int haveread = 0;

    /* Clear MAD_BUFFER_GUARD chunk (last 8 bytes): */
    memset(buf + MP3_SIZE, 0, MAD_BUFFER_GUARD);

    int Remaining;
    char *ReadStart;
    int ReadSize;

    /* MAD_ERROR_BUFLEN (= 0x0001) "input buffer too small (or EOF)" */
    if (stream->error == MAD_ERROR_BUFLEN) {
        /* Some data not decoded; must reissue: */
        Remaining = stream->bufend - stream->next_frame;
        memcpy(buf, stream->next_frame, Remaining);
        ReadStart = buf + Remaining;
        ReadSize  = MP3_SIZE - Remaining;
    }
    else {
        ReadStart = buf;
        ReadSize = MP3_SIZE;
        Remaining = 0;
    }

    int got = http_read(p, ReadStart, ReadSize);

    if (got == 0) {
        /* Reset: */
        buf = buf1;
        haveread = 0;
        next_item();
        return MAD_FLOW_STOP;
    }

    haveread += got;

    mad_stream_buffer(stream, buf, Remaining + got);

    /* Switch between buffers: */
    if (buf == buf1) {
        buf = buf2;
    }
    else {
        buf = buf1;
    }

    return MAD_FLOW_CONTINUE;
}
예제 #6
0
static int http_seek_to_end(void *appdata)
{
	assert(appdata);
	netfile* nf = (netfile*) appdata;

	int n = 0;
	do
	{
		Uint8 b;
		n = http_read(&b, 1, appdata);
	}
	while (n == 1);
	return 0;
}
예제 #7
0
char *System::loadResource(const char *fileName) {
  char *buffer = NULL;
  if (strstr(fileName, "://") != NULL) {
    String *cached = _cache.get(fileName);
    if (cached != NULL) {
      int len = cached->length();
      buffer = (char *)malloc(len + 1);
      memcpy(buffer, cached->c_str(), len);
      buffer[len] = '\0';
    } else {
      int handle = 1;
      var_t *var_p = v_new();
      dev_file_t *f = dev_getfileptr(handle);
      _output->setStatus("Loading...");
      _output->redraw();
      if (dev_fopen(handle, fileName, 0)) {
        if (http_read(f, var_p) == 0) {
          systemPrint("\nfailed to read %s\n", fileName);
        } else {
          int len = var_p->v.p.length;
          buffer = (char *)malloc(len + 1);
          memcpy(buffer, var_p->v.p.ptr, len);
          buffer[len] = '\0';
          _cache.add(fileName, buffer);
        }
      } else {
        systemPrint("\nfailed to open %s\n", fileName);
      }
      _output->setStatus(NULL);
      dev_fclose(handle);
      v_free(var_p);
      v_detach(var_p);
      opt_file_permitted = 0;
    }
  }
  if (buffer == NULL) {
    // remove failed item from history
    strlib::String *old = _history.peek();
    if (old && old->equals(fileName)) {
      delete _history.pop();
    }
  }
  return buffer;
}
예제 #8
0
파일: http_tr_if.c 프로젝트: Koushien/btpd
static void
httptr_io_cb(int sd, short type, void *arg)
{
    struct tr_response res;
    struct httptr_req *treq = arg;
    switch (type) {
    case EV_READ:
        if (http_read(treq->req, sd) && !http_want_read(treq->req))
            btpd_ev_disable(&treq->ioev, EV_READ);
        break;
    case EV_WRITE:
        if (http_write(treq->req, sd) && !http_want_write(treq->req))
            btpd_ev_disable(&treq->ioev, EV_WRITE);
        break;
    case EV_TIMEOUT:
        res.type = TR_RES_CONN;
        tr_result(treq->tr, &res);
        httptr_cancel(treq);
        break;
    default:
        abort();
    }
}
예제 #9
0
파일: http.c 프로젝트: intelrsasw/intelRSD
void *http_process(void *args)
{
	int32		fd;
	struct	http_request *req;
	int8 *cp = NULL;
	int8 *line = NULL;
	int8 *method = NULL;
	int8 *url = NULL;
	int8 *protocol = NULL;
	struct timeval timo;
	int32 optval = 1;
	int32 rc, rc_r, rc_s;
	int32 r = 0;

	if (NULL == args)
		return NULL;

	req = (struct http_request *)args;
	fd = req->fd;

	req->buff = malloc(BUFFSIZ);
	req->buff_size = BUFFSIZ;
	if (NULL == req->buff) {
		HTTPD_ERR("get_request_line malloc %d fail\n", BUFFSIZ);
		free(args);
		return NULL;
	}
	memset(req->buff, 0, BUFFSIZ);

	rc = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
	if (rc < 0)
		HTTPD_ERR("setsockopt error rc=%d errno=%d %s\n", rc, errno, strerror(errno));

	timo.tv_sec  = HTTPD_TIMO;
	timo.tv_usec = 0;

	rc_r = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timo, sizeof(timo));
	rc_s = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timo, sizeof(timo));
	if (rc_r < 0 || rc_s < 0)
		HTTPD_ERR("setsockopt error fd=%d rc=%d rc_r=%d rc_s=%d errno=%d %s\n", fd, rc, rc_r, rc_s, errno, strerror(errno));

	/* GET / HTTP/1.1 */
	method = get_request_line(req);
	if (method == NULL)
		goto close_task;

	url = parse_reqline(fd, method);
	if (url == NULL)
		goto close_task;

	protocol = parse_reqline(fd, url);
	if (protocol == NULL)
		goto close_task;

	req->method = http_method(method);

	if (req->method == M_OPTIONS) {
		send_error(fd, 204, "No Content", NULL, "Method OPTIONS.");
		goto close_task;
	}

	if (req->method == M_UNKNOWN) {
		send_error(fd, 400, "Bad Request", NULL, "Method Not Support.");
		goto close_task;
	}

	decode_url(req, url);

	HTTPD_INFO("method[%s] protocol[%s] url[%s] path[%s] query[%s]!\n", method, protocol, url, req->path, req->query ? : "");

	while ((line = get_request_line(req)) != NULL) {
		if (line[0] == '\0')
			break;

		if (strncasecmp(line, "Upgrade:", 8) == 0) {
			cp = &line[8];
			cp += strspn(cp, " \t");

			if (strncasecmp(cp, "websocket", 9) == 0)
				req->is_websocket =  1;
		} else if (strncasecmp(line, "Connection:", 11) == 0) {
			cp = &line[11];
			cp += strspn(cp, " \t");

			/* Firefox: [Connection: keep-alive, Upgrade] */
			if (strcasestr(cp, "Upgrade") != NULL)
				req->is_connection_upgrade = 1;
		} else if (strncasecmp(line, "Sec-WebSocket-Key:", 18) == 0) {
			cp = &line[18];
			cp += strspn(cp, " \t");
			req->sec_websocket_key = cp;
		} else if (strncasecmp(line, "Origin:", 7) == 0) {
			cp = &line[7];
			cp += strspn(cp, " \t");
			req->origin = cp;
		} else if (strncasecmp(line, "Sec-WebSocket-Version:", 22) == 0) {
			cp = &line[22];
			cp += strspn(cp, " \t");
			req->sec_websocket_version = atoi(cp);
		} else if (strncasecmp(line, "Content-Length:", 15) == 0) {
			cp = &line[15];
			cp += strspn(cp, " \t");
			req->content_length = atol(cp);

			if ((BUFFSIZ < req->content_length + MAX_HEADER_LEN) &&
				(req->buff_size != req->content_length + MAX_HEADER_LEN) + 1) {
				re_alloc_buff(req);
				memset(req->buff + BUFFSIZ, 0, req->buff_size - BUFFSIZ);
			}
		} else if (strncasecmp(line, "Content-Type:", 13) == 0) {
			cp = &line[13];
			cp += strspn(cp, " \t");
			req->content_type = cp;
		} else if (strncasecmp(line, "Host:", 5) == 0) {
			cp = &line[5];
			cp += strspn(cp, " \t");
			req->host = cp;
		}
	}

	HTTPD_INFO("Left %d bytes HTTP data with Content-Length: %ld req->sz[%d] req->pos[%d]\n",
			req->sz - req->pos, req->content_length, req->sz, req->pos);

	if (line == NULL || req->path[0] != '/')
		send_error(fd, 400, "Bad Request", NULL, "Bad Request!");

	if ((0 != req->content_length) && (req->sz != req->hd_sz + req->content_length)) {
		while ((r = http_read(req->fd, req->buff + req->sz, req->buff_size - req->sz)) > 0) {
			req->sz += r;
			if (req->sz == req->hd_sz + req->content_length)
				break;
		}
	}

	if (req->is_websocket)
		ws_process(req);
	else {
		uint32 i = 0;
		int8 *file = NULL;
		int8 *path = req->path;
		int8 *pTmp = path;
		int8 prefix[PREFIX_LEN] = {0};
		int8 new_link[MAX_URL + 8] = {0};

		rmm_cfg_get_rest_prefix(prefix, PREFIX_LEN);
		/*snprintf(new_link, (MAX_URL + 8), "%s%s", prefix, "/rack");*/
		snprintf_s_s(new_link, (MAX_URL + 8), "%s", prefix);

		/*TODO: move to correct place */
		get_json_pointer(req);

		/* remove redundant '/' */
		for (; *(path+i) != '\0'; i++) {
			if ((*(path+i) == '/') && (*(path+i+1) == '/'))
				continue;
			*pTmp++ = *(path+i);
		}
		*pTmp = '\0';
		if ((path[1] == '\0')
			|| (strncasecmp(path, new_link, strnlen_s(new_link, sizeof(new_link)-1)) == 0))
			file = NULL;
		else
			file = path;

		if (file != NULL)
			send_file(req->fd, file);
		else
			rest_process(req);
	}

close_task:
	close(fd);
	if (NULL != req->buff) {
		free(req->buff);
		req->buff = NULL;
	}
	HTTPD_INFO("\nrest_req_thread[%lld] exit, fd[%d], errno:%d %s\n", (uint64)(req->tid_rest_req), fd, errno, strerror(errno));
	free(args);
	pthread_detach(pthread_self());
	return NULL;
}
예제 #10
0
void *check_version_proc(void *ptr)
{
	int patch, build;
	char *url = "http://gridlab-d.svn.sourceforge.net/viewvc/gridlab-d/trunk/core/versions.txt";
	HTTPRESULT *result = http_read(url,0x1000);
	char target[32];
	char *pv = NULL, *nv = NULL;
	int rc = 0;
	int mypatch = REV_PATCH;
	int mybuild = atoi(BUILDNUM);

	/* if result not found */
	if ( result==NULL || result->body.size==0 )
	{
		output_warning("check_version: unable to read %s", url);
		rc=CV_NOINFO;
		goto Done;
	}

	/** @todo check the version against latest available **/
	if ( result->status>0 && result->status<400 )
	{
		output_warning("check_version: '%s' error %d", url, result->status);
		rc=CV_BADURL;
		goto Done;
	}

	/* read version data */
	sprintf(target,"%d.%d:",REV_MAJOR,REV_MINOR);
	pv = strstr(result->body.data,target);
	if ( pv==NULL )
	{
		output_warning("check_version: '%s' has no entry for version %d.%d", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}
	if ( sscanf(pv,"%*d.%*d:%d:%d", &patch, &build)!=2 )
	{
		output_warning("check_version: '%s' entry for version %d.%d is bad", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}

	nv = strchr(pv,'\n');
	if ( nv!=NULL )
	{
		while ( *nv!='\0' && isspace(*nv) ) nv++;
		if ( *nv!='\0' )
		{
			output_warning("check_version: newer versions than %s (Version %d.%d) are available", BRANCH, REV_MAJOR, REV_MINOR);
			rc|=CV_NEWVER;
		}
		/* not done yet */
	}
	if ( mypatch<patch )
	{
		output_warning("check_version: a newer patch of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWPATCH;
		/* not done yet */
	}
	if ( mybuild>0 && mybuild<build )
	{
		output_warning("check_version: a newer build of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWBUILD;
	}
	if ( rc==0 )
		output_verbose("this version is current");

	/* done */
Done:
	http_delete_result(result);
	return (void*)rc;
}
예제 #11
0
static int read_http_payload(struct ledm_session *ps, char *payload, int max_size, int sec_timeout, int *bytes_read)
{
  struct bb_ledm_session *pbb = ps->bb_session;
  int stat=1, total=0, len;
  int tmo=sec_timeout;
  enum HTTP_RESULT ret;
  int payload_length=-1;
  char *temp=NULL;

  *bytes_read = 0;

  if(http_read_header(pbb->http_handle, payload, max_size, tmo, &len) != HTTP_R_OK)
      goto bugout;

  _DBG("read_http_payload len=%d %s\n",len,payload);
  temp = strstr(payload, "HTTP/1.1 201 Created");
  if (temp)
  {
		*bytes_read = total = len;
		stat=0;
		return stat ;
  }
  
  temp=strstr(payload, "Content-Length:");
  if (temp)
  {
		temp=temp+16;
		temp=strtok(temp, "\r\n");
		payload_length=strtol(temp, NULL, 10);
		if (payload_length == 0)
	  	{
			*bytes_read = total = len;
			stat=0;
			return stat ;
		}
  }
  memset(payload, ' ', len);
  if(payload_length==-1)
  {
    int i=10;
    while(i)
    {
		len = 0;
		ret = http_read(pbb->http_handle, payload+total, max_size-total, tmo, &len);
		total+=len;
      	tmo=1;
    	i--;
		if (ret == HTTP_R_EOF)
        {
         _DBG("read_http_payload1 DONE......\n");
          break;    /* done */
        }

    	if (!(ret == HTTP_R_OK || ret == HTTP_R_EOF))
        {
        	_DBG("read_http_payload1 ERROR......\n");
        	goto bugout;
        }
    }//end while(i)
  }//end if(payload_length==-1)
  else
  {
	  len=payload_length;
	  while (total < payload_length) 
	  {
		  ret = http_read(pbb->http_handle, payload+total, max_size-total, tmo, &len);
		  total+=len;
		  tmo=1;
		  if (ret == HTTP_R_EOF)
		  {
		     _DBG("read_http_payload2 DONE......\n");
		     break;    /* done */
		  } 

		  if (!(ret == HTTP_R_OK || ret == HTTP_R_EOF))
		  {
        	  _DBG("read_http_payload2 ERROR......\n");
        	  goto bugout;
           }
        }//end while()
  }//end else

 *bytes_read = total;
  stat=0;

bugout:
   return stat;
} /* read_http_payload */
예제 #12
0
UNSIGNED32 get_timestamp_response(const char* urlStr, char* hash, UNSIGNED32 hash_size, UNSIGNED32 httpTimeOut, TS_RESP** tsResponse)
{
	UNSIGNED32 result = TINTERNALERROR;
	BIO* responseBio = NULL;
	Url* url = NULL;
	TS_REQ* tsRequest = NULL;
	BIO* requestBio = NULL;
	int requestHeaderLength;
	int requestLength;
	int requestContentLength;
	char requestHeader[2048 + 256];
	char* request = NULL;
	void* contentBuffer = NULL;
	void* resultBuffer = NULL;
	int resultLength;
	TS_MSG_IMPRINT* msgImprint = NULL;
	ASN1_OCTET_STRING* hashedMessage = NULL;
	int hashedMessageLength;
	int httpResult;
	char *urlBuffer = NULL;
	int redirection = 0;

	/* Check if TS url is specified */
	if (!urlStr)
	{
		goto end;
	}

	/* Get Request for timestamp */
	tsRequest = get_timestamp_request(hash, hash_size, create_nonce(NONCE_LENGTH));
	msgImprint = TS_REQ_get_msg_imprint(tsRequest);
	hashedMessage = TS_MSG_IMPRINT_get_msg(msgImprint);
	hashedMessageLength = ASN1_STRING_length((ASN1_STRING*)hashedMessage);
	if ((int)hash_size != hashedMessageLength)
	{
		goto end;
	}

	requestBio = BIO_new(BIO_s_mem());
	if (requestBio == NULL)
	{
		goto end;
	}

	if (!i2d_TS_REQ_bio(requestBio, tsRequest))
	{
		goto end;
	}

	contentBuffer = memory_alloc(BIO_number_written(requestBio));
	if (contentBuffer == NULL)
	{
		goto end;
	}

    requestContentLength = BIO_read(requestBio, contentBuffer, BIO_number_written(requestBio));

    /* Allocate memory buffer for timestamp server url */
    urlBuffer = memory_alloc(strlen(urlStr) + 1);
    if (!urlBuffer)
    {
    	goto end;
    }
    /* Copy TS url to allocated buffer */
    strcpy(urlBuffer, urlStr);

http_redirect:

	/* Parse and check URL */
	url = parse_url(urlBuffer);
	if (url == NULL)
	{
		goto end;
	}
	if (strcmp(url->Scheme, "http") != 0)
	{
		goto end;
	}

    requestHeaderLength = sprintf(requestHeader, "POST %s HTTP/1.0\r\nHOST: %s\r\nPragma: no-cache\r\nContent-Type: application/timestamp-query\r\nAccept: application/timestamp-reply\r\nContent-Length: %d\r\n\r\n",
    		urlBuffer, url->Host, requestContentLength);

	requestLength = requestHeaderLength + requestContentLength;

	request = (char*)memory_alloc(requestLength);
	if (request == NULL)
	{
		goto end;
	}

	memcpy(request, requestHeader, requestHeaderLength);
	memcpy(request + requestHeaderLength, contentBuffer, requestContentLength);

	httpResult = http_read(url->Host, request, requestLength, url->Port, httpTimeOut, 1, &resultBuffer, &resultLength);
	if (httpResult == HTTP_REDIRECTION && (resultBuffer) && !redirection)
	{
		free_url(url);
		url = NULL;
		memory_free(request);
		request = NULL;
		/* Allocated buffer for redirected url */
	    urlBuffer = memory_realloc(urlBuffer, resultLength);
	    if (!urlBuffer)
	    {
	    	goto end;
	    }
	    memcpy(urlBuffer, resultBuffer, resultLength);
	    memory_free(resultBuffer);
	    redirection++;
		goto http_redirect;
	} else
	if ((httpResult == HTTP_NOERROR) && (resultBuffer))
	{
		responseBio = BIO_new(BIO_s_mem());
		if (responseBio == NULL)
		{
			goto end;
		}
		BIO_write(responseBio, resultBuffer, resultLength);

		*tsResponse = d2i_TS_RESP_bio(responseBio, NULL);
		if (*tsResponse == NULL)
		{
			goto end;
		}

		result = TNOERR;
	}
	else
	{
		switch (httpResult)
		{
			case HTTP_NOLIVEINTERNET_ERROR:
				result = TNONET;
				break;
			case HTTP_TIMEOUT_ERROR:
				result = TTIMEOUT;
				break;
			case HTTP_RESPONSESTATUS_ERROR:
				result = TSERVERERROR;
				break;
			default:
				result = TINTERNALERROR;
				break;
		}
	}

end:
	free_url(url);
	if (tsRequest != NULL)
	{
		TS_REQ_free(tsRequest);
	}
	if (requestBio != NULL)
	{
		BIO_free_all(requestBio);
	}
	if (responseBio != NULL)
	{
		BIO_free_all(responseBio);
	}
	if (request != NULL)
	{
		memory_free(request);
	}
	if (contentBuffer != NULL)
	{
		memory_free(contentBuffer);
	}
	if (resultBuffer != NULL)
	{
		memory_free(resultBuffer);
	}
	if (urlBuffer != NULL)
	{
		memory_free(urlBuffer);
	}

	return result;
}
예제 #13
0
void http_buf(TCP_NODE * n)
{
	char *p_cmd = NULL;
	char *p_url = NULL;
	char *p_var = NULL;
	char *p_proto = NULL;
	char *p_head = NULL;
	char *p_body = NULL;
	HASH *head = NULL;
	char recv_buf[BUF_SIZE];

	/* Do not start before at least this much arrived: "GET / HTTP/1.1" */
	if (n->recv_size <= 14) {
		return;
	}

	/* Copy HTTP request */
	memset(recv_buf, '\0', BUF_SIZE);
	memcpy(recv_buf, n->recv_buf, n->recv_size);

	/* Return until the header is complete. Gets killed if this grows beyond
	 * all imaginations. */
	if ((p_body = strstr(recv_buf, "\r\n\r\n")) == NULL) {
		return;
	}

	/* Keep one \r\n for consistent header analysis. */
	*p_body = '\r';
	p_body++;
	*p_body = '\n';
	p_body++;
	*p_body = '\0';
	p_body++;
	*p_body = '\0';
	p_body++;

	/* HTTP Pipelining: There is at least one more request. */
	if (n->recv_size > (ssize_t) (p_body - recv_buf)) {
		n->recv_size -= (ssize_t) (p_body - recv_buf);
		memset(n->recv_buf, '\0', BUF_SIZE);
		memcpy(n->recv_buf, p_body, n->recv_size);
	} else {
		/* The request has been copied. Reset the receive buffer. */
		node_clearRecvBuf(n);
	}

	/* Remember start point */
	p_cmd = recv_buf;

	/* Find url */
	if ((p_url = strchr(p_cmd, ' ')) == NULL) {
		info(_log, &n->c_addr, "Requested URL was not found");
		node_status(n, NODE_SHUTDOWN);
		return;
	}
	*p_url = '\0';
	p_url++;

	/* Find protocol type */
	if ((p_proto = strchr(p_url, ' ')) == NULL) {
		info(_log, &n->c_addr, "No protocol found in request");
		node_status(n, NODE_SHUTDOWN);
		return;
	}
	*p_proto = '\0';
	p_proto++;

	/* Find variables( Start from p_url again) */
	if ((p_var = strchr(p_url, '?')) != NULL) {
		*p_var = '\0';
		p_var++;
	}

	/* Find header lines */
	if ((p_head = strstr(p_proto, "\r\n")) == NULL) {
		info(_log, &n->c_addr,
		     "There must be a \\r\\n. I put it there...");
		node_status(n, NODE_SHUTDOWN);
		return;
	}
	*p_head = '\0';
	p_head++;
	*p_head = '\0';
	p_head++;

	/* Hash header */
	head = http_hashHeader(p_head);

	/* Validate input */
	http_read(n, p_cmd, p_url, p_proto, head);

	/* Delete Hash */
	http_deleteHeader(head);
}
예제 #14
0
파일: ahttp.c 프로젝트: hfs/afd
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ascp $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
int
main(int argc, char *argv[])
{
    int   bytes_buffered,
          fd,
          hunk_size;
    off_t bytes_read = 0;
    char  block[1024],
          hostname[45],
          path[MAX_PATH_LENGTH];

    if ((argc != 2) && (argc != 3) && (argc != 4))
    {
        (void)fprintf(stderr, "Usage: %s <filename> [<host> [<path>]]\n", argv[0]);
        exit(-1);
    }
    if (argc == 4)
    {
        (void)strncpy(hostname, argv[2], 44);
        (void)strncpy(path, argv[3], MAX_PATH_LENGTH - 1);
    }
    else if (argc == 3)
    {
        (void)strncpy(hostname, argv[2], 44);
        (void)strcpy(path, "/");
    }
    else
    {
        (void)strcpy(hostname, "localhost");
        (void)strcpy(path, "/");
    }
    if (http_connect(hostname, DEFAULT_HTTP_PORT) == -1)
    {
        (void)fprintf(stderr, "http_connect() failed\n");
        exit(-1);
    }
    if (http_get(hostname, path, argv[1], &bytes_buffered) == INCORRECT)
    {
        (void)fprintf(stderr, "http_get() failed\n");
        exit(-1);
    }
    if ((fd = open(argv[1], (O_WRONLY | O_CREAT | O_TRUNC),
                   (S_IRUSR | S_IWUSR))) == -1)
    {
        (void)fprintf(stderr, "Failed to open() %s : %s\n",
                      argv[1], strerror(errno));
        exit(-1);
    }
    if (bytes_buffered > 0)
    {
        bytes_read += bytes_buffered;
        if (write(fd, msg_str, bytes_buffered) != bytes_buffered)
        {
            (void)fprintf(stderr, "write() error : %s\n", strerror(errno));
            exit(-1);
        }
    }
    while ((hunk_size = http_read(block, 1024)) > 0)
    {
        if (write(fd, block, hunk_size) != hunk_size)
        {
            (void)fprintf(stderr, "write() error : %s\n", strerror(errno));
            exit(-1);
        }
        bytes_read += hunk_size;
    }
    if (close(fd) == -1)
    {
        (void)fprintf(stderr, "close() error : %s\n", strerror(errno));
    }
    (void)fprintf(stdout, "Got file %s with %d Bytes.\n", argv[1], bytes_read);

    return(0);
}