Exemple #1
0
/* open stream                                                         */
static void *http_open(const char *uri, reader_status_type status, void *data)
{
    http_desc_t *desc;
    char redirect[10240];
    int tries = 0;

    /* Alloc descripor and init members. */
    desc = malloc (sizeof (http_desc_t));
    desc->going = 0;
    desc->new_datablock = 0;
    desc->dont_wait = 0;
    desc->sock = 0;
    desc->size = 0;
    desc->pos = 0;
    desc->buffer = NULL;
    desc->buffer_pos = 0;
    desc->begin = 0;
    desc->len = 0;
    desc->direction = 0;
    desc->metadata = NULL;
    desc->status = status;
    desc->data = data;
    pthread_mutex_init (&desc->buffer_lock, NULL);
    pthread_mutex_init (&desc->meta_lock, NULL);
    pthread_cond_init (&desc->new_datablock_signal, NULL);
    pthread_cond_init (&desc->dont_wait_signal, NULL);

    /* Parse URI */
    if (parse_uri (uri, &desc->host, &desc->port, &desc->path)) {
	http_close (desc);
	return NULL;
    }

    /* Connect */
    if (desc->status) {
	    desc->status(desc->data, "Connecting");
    }
    while (tries++ < 5) {
	redirect[0] = 0;
    	if (reconnect (desc, redirect)) {
		if (*redirect) {
			if (parse_uri (redirect, &desc->host, &desc->port, &desc->path)) {
				http_close(desc);
				return NULL;
			}
		}
		continue;
	} else { /* Success! */
		return desc;
	}
    }
    http_close (desc);
    return NULL;
}
Exemple #2
0
//404
void resp_error_page( header_out_t*  header_out, int status_code )
{
	if ( status_code >= 400 && status_code <= 507 )
	{
		int ret = resp_defined_error_page(  header_out , status_code );
		if ( ret == 1 )
		{
			return;
		}
	}

	//get header info
	header_status_t  error_page = get_http_status( status_code );
	int datalen = strlen( error_page.data );

	//header append
	//resp_append_header( header_out , HEADER_STATUS , error_page.status  );
	//resp_append_header( header_out , HEADER_SERVER );

	create_common_header( header_out , status_code );
	header_append_length( header_out , datalen );
	resp_append_header( header_out , HEADER_END_LINE );

	//send
	http_response_write( header_out->req->connfd, header_out->data , header_out->length );
	http_response_write( header_out->req->connfd, error_page.data , datalen );
	http_close( header_out->req , 0 );
}
Exemple #3
0
int http_server_task(struct httpd * httpd)
{
	struct httpctl httpctl;
	struct httpctl * ctl = &httpctl;
	const struct httpdobj * obj;

	INF("Webserver started (thread %d).", thinkos_thread_self());

	for (;;) {
		if (http_accept(httpd, ctl) < 0) {
			ERR("tcp_accept() failed!\n");
			thinkos_sleep(1000);
			continue;
		}

		if ((obj = http_obj_lookup(ctl)) != NULL) {
			switch (ctl->method) {
			case HTTP_GET:
				DBG("HTTP GET \"%s\"", obj->oid);
				http_get(ctl, obj);
				break;
			case HTTP_POST:
				DBG("HTTP POST \"%s\"", obj->oid);
				http_post(ctl, obj);
				break;
			}
		}

		http_close(ctl);
	}

	return 0;
}
Exemple #4
0
/**
 * Closes the underlying #http_request.
 *
 * @param callback TRUE to execute the callback, otherwise FALSE.
 *
 * @param req The #SteamHttpReq.
 **/
static void steam_http_req_close(SteamHttpReq *req, gboolean callback)
{
    g_return_if_fail(req != NULL);

    b_event_remove(req->toid);

    if ((req->err == NULL) && (req->scode == 0)) {
        g_set_error(&req->err, STEAM_HTTP_ERROR, STEAM_HTTP_ERROR_CLOSED,
                    "Request closed");
    }

    if (callback && (req->func != NULL))
        req->func(req, req->data);

    if (req->request != NULL) {
        /* Prevent more than one call to request->func() */
        req->request->func = steam_http_req_close_nuller;
        req->request->data = NULL;

        if (!(req->request->flags & STEAM_HTTP_CLIENT_FREED))
            http_close(req->request);
    }

    req->status    = NULL;
    req->scode     = 0;
    req->header    = NULL;
    req->body      = NULL;
    req->body_size = 0;
    req->toid      = 0;
    req->request   = NULL;
}
Exemple #5
0
// pong_thread(threadarg)
//    Connect to the server at the position indicated by `threadarg`
//    (which is a pointer to a `pong_args` structure).
void* pong_thread(void* threadarg) {
    pthread_detach(pthread_self());

    // Copy thread arguments onto our stack.
    pong_args pa = *((pong_args*) threadarg);

    char url[256];
    snprintf(url, sizeof(url), "move?x=%d&y=%d&style=on",
             pa.x, pa.y);

    http_connection* conn = http_connect(pong_addr);
    http_send_request(conn, url);
    http_receive_response_headers(conn);
    if (conn->status_code != 200)
        fprintf(stderr, "%.3f sec: warning: %d,%d: "
                "server returned status %d (expected 200)\n",
                elapsed(), pa.x, pa.y, conn->status_code);

    http_receive_response_body(conn);
    double result = strtod(conn->buf, NULL);
    if (result < 0) {
        fprintf(stderr, "%.3f sec: server returned error: %s\n",
                elapsed(), http_truncate_response(conn));
        exit(1);
    }

    http_close(conn);

    // signal the main thread to continue
    pthread_cond_signal(&condvar);
    // and exit!
    pthread_exit(NULL);
}
Exemple #6
0
/**
 * Logout method. Just free the twitter_data.
 */
static void twitter_logout(struct im_connection *ic)
{
	struct twitter_data *td = ic->proto_data;

	// Set the status to logged out.
	ic->flags &= ~OPT_LOGGED_IN;

	// Remove the main_loop function from the function queue.
	b_event_remove(td->main_loop_id);

	if (td->timeline_gc)
		imcb_chat_free(td->timeline_gc);

	if (td) {
		http_close(td->stream);
		oauth_info_free(td->oauth_info);
		g_free(td->user);
		g_free(td->prefix);
		g_free(td->url_host);
		g_free(td->url_path);
		g_free(td->log);
		g_free(td);
	}

	twitter_connections = g_slist_remove(twitter_connections, ic);
}
Exemple #7
0
int httpreq(char** buffer, size_t* length)
{
  int socket_fd;
  size_t request_text_length;

  if ((socket_fd = http_connect(LFM_HOST)) < 0) {
    LOG(LOG_CRITICAL, "Could not connect to %s.", LFM_HOST);
    exit(ERROR);
  }

  http_request(NEW_RELEASE_URL, strlen(NEW_RELEASE_URL),
               LFM_HOST, strlen(LFM_HOST), buffer, &request_text_length);

  if (http_send_request(socket_fd, *buffer, request_text_length) == -1) {
    LOG(LOG_CRITICAL, "Could not send request.");
    exit(ERROR);
  }

  free(*buffer);

  if (http_read_response(socket_fd, buffer, length)) {
    LOG(LOG_CRITICAL, "Could not read request");
    exit(ERROR);
  }

  http_close(socket_fd);

  return OK;
}
Exemple #8
0
int bb_is_paper_in_adf(struct ledm_session *ps) /* 0 = no paper in adf, 1 = paper in adf, -1 = error */
{
  char buf[1024];
  int bytes_read;
  struct bb_ledm_session *pbb = ps->bb_session;

  if(http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
  {
        _BUG("unable to open channel HPMUD_S_LEDM_SCAN \n");
        return -1;
  }
  if (http_write(pbb->http_handle, GET_SCANNER_STATUS, sizeof(GET_SCANNER_STATUS)-1, 10) != HTTP_R_OK)
  {
    _BUG("unable to get scanner status \n");
  }
  read_http_payload(ps, buf, sizeof(buf), EXCEPTION_TIMEOUT, &bytes_read);

  http_close(pbb->http_handle);   /* error, close http connection */
  pbb->http_handle = 0;
  _DBG("bb_is_paper_in_adf .job_id=%d page_id=%d buf=%s \n", ps->job_id, ps->page_id, buf );
  if(strstr(buf, ADF_LOADED)) return 1;
  if(strstr(buf, ADF_EMPTY))
  {
     if (strstr(buf, SCANNER_BUSY_WITH_SCAN_JOB)) return 1;
     if (ps->currentInputSource ==IS_ADF_DUPLEX && ps->page_id % 2 == 1)
        return 1;
     else  
        return 0;
  }
  else return -1;
}
Exemple #9
0
DWORD HttpClient::http_get(const std::wstring& url
	, const std::vector<std::wstring>& headers, std::string& resp_data)
{
#ifndef USER_CURL
	DWORD ret = request(url, L"GET", headers, std::string(), resp_data);
	http_close();
	return ret;
#else

	std::string url_temp = Wide2UTF8(url);
	CURL* curl = curl_easy_init();

    CURLcode res = CURLE_OK;
    if (curl)
    {
        std::vector<std::string> respHeaders;
        ResponseSink sink = { &resp_data, &respHeaders };

        // set params  
        curl_easy_setopt(curl, CURLOPT_URL, url_temp.c_str()); // url
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, onResponse);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&sink);
        curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, onHeaderCallback);
        curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void *)&sink);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5000);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5000);

        if (false == m_proxyIP.empty())
        {
            curl_easy_setopt(curl, CURLOPT_PROXY, m_proxyIP.c_str());
            curl_easy_setopt(curl, CURLOPT_PROXYPORT, m_proxyPort);
            curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
        }

        struct curl_slist *headerlist = NULL;
        size_t headerlength = headers.size();
        for (int i = 0; i < headerlength; i++)
        {
            headerlist = curl_slist_append(headerlist, Wide2UTF8(headers[i]).c_str());
        }

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
        // start req  
        res = curl_easy_perform(curl);

        curl_slist_free_all(headerlist);
    }

    if (NULL != curl)
    {
        curl_easy_cleanup(curl);
        curl = NULL;
    }

	return res;
#endif // !USER_CURL
}
Exemple #10
0
static void http_free(git_smart_subtransport *subtransport)
{
	http_subtransport *t = (http_subtransport *) subtransport;

	http_close(subtransport);

	git__free(t);
}
Exemple #11
0
DWORD HttpClient::http_put(const std::wstring& url
	, const std::vector<std::wstring>& headers, const std::string& body, std::string& resp_data)
{
	DWORD ret = request(url, L"PUT", headers, body, resp_data);
	http_close();

	return ret;
}
/**
* Clear the test environment. Currently; clear test sequence
*/
void tests_reset(testcase* test) {
	g_slist_free_full(test_sequence,(GDestroyNotify)free_key);
	test_sequence = NULL;
	
	g_hash_table_foreach(test->files,(GHFunc)testcase_reset_file,NULL);
	
	// Cleanup http
	http_close();
}
Exemple #13
0
void
curl_easy_cleanup(CURL *curl)
{
  if (curl)
    {
      http_close (curl->hd, 0);
      free(curl);
    }
}
Exemple #14
0
static errno_t     httpfs_close(struct uufile *f)
{
    if( f->impl )
    {
        struct uusocket *us = f->impl;
        http_close(us->prot_data);
        free(f->impl);
        f->impl = 0;
    }

    return 0;
}
Exemple #15
0
int bb_end_page(struct ledm_session *ps, int io_error)
{
   struct bb_ledm_session *pbb = ps->bb_session;

  _DBG("bb_end_page(error=%d)\n", io_error);

   if (pbb->http_handle)
   {
      http_close(pbb->http_handle);
      pbb->http_handle = 0;
   }
   return 0;
}
/** Process an incoming action request
	@returns non-zero on success, 0 on failure (errno set)
 **/
int http_action_request(HTTP *http,char *action)
{
	if (gui_post_action(action)==-1)
	{
		http_status(http,HTTP_ACCEPTED);
		http_type(http,"text/plain");
		http_format(http,"Goodbye");
		http_send(http);
		http_close(http);
		shutdown_now();
		return 1;
	}
	else
		return 0;
}
Exemple #17
0
void http_redirect( httpHeader* reqHeader ,  char* uri )
{
	header_out_t  header_out;
	memset( &header_out , 0 , sizeof( header_out ));
	header_out.req = reqHeader;
	header_status_t  error_page = get_http_status( 301 );        //header append

	create_common_header(  &header_out , 301 );
	resp_append_header( &header_out , HEADER_LOCATION , uri );
	resp_append_header( &header_out , HEADER_CONTENT_LENGTH , 0  );
	resp_append_header( &header_out , HEADER_END_LINE );

	http_response_write( reqHeader->connfd , header_out.data , header_out.length );
	http_close( reqHeader , 0 );
}
Exemple #18
0
static gboolean twitter_filter_update(gpointer data, gint fd,
                                      b_input_condition cond)
{
	struct im_connection *ic = data;
	struct twitter_data *td = ic->proto_data;

	if (td->filters) {
		twitter_open_filter_stream(ic);
	} else if (td->filter_stream) {
		http_close(td->filter_stream);
		td->filter_stream = NULL;
	}

	td->filter_update_id = 0;
	return FALSE;
}
Exemple #19
0
int bb_end_scan(struct ledm_session* ps, int io_error)
{
  struct bb_ledm_session *pbb = ps->bb_session;

  _DBG("bb_end_scan(error=%d)\n", io_error);

  if (pbb->http_handle)
  {
    http_close(pbb->http_handle);
    pbb->http_handle = 0;
  }
  cancel_job(ps);
  memset(ps->url, 0, sizeof(ps->url));
  ps->job_id = 0;
  ps->page_id = 0;
  return 0;
}
Exemple #20
0
static int cancel_job(struct ledm_session *ps)
{
  struct bb_ledm_session *pbb = ps->bb_session;
  int len, stat=1, tmo=5/*EXCEPTION_TIMEOUT*/;
  char buf[2048];
  int bytes_read;

  _DBG("cancel_job user_cancel=%d job_id=%d url=%s \n", ps->user_cancel, ps->job_id, ps->url);
  if (ps->job_id == 0 || ps->user_cancel == 0)
  {
       ps->job_id = 0;
       ps->page_id = 0;
       return 0 ;
  }
  
  if (http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
  {
    _BUG("unable to open http connection %s\n", ps->uri);
    goto bugout;
  }

  len = snprintf(buf, sizeof(buf), CANCEL_JOB_REQUEST, ps->url, strlen(CANCEL_JOB_DATA));
  if (http_write(pbb->http_handle, buf, len, 1) != HTTP_R_OK)
  {
    _BUG("unable to cancel_job %s\n", ps->url);
  }
 
  len = snprintf(buf, sizeof(buf), CANCEL_JOB_DATA);
  if (http_write(pbb->http_handle, buf, len, 1) != HTTP_R_OK)
  {
    _BUG("unable to cancel_job %s\n", ps->url);
  }

  if (read_http_payload(ps, buf, sizeof(buf), tmo, &bytes_read))
    goto bugout;

  stat=0;

bugout:
  if (pbb->http_handle)
  {
    http_close(pbb->http_handle);
    pbb->http_handle = 0;
  }
  return stat;   
}; /* cancel_job */
Exemple #21
0
static int get_scanner_elements(struct ledm_session *ps, struct wscn_scan_elements *elements)
{
  struct bb_ledm_session *pbb = ps->bb_session;
  int bytes_read = 0;
  int stat=1, tmo=10;
  char buf[8192];

  if (http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
  {
    _BUG("unable to open http connection %s\n", ps->uri);
    goto bugout;
  }

  /* Write the xml payload. */
  if (http_write(pbb->http_handle, GET_SCANNER_ELEMENTS, sizeof(GET_SCANNER_ELEMENTS)-1, tmo) != HTTP_R_OK)
  {
    _BUG("unable to get_scanner_elements %s\n", ps->uri);
    goto bugout;
  }

  /* Read http response. */
  if (read_http_payload(ps, buf, sizeof(buf), tmo, &bytes_read))
    goto bugout;

  _DBG("get_scanner_elements bytes_read=%d len=%d buf=%s\n", bytes_read, strlen(buf), buf);

   http_unchunk_data(buf);
   bytes_read=strlen(buf);
  
  _DBG("get_scanner_elements buf=%s\n", buf);
  parse_scan_elements(buf, bytes_read, elements);
  stat=0;

bugout:
  if (pbb->http_handle)
  {
    http_close(pbb->http_handle);
    pbb->http_handle = 0;
  }
  return stat;
} /* get_scanner_elements */
Exemple #22
0
CURLcode
curl_easy_perform(CURL *curl)
{
  int rc;
  CURLcode err=CURLE_OK;
  const char *errstr=NULL;
  char *proxy=NULL;
  struct http_srv srv;

  memset(&srv,0,sizeof(srv));

  /* Emulate the libcurl proxy behavior.  If the calling program set a
     proxy, use it.  If it didn't set a proxy or set it to NULL, check
     for one in the environment.  If the calling program explicitly
     set a null-string proxy the http code doesn't use a proxy at
     all. */

  if(curl->proxy)
    proxy=curl->proxy;
  else
    proxy=getenv(HTTP_PROXY_ENV);

  if(curl->srvtag)
    srv.srvtag=curl->srvtag;

  if(curl->flags.verbose)
    {
      fprintf(curl->errors,"* HTTP proxy is \"%s\"\n",proxy?proxy:"null");
      fprintf(curl->errors,"* HTTP URL is \"%s\"\n",curl->url);
      if(srv.srvtag)
	fprintf(curl->errors,
		"* SRV tag is \"%s\": host and port may be overridden\n",
		srv.srvtag);
      fprintf(curl->errors,"* HTTP auth is \"%s\"\n",
	      curl->auth?curl->auth:"null");
      fprintf(curl->errors,"* HTTP method is %s\n",
	      curl->flags.post?"POST":"GET");
    }

  if(curl->flags.post)
    {
      rc=http_open(&curl->hd,HTTP_REQ_POST,curl->url,curl->auth,0,proxy,
		   &srv,curl->headers?curl->headers->list:NULL);
      if(rc==0)
	{
	  char content_len[50];
	  unsigned int post_len=strlen(curl->postfields);

	  if(curl->flags.verbose && srv.used_server && srv.used_port)
	    fprintf (curl->errors, "* HTTP host:port post-SRV is \"%s:%hu\"\n",
		     srv.used_server, srv.used_port);

	  iobuf_writestr(curl->hd.fp_write,
			 "Content-Type: application/x-www-form-urlencoded\r\n");
	  sprintf(content_len,"Content-Length: %u\r\n",post_len);

	  iobuf_writestr(curl->hd.fp_write,content_len);

	  http_start_data(&curl->hd);
	  iobuf_write(curl->hd.fp_write,curl->postfields,post_len);
	  rc=http_wait_response(&curl->hd,&curl->status);
	  if(rc==0 && curl->flags.failonerror && curl->status>=300)
	    err=CURLE_HTTP_RETURNED_ERROR;
	}
    }
  else
    {
      rc=http_open(&curl->hd,HTTP_REQ_GET,curl->url,curl->auth,0,proxy,
		   &srv,curl->headers?curl->headers->list:NULL);
      if(rc==0)
	{
	  if(curl->flags.verbose && srv.used_server && srv.used_port)
	    fprintf (curl->errors, "* HTTP host:port post-SRV is \"%s:%hu\"\n",
		     srv.used_server, srv.used_port);

	  rc=http_wait_response(&curl->hd,&curl->status);
	  if(rc==0)
	    {
	      if(curl->flags.failonerror && curl->status>=300)
		err=CURLE_HTTP_RETURNED_ERROR;
	      else
		{
		  unsigned int maxlen=1024,buflen,len;
		  byte *line=NULL;

		  while((len=iobuf_read_line(curl->hd.fp_read,
					     &line,&buflen,&maxlen)))
		    {
		      size_t ret;

		      maxlen=1024;

		      ret=(curl->writer)(line,len,1,curl->file);
		      if(ret!=len)
			{
			  err=CURLE_WRITE_ERROR;
			  break;
			}
		    }

		  xfree(line);
		  http_close(&curl->hd);
		}
	    }
	  else
	    http_close(&curl->hd);
	}
    }

  free (srv.used_server);

  switch(rc)
    {
    case 0:
      break;

    case G10ERR_INVALID_URI:
      err=CURLE_UNSUPPORTED_PROTOCOL;
      break;

    case G10ERR_NETWORK:
      errstr=strerror(errno);
      err=CURLE_COULDNT_CONNECT;
      break;

    default:
      errstr=g10_errstr(rc);
      err=CURLE_COULDNT_CONNECT;
      break;
    }
      
  return handle_error(curl,err,errstr);
}
Exemple #23
0
/* Get the key from URL which is expected to specify a http style
   scheme.  On success R_FP has an open stream to read the data.  */
gpg_error_t
ks_http_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp)
{
  gpg_error_t err;
  http_session_t session = NULL;
  http_t http = NULL;
  int redirects_left = MAX_REDIRECTS;
  estream_t fp = NULL;
  char *request_buffer = NULL;

  err = http_session_new (&session, NULL);
  if (err)
    goto leave;
  http_session_set_log_cb (session, cert_log_cb);

  *r_fp = NULL;
 once_more:
  err = http_open (&http,
                   HTTP_REQ_GET,
                   url,
                   /* httphost */ NULL,
                   /* fixme: AUTH */ NULL,
                   0,
                   /* fixme: proxy*/ NULL,
                   session,
                   NULL,
                   /*FIXME curl->srvtag*/NULL);
  if (!err)
    {
      fp = http_get_write_ptr (http);
      /* Avoid caches to get the most recent copy of the key.  We set
         both the Pragma and Cache-Control versions of the header, so
         we're good with both HTTP 1.0 and 1.1.  */
      es_fputs ("Pragma: no-cache\r\n"
                "Cache-Control: no-cache\r\n", fp);
      http_start_data (http);
      if (es_ferror (fp))
        err = gpg_error_from_syserror ();
    }
  if (err)
    {
      /* Fixme: After a redirection we show the old host name.  */
      log_error (_("error connecting to '%s': %s\n"),
                 url, gpg_strerror (err));
      goto leave;
    }

  /* Wait for the response.  */
  dirmngr_tick (ctrl);
  err = http_wait_response (http);
  if (err)
    {
      log_error (_("error reading HTTP response for '%s': %s\n"),
                 url, gpg_strerror (err));
      goto leave;
    }

  switch (http_get_status_code (http))
    {
    case 200:
      err = 0;
      break; /* Success.  */

    case 301:
    case 302:
    case 307:
      {
        const char *s = http_get_header (http, "Location");

        log_info (_("URL '%s' redirected to '%s' (%u)\n"),
                  url, s?s:"[none]", http_get_status_code (http));
        if (s && *s && redirects_left-- )
          {
            xfree (request_buffer);
            request_buffer = xtrystrdup (s);
            if (request_buffer)
              {
                url = request_buffer;
                http_close (http, 0);
                http = NULL;
                goto once_more;
              }
            err = gpg_error_from_syserror ();
          }
        else
          err = gpg_error (GPG_ERR_NO_DATA);
        log_error (_("too many redirections\n"));
      }
      goto leave;

    default:
      log_error (_("error accessing '%s': http status %u\n"),
                 url, http_get_status_code (http));
      err = gpg_error (GPG_ERR_NO_DATA);
      goto leave;
    }

  fp = http_get_read_ptr (http);
  if (!fp)
    {
      err = gpg_error (GPG_ERR_BUG);
      goto leave;
    }

  /* Return the read stream and close the HTTP context.  */
  *r_fp = fp;
  http_close (http, 1);
  http = NULL;

 leave:
  http_close (http, 0);
  http_session_release (session);
  xfree (request_buffer);
  return err;
}
Exemple #24
0
int main(int argc, char *argv[])
{
    char *url;
    char data[1024], response[4096];
    int  i, ret, size;

    HTTP_INFO hi1, hi2;


    // Init http session. verify: check the server CA cert.
    http_init(&hi1, FALSE);
    http_init(&hi2, TRUE);

/*
    url = "https://localhost:8080/upload";
    sprintf(data,
            "--1234567890abcdef\r\n"
            "Content-Disposition: form-data; name=\"upload\"; filename=\"test.txt\"\r\n"
            "Content-Type: text/plain\r\n\r\n"
            "test message\r\n"
            "--1234567890abcdef--\r\n\r\n"
    );

    ret = http_post(&hi1, url, data, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);
*/

    url = "https://localhost:8080/upload";

    if(http_open(&hi1, url) < 0)
    {
        http_strerror(data, 1024);
        printf("socket error: %s \n", data);

        goto error;
    }

    snprintf(hi1.request.method, 8, "POST");
    hi1.request.close = FALSE;
    hi1.request.chunked = FALSE;
    snprintf(hi1.request.content_type, 256, "multipart/form-data; boundary=1234567890abcdef");

    size = sprintf(data,
                   "--1234567890abcdef\r\n"
                   "Content-Disposition: form-data; name=\"upload\"; filename=\"test.txt\"\r\n"
                   "Content-Type: text/plain\r\n\r\n"
                   "test message\r\n"
                   "--1234567890abcdef--\r\n"
                   );

    hi1.request.content_length = size;

    if(http_write_header(&hi1) < 0)
    {
        http_strerror(data, 1024);
        printf("socket error: %s \n", data);

        goto error;
    }

    if(http_write(&hi1, data, size) != size)
    {
        http_strerror(data, 1024);
        printf("socket error: %s \n", data);

        goto error;
    }

    // Write end-chunked
    if(http_write_end(&hi1) < 0)
    {
        http_strerror(data, 1024);
        printf("socket error: %s \n", data);

        goto error;
    }

    ret = http_read_chunked(&hi1, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);


/*
    // Test a http get method.
    url = "http://httpbin.org/get?message=https_client";

    ret = http_get(&hi1, url, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);

    // Test a http post method.

    url = "http://httpbin.org/post";
    sprintf(data, "{\"message\":\"Hello, https_client!\"}");

    ret = http_post(&hi1, url, data, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);

    // Test a https get method.

    url = "https://httpbin.org/get?message=https_client";

    ret = http_get(&hi2, url, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);

    // Test a https post method.

    url = "https://httpbin.org/post";
    sprintf(data, "{\"message\":\"Hello, https_client!\"}");

    ret = http_post(&hi2, url, data, response, sizeof(response));

    printf("return code: %d \n", ret);
    printf("return body: %s \n", response);

    // Test a https post with the chunked-encoding data.

    url = "https://httpbin.org/post";

    if(http_open_chunked(&hi2, url) == 0)
    {
        size = sprintf(data, "[{\"message\":\"Hello, https_client %d\"},", 0);

        if(http_write_chunked(&hi2, data, size) != size)
        {
            http_strerror(data, 1024);
            printf("socket error: %s \n", data);

            goto error;
        }

        for(i=1; i<4; i++)
        {
            size = sprintf(data, "{\"message\":\"Hello, https_client %d\"},", i);
            if(http_write_chunked(&hi2, data, size) != size)
            {
                http_strerror(data, 1024);
                printf("socket error: %s \n", data);

                goto error;
            }
        }

        size = sprintf(data, "{\"message\":\"Hello, https_client %d\"}]", i);
        if(http_write_chunked(&hi2, data, strlen(data)) != size)
        {
            http_strerror(data, 1024);
            printf("socket error: %s \n", data);

            goto error;
        }

        ret = http_read_chunked(&hi2, response, sizeof(response));

        printf("return code: %d \n", ret);
        printf("return body: %s \n", response);

    }
    else
    {
        http_strerror(data, 1024);
        printf("socket error: %s \n", data);
    }

    error:
*/

error:

    http_close(&hi1);
    http_close(&hi2);

    return 0;
}
Exemple #25
0
static void http_recv(slimaudio_t *audio) {
	char buf[AUDIO_CHUNK_SIZE];
	struct timeval timeOut; 
	int n;
	
	fd_set fdread;
	u32_t decode_num_tracks_started;
	u32_t autostart_threshold;

	timeOut.tv_sec  = 0; 
	timeOut.tv_usec = 100*1000; /* wait for up to 100ms */

	FD_ZERO(&fdread); 
	FD_SET(audio->streamfd, &fdread);  

	if (select(audio->streamfd + 1, &fdread, NULL, &fdread, &timeOut) == 0)
	{
		return;
	}

	while (slimaudio_buffer_available(audio->output_buffer) < AUDIO_CHUNK_SIZE * 2 &&
		slimaudio_buffer_available(audio->decoder_buffer) >= AUDIO_CHUNK_SIZE * 8)
	{
		DEBUGF("http_recv: output_buffer %i below %i\n",
				slimaudio_buffer_available(audio->output_buffer), AUDIO_CHUNK_SIZE * 2);
		DEBUGF("http_recv: output_decoder_available %i above %i\n",
				slimaudio_buffer_available(audio->decoder_buffer), AUDIO_CHUNK_SIZE * 8);
		sched_yield();
	}

	n = recv(audio->streamfd, buf, AUDIO_CHUNK_SIZE, 0);

	/* n == 0 http stream closed by server */
	if (n <= 0)
	{
		DEBUGF("http_recv: (2) n=%i msg=%s(%i)\n", n, strerror(SOCKETERROR), SOCKETERROR);
		http_close(audio);
		return;
	}

	VDEBUGF("http_recv: audio n=%i\n", n);

	slimaudio_buffer_write(audio->decoder_buffer, buf, n);

	pthread_mutex_lock(&audio->output_mutex);
	decode_num_tracks_started = audio->decode_num_tracks_started;
	pthread_mutex_unlock(&audio->output_mutex);

	pthread_mutex_lock(&audio->http_mutex);
	
	audio->http_total_bytes += n;
	audio->http_stream_bytes += n;

	autostart_threshold = audio->autostart_threshold;

	if ( !decode_num_tracks_started )
	{
		switch ( audio->autostart_mode )
		{
			case '1': /* Modify threshold for autostart modes, and not sync modes */
			case '3':
				switch (audio->decoder_mode)
				{
					case 'o':
					case 'm':
						if (threshold_override)
							autostart_threshold = 40000L;
						break;
					default:
						break;
				}
				break;
			default:
				break;
		}
	}

	VDEBUGF("http_recv: decode_num_tracks_started %u decode_bytes_available %u\n",
		decode_num_tracks_started, audio->http_stream_bytes );

	if ( ( !audio->autostart_threshold_reached ) && ( audio->http_stream_bytes >= autostart_threshold ) )
	{
		audio->autostart_threshold_reached = true;

		switch ( audio->autostart_mode )
		{
			case '0':
			case '2':
				DEBUGF("http_recv: AUTOSTART mode %c at %u threshold %u\n",
					audio->autostart_mode, audio->http_stream_bytes, autostart_threshold);

				slimaudio_stat(audio, "STMl", (u32_t) 0);

				pthread_mutex_unlock(&audio->http_mutex);
				pthread_cond_broadcast(&audio->http_cond);

				break;

			case '1':
			case '3':
				DEBUGF("http_recv: AUTOSTART mode %c at %u threshold %u\n",
					audio->autostart_mode, audio->http_stream_bytes, autostart_threshold);

				pthread_mutex_unlock(&audio->http_mutex);
				pthread_cond_broadcast(&audio->http_cond);

				slimaudio_output_unpause(audio);
				break;

			default:
				break;
		}


	}
	else
	{
		pthread_mutex_unlock(&audio->http_mutex);
		pthread_cond_broadcast(&audio->http_cond);
	}
}
Exemple #26
0
//response static resource
void http_response_static_proc( httpHeader* reqHeader )
{
	int len, cllen , ctlen ;
	char path[1024] = {0};
	header_out_t  header_out;
	memset( &header_out , 0 , sizeof( header_out ));
	header_out.req = reqHeader;

	get_file_path( reqHeader->uri , path );
	struct stat stat_file;
	int ret =  stat( path , &stat_file );

	if ( ret < 0 )
	{
		//printf( "not found page=%s \n" , path );
		resp_error_page( &header_out , 404 );
		return;
	}

	create_common_header( &header_out , 200 );
	header_append_length( &header_out , stat_file.st_size );
	resp_append_header( &header_out , HEADER_END_LINE );

	int nwritten = write( reqHeader->connfd , header_out.data , header_out.length );
	if (nwritten <= 0)
	{
		printf( "I/O error writing to client connfd=%d,len=%d: %s \n", reqHeader->connfd , header_out.length , strerror(errno));
		return;
	}

	int fd = open( path , O_RDONLY );
	if ( fd < 0 )
	{
		printf( "Open file Error:%s,errno=%d \n" , strerror(errno) , errno );
		return;
	}
    //优化
	//setsockopt (fd, SOL_TCP, TCP_CORK, &on, sizeof (on));
	off_t offset = 0;
	int force_close = 0;
	while ( offset < stat_file.st_size  )
	{
		int sendn = sendfile( reqHeader->connfd , fd , &offset , stat_file.st_size - offset );
		if ( sendn < 0 )
		{
			//如果socket缓冲区不可用,则挂起等待可用
			if (errno == EAGAIN || errno == EINTR  )
			{
				if( anetHandup(  reqHeader->connfd , 1000 , AE_WRITABLE ) < 0 )
				{
					//如果超时,退出
					printf( "Sendfile anetHandup timeout.......\n" );
					force_close = 1;
					break;
				}
				else
				{
					//否则继续发送
					continue;
				}
			}
			else
			{
				break;
			}
		}
		//printf( "Response uri=%s, connfd=%d,len=%d,send=%d \n", reqHeader->uri , reqHeader->connfd ,stat_file.st_size  , sendn );
	}
	close( fd );
	http_close( reqHeader , force_close );
}
Exemple #27
0
unsigned int http_sendfile(unsigned int idx, const char *name, unsigned char *tx)
{
  unsigned int len=0, i;

  if(name) //start transfer -> add http header
  {
    http_table[idx].status = HTTP_SEND;
    http_table[idx].file   = http_fid(name, &http_table[idx].fparam);
    http_table[idx].ftype  = http_ftype(http_table[idx].file);
    http_table[idx].flen   = http_flen(http_table[idx].file, http_table[idx].fparam);
    http_table[idx].fpos   = 0;
    http_table[idx].fparse = 0;

    if(http_table[idx].flen == 0) //file not found
    {
      http_table[idx].status = HTTP_CLOSED;
      len = sprintf((char*)tx, HTTP_404_HEADER"Error 404 Not found\r\n\r\n");
      tcp_send(idx, len, 0);
      tcp_close(idx);
      return len;
    }
    else //file found -> send http header
    {
      switch(http_table[idx].ftype)
      {
        case HTML_FILE:
          len = sprintf((char*)tx, HTTP_HTML_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case XML_FILE:
          len = sprintf((char*)tx, HTTP_XML_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case JS_FILE:
          len = sprintf((char*)tx, HTTP_JS_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case CSS_FILE:
          len = sprintf((char*)tx, HTTP_CSS_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case TXT_FILE:
          len = sprintf((char*)tx, HTTP_TXT_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case ICON_FILE:
          len = sprintf((char*)tx, HTTP_ICON_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case GIF_FILE:
          len = sprintf((char*)tx, HTTP_GIF_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
        case JPEG_FILE:
          len = sprintf((char*)tx, HTTP_JPEG_HEADER"%i\r\n\r\n", http_table[idx].flen);
          tx += len;
          break;
      }
    }
  }

  if(http_table[idx].flen) //file found
  {
    switch(http_table[idx].ftype)
    {
      //dynamic content
      case HTML_FILE:
      case XML_FILE:
        i = http_fparse((char*)tx, http_table[idx].file, &http_table[idx].fparse, (ETH_MTUSIZE-IP_HEADERLEN-TCP_HEADERLEN-MAX_ADDR-100), http_table[idx].fparam);
        http_table[idx].fpos += i;
        len += i;
        break;
      //static content
      case JS_FILE:
      case CSS_FILE:
      case TXT_FILE:
      case ICON_FILE:
      case GIF_FILE:
      case JPEG_FILE:
        i = http_fdata(tx, http_table[idx].file, http_table[idx].fpos, (ETH_MTUSIZE-IP_HEADERLEN-TCP_HEADERLEN-MAX_ADDR-100));
        http_table[idx].fpos += i;
        len += i;
        break;
    }
    tcp_send(idx, len, 0);
    if((http_table[idx].fpos >= http_table[idx].flen) || (len == 0))
    {
      http_close(idx);
      tcp_close(idx);
    }
  }

  return len;
}
/** Process an incoming request
	@returns nothing
 **/
void http_response(SOCKET fd)
{
	HTTP *http = http_create(fd);
	size_t len;
	int content_length = 0;
	char *user_agent = NULL;
	char *host = NULL;
	int keep_alive = 0;
	char *connection = NULL;
	char *accept = NULL;
	struct s_map {
		char *name;
		enum {INTEGER,STRING} type;
		void *value;
		size_t sz;
	} map[] = {
		{"Content-Length", INTEGER, (void*)&content_length, 0},
		{"Host", STRING, (void*)&host, 0},
		{"Keep-Alive", INTEGER, (void*)&keep_alive, 0},
		{"Connection", STRING, (void*)&connection, 0},
		{"Accept", STRING, (void*)&accept, 0},
	};

	while ( (int)(len=recv_data(fd,http->query,sizeof(http->query)))>0 )
	{
		/* first term is always the request */
		char *request = http->query;
		char method[32];
		char uri[1024];
		char version[32];
		char *p = strchr(http->query,'\r');
		int v;
		
		/* initialize the response */
		http_reset(http);

		/* read the request string */
		if (sscanf(request,"%s %s %s",method,uri,version)!=3)
		{
			http_status(http,HTTP_BADREQUEST);
			http_format(http,HTTP_BADREQUEST);
			http_type(http,"text/html");
			http_send(http);
			break;
		}

		/* read the rest of the header */
		while (p!=NULL && (p=strchr(p,'\r'))!=NULL) 
		{
 			*p = '\0';
			p+=2;
			for ( v=0 ; v<sizeof(map)/sizeof(map[0]) ; v++ )
			{
				if (map[v].sz==0) map[v].sz = strlen(map[v].name);
				if (strnicmp(map[v].name,p,map[v].sz)==0 && strncmp(p+map[v].sz,": ",2)==0)
				{
					if (map[v].type==INTEGER) { *(int*)(map[v].value) = atoi(p+map[v].sz+2); break; }
					else if (map[v].type==STRING) { *(char**)map[v].value = p+map[v].sz+2; break; }
				}
			}
		}
		output_verbose("%s (host='%s', len=%d)",http->query,host?host:"???",content_length);

		/* reject anything but a GET */
		if (stricmp(method,"GET")!=0)
		{
			http_status(http,HTTP_METHODNOTALLOWED);
			http_format(http,HTTP_METHODNOTALLOWED);
			http_type(http,"text/html");
			/* technically, we should add an Allow entry to the response header */
			http_send(http);
			break;
		}

		/* handle request */
		if ( strcmp(uri,"/favicon.ico")==0 )
		{
			if ( http_favicon(http) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else {
			static struct s_map {
				char *path;
				int (*request)(HTTP*,char*);
				char *success;
				char *failure;
			} map[] = {
				/* this is the map of recognize request types */
				{"/xml/",		http_xml_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/gui/",		http_gui_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/output/",	http_output_request,	HTTP_OK, HTTP_NOTFOUND},
				{"/action/",	http_action_request,	HTTP_ACCEPTED,HTTP_NOTFOUND},
				{"/rt/",		http_get_rt,			HTTP_OK, HTTP_NOTFOUND},
				{"/perl/",		http_run_perl,			HTTP_OK, HTTP_NOTFOUND},
				{"/gnuplot/",	http_run_gnuplot,		HTTP_OK, HTTP_NOTFOUND},
				{"/java/",		http_run_java,			HTTP_OK, HTTP_NOTFOUND},
				{"/python/",	http_run_python,		HTTP_OK, HTTP_NOTFOUND},
				{"/r/",			http_run_r,				HTTP_OK, HTTP_NOTFOUND},
				{"/scilab/",	http_run_scilab,		HTTP_OK, HTTP_NOTFOUND},
				{"/octave/",	http_run_octave,		HTTP_OK, HTTP_NOTFOUND},
			};
			int n;
			for ( n=0 ; n<sizeof(map)/sizeof(map[0]) ; n++ )
			{
				size_t len = strlen(map[n].path);
				if (strncmp(uri,map[n].path,len)==0)
				{
					if ( map[n].request(http,uri+len) )
						http_status(http,map[n].success);
					else
						http_status(http,map[n].failure);
					http_send(http);
					goto Next;
				}
			}
		}
		/* deprecated XML usage */
		if (strncmp(uri,"/",1)==0 )
		{
			if ( http_xml_request(http,uri+1) )
			{	
				output_warning("deprecate XML usage in request '%s'", uri);
				http_status(http,HTTP_OK);
			}
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else 
		{
			http_status(http,HTTP_NOTFOUND);
			http_format(http,HTTP_NOTFOUND);
			http_type(http,"text/html");
			http_send(http);
		}

		/* keep-alive not desired*/
Next:
		if (connection && stricmp(connection,"close")==0)
			break;
	}
	http_close(http);
	output_verbose("socket %d closed",http->s);
}
Exemple #29
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  gpg_error_t err;
  int rc;
  parsed_uri_t uri;
  uri_tuple_t r;
  http_t hd;
  int c;
  unsigned int my_http_flags = 0;
  int no_out = 0;
  int tls_dbg = 0;
  const char *cafile = NULL;
  http_session_t session = NULL;

  gpgrt_init ();
  log_set_prefix (PGM, 1 | 4);
  if (argc)
    { argc--; argv++; }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: " PGM " URL\n"
                 "Options:\n"
                 "  --verbose         print timings etc.\n"
                 "  --debug           flyswatter\n"
                 "  --gnutls-debug N  use GNUTLS debug level N\n"
                 "  --cacert FNAME    expect CA certificate in file FNAME\n"
                 "  --no-verify       do not verify the certificate\n"
                 "  --force-tls       use HTTP_FLAG_FORCE_TLS\n"
                 "  --no-out          do not print the content\n",
                 stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose += 2;
          debug++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--gnutls-debug"))
        {
          argc--; argv++;
          if (argc)
            {
              tls_dbg = atoi (*argv);
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--cacert"))
        {
          argc--; argv++;
          if (argc)
            {
              cafile = *argv;
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--no-verify"))
        {
          no_verify = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force-tls"))
        {
          my_http_flags |= HTTP_FLAG_FORCE_TLS;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-out"))
        {
          no_out = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        {
          fprintf (stderr, PGM ": unknown option '%s'\n", *argv);
          exit (1);
        }
    }
  if (argc != 1)
    {
      fprintf (stderr, PGM ": no or too many URLS given\n");
      exit (1);
    }

  if (!cafile)
    cafile = prepend_srcdir ("tls-ca.pem");

#if HTTP_USE_NTBTLS

  (void)err;

  ntbtls_set_debug (tls_dbg, NULL, NULL);

#elif HTTP_USE_GNUTLS

  rc = gnutls_global_init ();
  if (rc)
    log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));

  http_register_tls_callback (verify_callback);
  http_register_tls_ca (cafile);

  err = http_session_new (&session, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));

  /* rc = gnutls_dh_params_init(&dh_params); */
  /* if (rc) */
  /*   log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */
  /* read_dh_params ("dh_param.pem"); */

  /* rc = gnutls_certificate_set_x509_trust_file */
  /*   (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */
  /* if (rc) */
  /*   log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */
  /*              gnutls_strerror (rc)); */

  /* gnutls_certificate_set_dh_params (certcred, dh_params); */

  gnutls_global_set_log_function (my_gnutls_log);
  if (tls_dbg)
    gnutls_global_set_log_level (tls_dbg);

#endif /*HTTP_USE_GNUTLS*/

  rc = http_parse_uri (&uri, *argv, 1);
  if (rc)
    {
      log_error ("'%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }

  printf ("Scheme: %s\n", uri->scheme);
  if (uri->opaque)
    printf ("Value : %s\n", uri->path);
  else
    {
      printf ("Auth  : %s\n", uri->auth? uri->auth:"[none]");
      printf ("Host  : %s\n", uri->host);
      printf ("Port  : %u\n", uri->port);
      printf ("Path  : %s\n", uri->path);
      for (r = uri->params; r; r = r->next)
        {
          printf ("Params: %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      for (r = uri->query; r; r = r->next)
        {
          printf ("Query : %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      printf ("TLS   : %s\n",
              uri->use_tls? "yes":
              (my_http_flags&HTTP_FLAG_FORCE_TLS)? "forced" : "no");

    }
  fflush (stdout);
  http_release_parsed_uri (uri);
  uri = NULL;

  rc = http_open_document (&hd, *argv, NULL, my_http_flags,
                           NULL, session, NULL, NULL);
  if (rc)
    {
      log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }
  log_info ("open_http_document succeeded; status=%u\n",
            http_get_status_code (hd));

  {
    const char **names;
    int i;

    names = http_get_header_names (hd);
    if (!names)
      log_fatal ("http_get_header_names failed: %s\n",
                 gpg_strerror (gpg_error_from_syserror ()));
    for (i = 0; names[i]; i++)
      printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i]));
    xfree (names);
  }
  fflush (stdout);

  switch (http_get_status_code (hd))
    {
    case 200:
    case 400:
    case 401:
    case 403:
    case 404:
      {
        unsigned long count = 0;
        while ((c = es_getc (http_get_read_ptr (hd))) != EOF)
          {
            count++;
            if (!no_out)
              putchar (c);
          }
        log_info ("Received bytes: %lu\n", count);
      }
      break;
    case 301:
    case 302:
    case 307:
      log_info ("Redirected to: %s\n", http_get_header (hd, "Location"));
      break;
    }
  http_close (hd, 0);

  http_session_release (session);
#ifdef HTTP_USE_GNUTLS
  gnutls_global_deinit ();
#endif /*HTTP_USE_GNUTLS*/

  return 0;
}
Exemple #30
0
SANE_Status bb_start_scan(struct ledm_session *ps)
{
  char buf[4096] = {0};
  char buf1[1024]={0};
  int len, bytes_read, paper_status;
  int i, timeout = 10 ;
  char szPage_ID[5] = {0};
  char szJob_ID[5] = {0};
  SANE_Status stat = SANE_STATUS_IO_ERROR;
  struct bb_ledm_session *pbb = ps->bb_session;
  
  ps->user_cancel = 0;
  _DBG("bb_start_scan() entering...job_id=%d\n", ps->job_id);
  if (ps->job_id == 0)
  {
    if(http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
    {
        _BUG("unable to open channel HPMUD_S_LEDM_SCAN \n");
        goto bugout;
    }

    if (http_write(pbb->http_handle, GET_SCANNER_STATUS, sizeof(GET_SCANNER_STATUS)-1, timeout) != HTTP_R_OK)
    {
       _BUG("unable to GET_SCANNER_STATUS \n");
       goto bugout;
    }
 
    read_http_payload(ps, buf, sizeof(buf), timeout, &bytes_read);
     
    if(!strstr(buf, SCANNER_IDLE)) 
    {
        stat = SANE_STATUS_DEVICE_BUSY;
        goto bugout;
    }

    http_close(pbb->http_handle);
  	pbb->http_handle = 0;

    if(http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
    {
        _BUG("unable to open channel HPMUD_S_LEDM_SCAN \n");
        goto bugout;
    }

    len = snprintf(buf, sizeof(buf), CREATE_SCAN_JOB_REQUEST,
        ps->currentResolution,//<XResolution>
        ps->currentResolution,//<YResolution>
        (int) (ps->currentTlx / 5548.7133),//<XStart>
        (int) ((ps->currentBrx / 5548.7133) - (ps->currentTlx / 5548.7133)),//<Width>
        (int) (ps->currentTly / 5548.7133),//<YStart>
        (int) ((ps->currentBry / 5548.7133) - (ps->currentTly / 5548.7133)),//<Height>
        "Jpeg",//<Format>
        (! strcmp(ce_element[ps->currentScanMode], "Color8")) ? "Color" : (! strcmp(ce_element[ps->currentScanMode], "Gray8")) ? "Gray" : "Gray",//<ColorSpace>
        ((! strcmp(ce_element[ps->currentScanMode], "Color8")) || (! strcmp(ce_element[ps->currentScanMode], "Gray8"))) ? 8: 8,//<BitDepth>
        ps->currentInputSource == IS_PLATEN ? is_element[1] : is_element[2],//<InputSource>
        ps->currentInputSource == IS_PLATEN ? is_element[1] : is_element[2],//<InputSourceType>
        ps->currentInputSource != IS_ADF_DUPLEX ? "" : "<AdfOptions><AdfOption>Duplex</AdfOption></AdfOptions>",
        (int)ps->currentBrightness,//<Brightness>
        (int)ps->currentContrast);//<Contrast>

    len = len + strlen(ZERO_FOOTER);

    len = snprintf(buf1, sizeof(buf1), POST_HEADER, len);
    if (http_write(pbb->http_handle, buf1, strlen(buf1), timeout) != HTTP_R_OK)
    {
        //goto bugout;
    }
    
    if (http_write(pbb->http_handle, buf, strlen(buf), 1) != HTTP_R_OK)
    {
        //goto bugout;
    }

    /* Write zero footer. */
    if (http_write(pbb->http_handle, ZERO_FOOTER, sizeof(ZERO_FOOTER)-1, 1) != HTTP_R_OK)
    {
        //goto bugout;
    }
    memset(buf, 0, sizeof(buf));
    /* Read response. */
    if (read_http_payload(ps, buf, sizeof(buf), timeout, &bytes_read))
       goto bugout;

    http_close(pbb->http_handle);
    pbb->http_handle = 0;

    char joblist[64];
    char* jl=strstr(buf, "Location:");
    if (!jl) goto bugout;
    jl=jl+10;
	
    int i=0;
    while(*jl != '\r')
    { 
      joblist[i]=*jl; 
      jl=jl+1; i++;
    } 
    joblist[i]='\0';

    strcpy(ps->url, joblist);
    char *c=ps->url;
    c=strstr(c, "JobList"); 
    if (c)
    {
      c=c+8;
      int job_id=strtol(c, NULL, 10);
      itoa(job_id, szJob_ID,10);
      itoa(1, szPage_ID,10);
      ps->page_id = 1;
      ps->job_id = job_id;
    }
  }
  else
  {
    if (ps->currentInputSource == IS_PLATEN)
    {
       stat = SANE_STATUS_INVAL;
       goto bugout;
    }

    ps->page_id++;
    itoa(ps->job_id,szJob_ID,10);
    itoa(ps->page_id, szPage_ID,10);
  }
  _DBG("bb_start_scan() url=%s page_id=%d\n", ps->url, ps->page_id);
  
  memset(buf, 0, sizeof(buf)-1);

  if(http_open(ps->dd, HPMUD_S_LEDM_SCAN, &pbb->http_handle) != HTTP_R_OK)
  {
      _BUG("unable to open channel HPMUD_S_LEDM_SCAN \n");
      goto bugout;
  }
  while(strstr(buf, READY_TO_UPLOAD) == NULL)
  {
     _DBG("bb_start_scan() ENTERING....buf=%s\n", buf);
     len = snprintf(buf, sizeof(buf), GET_SCAN_JOB_URL, ps->url);

     if (http_write(pbb->http_handle, buf, strlen(buf), 1) != HTTP_R_OK)
     {
        //goto bugout;
        break ;
     }
     if (read_http_payload (ps, buf, sizeof(buf), 5, &len) != HTTP_R_OK)
     {
        //goto bugout
        _DBG("bb_start_scan() read_http_payload FAILED len=%d buf=%s\n", len, buf);
        break;
     }
      //For a new scan, buf must contain <PreScanPage>. 
     if (NULL == strstr(buf,PRESCANPAGE)) 
     {         //i.e Paper is not present in Scanner
         stat = SANE_STATUS_NO_DOCS;
         goto bugout;
     }
     if (strstr(buf,JOBSTATE_CANCELED) || strstr(buf, CANCELED_BY_DEVICE) || strstr(buf, CANCELED_BY_CLIENT))
     {
        _DBG("bb_start_scan() SCAN CANCELLED\n");
        stat = SANE_STATUS_GOOD;
        ps->user_cancel = 1;
        goto bugout;
     }
     if (strstr(buf, JOBSTATE_COMPLETED))
     {
        stat = SANE_STATUS_GOOD;
        goto bugout;
     }
     usleep(500000);//0.5 sec delay
  }//end while()

  char *c = strstr(buf, "<BinaryURL>");
  _DBG("bb_start_scan() BinaryURL=%s \n", c);
  
  if (!c) goto bugout;
  c +=11;
  char BinaryURL[30];
  i = 0;
  while(*c != '<')
  {
     BinaryURL[i++] = *c ;
     c++;
  }
  BinaryURL[i] = '\0';
  //_DBG("bb_start_scan() BinaryURL=%s\n", BinaryURL);
  len = snprintf(buf, sizeof(buf), GET_SCAN_JOB_URL, BinaryURL);
 
  if (http_write(pbb->http_handle, buf, strlen(buf), timeout) != HTTP_R_OK)
  {
 	//goto bugout;
  }
 
  if (http_read_header(pbb->http_handle, buf, sizeof(buf), timeout, &len) != HTTP_R_OK)
  {
	 //goto bugout;
  }

  if(strstr(buf, "HTTP/1.1 400 Bad Request")) http_read_header(pbb->http_handle, buf, sizeof(buf), timeout, &len);
  
  stat = SANE_STATUS_GOOD;
bugout:
  if (stat && pbb->http_handle)
  {
    http_close(pbb->http_handle);   /* error, close http connection */
    pbb->http_handle = 0;
  }
  return stat;
} /* bb_start_scan */