Example #1
0
static gboolean osm_delete_item(struct log_s *log, char *xml_str,
				char *url, char *user, proxy_t *proxy) {
  int retry = MAX_TRY;
  char buffer[CURL_ERROR_SIZE];

  CURL *curl;
  CURLcode res;

  /* delete has a payload since api 0.6 */
  curl_data_t read_data;
  curl_data_t write_data;

  while(retry >= 0) {

    if(retry != MAX_TRY)
      appendf(log, NULL, _("Retry %d/%d "), MAX_TRY-retry, MAX_TRY-1);

    /* get a curl handle */
    curl = curl_easy_init();
    if(!curl) {
      appendf(log, NULL, _("CURL init error\n"));
      return FALSE;
    }

    read_data.ptr = xml_str;
    read_data.len = xml_str?strlen(xml_str):0;
    write_data.ptr = NULL;
    write_data.len = 0;

    /* we want to use our own read/write functions */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

    curl_easy_setopt(curl, CURLOPT_INFILESIZE, (curl_off_t)read_data.len);

    /* now specify which file to upload */
    curl_easy_setopt(curl, CURLOPT_READDATA, &read_data);

    /* we pass our 'chunk' struct to the callback function */
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_data);

    /* enable uploading */
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

    /* no read/write functions required */
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");

    /* specify target URL, and note that this URL should include a file
       name, not only a directory */
    curl_easy_setopt(curl, CURLOPT_URL, url);

	curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    /* some servers don't like requests that are made without a user-agent
       field, so we provide one */
    curl_easy_setopt(curl, CURLOPT_USERAGENT, PACKAGE "-libcurl/" VERSION);

#ifdef NO_EXPECT
    struct curl_slist *slist = NULL;
    slist = curl_slist_append(slist, "Expect:");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
#endif

    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);

    /* set user name and password for the authentication */
    curl_easy_setopt(curl, CURLOPT_USERPWD, user);

    net_io_set_proxy(curl, proxy);

    /* Now run off and do what you've been told! */
    res = curl_easy_perform(curl);

    long response;
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);

    /* always cleanup */
#ifdef NO_EXPECT
    curl_slist_free_all(slist);
#endif
    curl_easy_cleanup(curl);

    if(res != 0)
      appendf(log, COLOR_ERR, _("failed: %s\n"), buffer);
    else if(response != 200)
      appendf(log, COLOR_ERR, _("failed, code: %ld %s\n"),
	      response, osm_http_message(response));
    else
      appendf(log, COLOR_OK, _("ok\n"));

    /* if it's neither "ok" (200), nor "internal server error" (500) */
    /* then write the message to the log */
    if((response != 200) && (response != 500) && write_data.ptr) {
      appendf(log, NULL, _("Server reply: "));
      appendf(log, COLOR_ERR, _("%s\n"), write_data.ptr);
    }

    g_free(write_data.ptr);

    /* don't retry unless we had an "internal server error" */
    if(response != 500)
      return((res == 0)&&(response == 200));

    retry--;
  }

  return FALSE;
}
/*
 * send a SCEP request via HTTP and wait for a response
 */
bool
scep_http_request(const char *url, chunk_t pkcs7, scep_op_t op
, fetch_request_t req_type, chunk_t *response)
{
#ifdef LIBCURL
    char errorbuffer[CURL_ERROR_SIZE] = "";
    char *complete_url = NULL;
    struct curl_slist *headers = NULL;
    CURL *curl;
    CURLcode res;

    /* initialize response */
    *response = empty_chunk;

    /* initialize curl context */
    curl = curl_easy_init();
    if (curl == NULL)
    {
	plog("could not initialize curl context");
	return FALSE;
    }

    if (op == SCEP_PKI_OPERATION)
    {
	const char operation[] = "PKIOperation";

	if (req_type == FETCH_GET)
	{
	    char *escaped_req = escape_http_request(pkcs7);

	    /* form complete url */
	    int len = strlen(url) + 20 + strlen(operation) + strlen(escaped_req) + 1;

	    complete_url = alloc_bytes(len, "complete url");
	    snprintf(complete_url, len, "%s?operation=%s&message=%s"
		    , url, operation, escaped_req);
	    pfreeany(escaped_req);

	    curl_easy_setopt(curl, CURLOPT_HTTPGET, TRUE);
	    headers = curl_slist_append(headers, "Pragma:");
	    headers = curl_slist_append(headers, "Host:");
	    headers = curl_slist_append(headers, "Accept:");
	    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
	    curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	}
	else /* HTTP_POST */
	{
	    /* form complete url */
	    int len = strlen(url) + 11 + strlen(operation) + 1;

	    complete_url = alloc_bytes(len, "complete url");
	    snprintf(complete_url, len, "%s?operation=%s", url, operation);

	    curl_easy_setopt(curl, CURLOPT_HTTPGET, FALSE);
	    headers = curl_slist_append(headers, "Content-Type:");
	    headers = curl_slist_append(headers, "Expect:");
	    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, pkcs7.ptr);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, pkcs7.len);
	}
    }
    else  /* SCEP_GET_CA_CERT */
    {
	const char operation[] = "GetCACert";

	/* form complete url */
	int len = strlen(url) + 32 + strlen(operation) + 1;

	complete_url = alloc_bytes(len, "complete url");
	snprintf(complete_url, len, "%s?operation=%s&message=CAIdentifier"
		, url, operation);

	curl_easy_setopt(curl, CURLOPT_HTTPGET, TRUE);
    }

    curl_easy_setopt(curl, CURLOPT_URL, complete_url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_buffer);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
    curl_easy_setopt(curl, CURLOPT_FAILONERROR, TRUE);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, FETCH_CMD_TIMEOUT);
	
    DBG(DBG_CONTROL,
	DBG_log("sending scep request to '%s'", url)
    )
    res = curl_easy_perform(curl);
	
    if (res == CURLE_OK)
    {
	DBG(DBG_CONTROL,
	    DBG_log("received scep response")
	)
	DBG(DBG_RAW,
	    DBG_dump_chunk("SCEP response:\n", *response)
	)
    }
    else
    {
	plog("failed to fetch scep response from '%s': %s", url, errorbuffer);
    }
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    pfreeany(complete_url);

    return (res == CURLE_OK);
#else   /* !LIBCURL */
    plog("scep error: pluto wasn't compiled with libcurl support");
    return FALSE;
#endif  /* !LIBCURL */
}
Example #3
0
/*
 * Upload a file
 * returns a basic status:
 *   < 0  : curl error
 *   == 0 : OK
 *   > 0  : HTTP error
  */
static gint osm_traces_upload_file(const char *user,
				   const char *password,
				   const char *file,
				   const char *filename,
				   const char *description,
				   const char *tags,
				   const OsmTraceVis_t *vistype)
{
  CURL *curl;
  CURLcode res;
  char curl_error_buffer[CURL_ERROR_SIZE];
  struct curl_slist *headers = NULL;
  struct curl_httppost *post=NULL;
  struct curl_httppost *last=NULL;

  char *base_url = "http://www.openstreetmap.org/api/0.6/gpx/create";

  gchar *user_pass = osm_get_login();

  gint result = 0; // Default to it worked!

  g_debug("%s: %s %s %s %s %s %s", __FUNCTION__,
  	  user, password, file, filename, description, tags);

  /* Init CURL */
  curl = curl_easy_init();

  /* Filling the form */
  curl_formadd(&post, &last,
               CURLFORM_COPYNAME, "description",
               CURLFORM_COPYCONTENTS, description, CURLFORM_END);
  curl_formadd(&post, &last,
               CURLFORM_COPYNAME, "tags",
               CURLFORM_COPYCONTENTS, tags, CURLFORM_END);
  curl_formadd(&post, &last,
               CURLFORM_COPYNAME, "visibility",
               CURLFORM_COPYCONTENTS, vistype->apistr, CURLFORM_END);
  curl_formadd(&post, &last,
               CURLFORM_COPYNAME, "file",
               CURLFORM_FILE, file,
               CURLFORM_FILENAME, filename,
	       CURLFORM_CONTENTTYPE, "text/xml", CURLFORM_END);

  /* Prepare request */
  /* As explained in http://wiki.openstreetmap.org/index.php/User:LA2 */
  /* Expect: header seems to produce incompatibilites between curl and httpd */
  headers = curl_slist_append(headers, "Expect: ");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
  curl_easy_setopt(curl, CURLOPT_URL, base_url);
  curl_easy_setopt(curl, CURLOPT_USERPWD, user_pass);
  curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_error_buffer);
  if (vik_verbose)
    curl_easy_setopt ( curl, CURLOPT_VERBOSE, 1 );

  /* Execute request */
  res = curl_easy_perform(curl);
  if (res == CURLE_OK)
  {
    long code;
    res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
    if (res == CURLE_OK)
    {
      g_debug("received valid curl response: %ld", code);
      if (code != 200) {
        g_warning(_("failed to upload data: HTTP response is %ld"), code);
	result = code;
      }
    }
    else {
      g_critical(_("curl_easy_getinfo failed: %d"), res);
      result = -1;
    }
  }
  else {
    g_warning(_("curl request failed: %s"), curl_error_buffer);
    result = -2;
  }

  /* Memory */
  g_free(user_pass); user_pass = NULL;
  
  curl_formfree(post);
  curl_easy_cleanup(curl);
  return result;
}
Example #4
0
void LLCurl::Easy::slist_append(const char* str)
{
	mHeaders = curl_slist_append(mHeaders, str);
}
Example #5
0
static ae_error_t http_network_send_data(CURL *curl, const char *req_msg, uint32_t msg_size, char **resp_msg, uint32_t& resp_size, http_methods_t method, bool is_ocsp)
{
    AESM_DBG_TRACE("send data method=%d",method);
    struct curl_slist *headers=NULL;
    struct curl_slist *tmp=NULL;
    ae_error_t ae_ret = AE_SUCCESS;
    CURLcode cc=CURLE_OK;
    int num_bytes = 0;
    if(is_ocsp){
        tmp = curl_slist_append(headers, "Accept: application/ocsp-response");
        if(tmp==NULL){
            AESM_DBG_ERROR("fail in add accept ocsp-response header");
            ae_ret = AE_FAILURE;
            goto fini;
        }
        headers = tmp;
        tmp = curl_slist_append(headers, "Content-Type: application/ocsp-request");
        if(tmp == NULL){
           AESM_DBG_ERROR("fail in add content type ocsp-request");
           ae_ret = AE_FAILURE;
           goto fini;
        }
        headers=tmp;
        AESM_DBG_TRACE("ocsp request");
    }
    char buf[50];
    num_bytes = snprintf(buf,sizeof(buf), "Content-Length: %u", (unsigned int)msg_size);
    if(num_bytes<0 || num_bytes>=sizeof(buf)){
         AESM_DBG_ERROR("fail to prepare string Content-Length");
         ae_ret = AE_FAILURE;
         goto fini;
    }
    tmp = curl_slist_append(headers, buf);
    if(tmp == NULL){
         AESM_DBG_ERROR("fail to add content-length header");
         ae_ret = AE_FAILURE;
         goto fini;
    }
    headers=tmp;
    if((cc=curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers))!=CURLE_OK){
        AESM_DBG_ERROR("fail to set http header:%d",(int)cc);
        ae_ret = AE_FAILURE;
        goto fini;
    }
    if(method == POST){
        if((cc=curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req_msg))!=CURLE_OK){
            AESM_DBG_ERROR("fail to set POST fields:%d",(int)cc);
            ae_ret = AE_FAILURE;
            goto fini;
        }
        if((cc=curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, msg_size))!=CURLE_OK){
            AESM_DBG_ERROR("fail to set POST fields size:%d",(int)cc);
            ae_ret = AE_FAILURE;
            goto fini;
        }
    }
    if((cc=curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback))!=CURLE_OK){
        AESM_DBG_ERROR("Fail to set callback function:%d",(int)cc);
        ae_ret = AE_FAILURE;
        goto fini;
    }

    network_malloc_info_t malloc_info;
    malloc_info.base=NULL;
    malloc_info.size = 0;
    if((cc=curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void *>(&malloc_info)))!=CURLE_OK){
       AESM_DBG_ERROR("fail to set write back function parameter:%d",(int)cc);
       ae_ret = AE_FAILURE;
       goto fini;
    }
    if((cc=curl_easy_perform(curl))!=CURLE_OK){
        if(malloc_info.base){
            free(malloc_info.base);
        }
        AESM_DBG_ERROR("fail in connect:%d",(int)cc);
        ae_ret = OAL_NETWORK_UNAVAILABLE_ERROR;
        goto fini;
    }
    *resp_msg = malloc_info.base;
    resp_size = malloc_info.size;
    AESM_DBG_TRACE("get response size=%d",resp_size);
    ae_ret = AE_SUCCESS;
fini:
    if(headers!=NULL){
        curl_slist_free_all(headers);
    }
    return ae_ret;
}
Example #6
0
int test(char *URL)
{
   CURLcode res;
   CURL *curl;
   char *newURL;
   struct curl_slist *slist;

   if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
     fprintf(stderr, "curl_global_init() failed\n");
     return TEST_ERR_MAJOR_BAD;
   }

   if ((curl = curl_easy_init()) == NULL) {
     fprintf(stderr, "curl_easy_init() failed\n");
     curl_global_cleanup();
     return TEST_ERR_MAJOR_BAD;
   }

   /*
    * Begin with cURL set to use a single CWD to the URL's directory.
    */
   curl_easy_setopt(curl, CURLOPT_URL, URL);
   curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
   curl_easy_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD);

   res = curl_easy_perform(curl);

   /*
    * Change the FTP_FILEMETHOD option to use full paths rather than a CWD
    * command.  Alter the URL's path a bit, appending a "./".  Use an innocuous
    * QUOTE command, after which cURL will CWD to ftp_conn->entrypath and then
    * (on the next call to ftp_statemach_act) find a non-zero ftpconn->dirdepth
    * even though no directories are stored in the ftpconn->dirs array (after a
    * call to freedirs).
    */
   newURL = malloc(strlen(URL) + 3);
   if (newURL == NULL) {
     curl_easy_cleanup(curl);
     curl_global_cleanup();
     return TEST_ERR_MAJOR_BAD;
   }
   newURL = strcat(strcpy(newURL, URL), "./");

   slist = curl_slist_append (NULL, "SYST");
   if (slist == NULL) {
     free(newURL);
     curl_easy_cleanup(curl);
     curl_global_cleanup();
     return TEST_ERR_MAJOR_BAD;
   }

   curl_easy_setopt(curl, CURLOPT_URL, newURL);
   curl_easy_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD);
   curl_easy_setopt(curl, CURLOPT_QUOTE, slist);

   res = curl_easy_perform(curl);

   curl_slist_free_all(slist);
   free(newURL);
   curl_easy_cleanup(curl);
   curl_global_cleanup();

   return (int)res;
}
Example #7
0
static int send_request(char *method, const char *path, FILE *fp, xmlParserCtxtPtr xmlctx, curl_slist *extra_headers)
{
  long response = -1;
  int tries = 0;

  // retry on failures
  for (tries = 0; tries < REQUEST_RETRIES; tries++)
  {
    CURL *curl = get_connection(path);
    curl_slist *headers = NULL;
    add_header(&headers, "X-Auth-Token", storage_token);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
    if (!strcasecmp(method, "MKDIR"))
    {
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
      add_header(&headers, "Content-Type", "application/directory");
    }
    else if (!strcasecmp(method, "PUT") && fp)
    {
      rewind(fp);
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size(fileno(fp)));
      curl_easy_setopt(curl, CURLOPT_READDATA, fp);
    }
    else if (!strcasecmp(method, "GET"))
    {
      if (fp)
      {
        rewind(fp); // make sure the file is ready for a-writin'
        fflush(fp);
        ftruncate(fileno(fp), 0);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
      }
      else if (xmlctx)
      {
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
      }
    }
    else
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
    /* add the headers from extra_headers if any */
    curl_slist *extra;
    for (extra = extra_headers; extra; extra = extra->next)
    {
      debugf("adding header: %s", extra->data);
      headers = curl_slist_append(headers, extra->data);
    }
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
    curl_slist_free_all(headers);
    return_connection(curl);
    if (response >= 200 && response < 400)
      return response;
    sleep(8 << tries); // backoff
    if (response == 401 && !cloudfs_connect(0, 0, 0, 0)) // re-authenticate on 401s
      return response;
    if (xmlctx)
      xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL);
  }
  return response;
}
static void * _sendHttpMessage()
{
   pthread_mutex_lock(&mutexHttpSendThreadControl);

  while (NULL != _httpMessageBeingSent)
  {
    // ---------------------------------------------------------------------------
    // Set the limit of the message to send
    // ---------------------------------------------------------------------------
    #ifdef X86
    curl_easy_setopt(_sessionHandle, CURLOPT_POSTFIELDSIZE_LARGE, strlen(_httpMessageBeingSent) );
    #else
    curl_easy_setopt(_sessionHandle, CURLOPT_POSTFIELDSIZE, strlen(_httpMessageBeingSent) );
    #endif
    
    // Set the relevant Content-type (No Content-type for 0 size data message)
    if(NULL != _slist) {
      // Free the list
      curl_slist_free_all(_slist); /* free the list - List used to define the HTTP Content Type */
      _slist=NULL;
    } 
    if(0 == strlen(_httpMessageBeingSent)) {
      DBG("Set empty HTTP Content-type");
      _slist = curl_slist_append(_slist, HttpEmptyContentType);
    } else {
      DBG("Set XML HTTP Content-type");
      _slist = curl_slist_append(_slist, HttpXmlContentType); 
    }
    curl_easy_setopt(_sessionHandle, CURLOPT_HTTPHEADER, _slist); 
    

    // ---------------------------------------------------------------------------
    // Fill the data to send
    // ---------------------------------------------------------------------------
    curl_easy_setopt( _sessionHandle, CURLOPT_POSTFIELDS, _httpMessageBeingSent );

    INFO("HTTP Message to send:\n%s", _httpMessageBeingSent);

    pthread_mutex_unlock(&mutexHttpSendThreadControl);

    if ( curl_easy_perform( _sessionHandle ) == 0 ) {
      INFO("HTTP Message sent");
    } else {
      WARN("HTTP Message Not Sent");
    }

    pthread_mutex_lock(&mutexHttpSendThreadControl);

    // Free and set to NULL the _httpMessageBeingSent
    DM_ENG_FREE(_httpMessageBeingSent);
    _httpMessageBeingSent = _getFirstPendingHttpMessage();

  }  // end if(NULL != _httpMessageBeingSent)

  if(_closeHttpSessionExpected)
  {
     _CloseHttpSession(NORMAL_CLOSE);
  }

  pthread_mutex_unlock(&mutexHttpSendThreadControl);

   // Quit the current thread
   pthread_exit(DM_OK);
}
Example #9
0
int main(void)
{
  CURL *curl;
  CURLM *mcurl;
  int still_running = 1;
  struct timeval mp_start;
  struct curl_slist *recipients = NULL;
  struct upload_status upload_ctx;

  upload_ctx.lines_read = 0;

  curl_global_init(CURL_GLOBAL_DEFAULT);

  curl = curl_easy_init();
  if(!curl)
    return 1;

  mcurl = curl_multi_init();
  if(!mcurl)
    return 2;

  /* This is the URL for your mailserver */
  curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com");

  /* Note that this option isn't strictly required, omitting it will result in
   * libcurl sending the MAIL FROM command with empty sender data. All
   * autoresponses should have an empty reverse-path, and should be directed
   * to the address in the reverse-path which triggered them. Otherwise, they
   * could cause an endless loop. See RFC 5321 Section 4.5.5 for more details.
   */
  curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);

  /* Add two recipients, in this particular case they correspond to the
   * To: and Cc: addressees in the header, but they could be any kind of
   * recipient. */
  recipients = curl_slist_append(recipients, TO);
  recipients = curl_slist_append(recipients, CC);
  curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

  /* We're using a callback function to specify the payload (the headers and
   * body of the message). You could just use the CURLOPT_READDATA option to
   * specify a FILE pointer to read from. */
  curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
  curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* Tell the multi stack about our easy handle */
  curl_multi_add_handle(mcurl, curl);

  /* Record the start time which we can use later */
  mp_start = tvnow();

  /* We start some action by calling perform right away */
  curl_multi_perform(mcurl, &still_running);

  while(still_running) {
    struct timeval timeout;
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;
    int maxfd = -1;
    int rc;
    CURLMcode mc; /* curl_multi_fdset() return code */

    long curl_timeo = -1;

    /* Initialise the file descriptors */
    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);

    /* Set a suitable timeout to play around with */
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    curl_multi_timeout(mcurl, &curl_timeo);
    if(curl_timeo >= 0) {
      timeout.tv_sec = curl_timeo / 1000;
      if(timeout.tv_sec > 1)
        timeout.tv_sec = 1;
      else
        timeout.tv_usec = (curl_timeo % 1000) * 1000;
    }

    /* get file descriptors from the transfers */
    mc = curl_multi_fdset(mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);

    if(mc != CURLM_OK) {
      fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
      break;
    }

    /* On success the value of maxfd is guaranteed to be >= -1. We call
       select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
       no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
       to sleep 100ms, which is the minimum suggested value in the
       curl_multi_fdset() doc. */

    if(maxfd == -1) {
#ifdef _WIN32
      Sleep(100);
      rc = 0;
#else
      /* Portable sleep for platforms other than Windows. */
      struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
      rc = select(0, NULL, NULL, NULL, &wait);
#endif
    }
    else {
      /* Note that on some platforms 'timeout' may be modified by select().
         If you need access to the original value save a copy beforehand. */
      rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
    }

    if(tvdiff(tvnow(), mp_start) > MULTI_PERFORM_HANG_TIMEOUT) {
      fprintf(stderr,
              "ABORTING: Since it seems that we would have run forever.\n");
      break;
    }

    switch(rc) {
    case -1:  /* select error */
      break;
    case 0:   /* timeout */
    default:  /* action */
      curl_multi_perform(mcurl, &still_running);
      break;
    }
  }

  /* Free the list of recipients */
  curl_slist_free_all(recipients);

  /* Always cleanup */
  curl_multi_remove_handle(mcurl, curl);
  curl_multi_cleanup(mcurl);
  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return 0;
}
Example #10
0
HttpResponse* HttpClient::post(const wstring& url) {
	CURLcode res;	

	struct MemoryStruct chunk; 
	chunk.memory = (char*) malloc(1);  /* will be grown as needed by the realloc above */ 
	chunk.size = 0;    /* no data at this point */

	if(curl) {
		curl_easy_setopt(curl, CURLOPT_URL, wide2char(url.c_str()));		
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(curl, CURLOPT_POST, 1L);

		/// HEADERS
		struct curl_slist *headerList = NULL;

		for(std::vector<std::wstring>::iterator it = headers.begin(); 
			it != headers.end();
			it++)
		{
			char* header;			
			header = wide2char(it->c_str());

			headerList = curl_slist_append(headerList, header);
		}

		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList);

		/* send all data to this function  */ 
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
 
		/* we pass our 'chunk' struct to the callback function */ 
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
 
		/* some servers don't like requests that are made without a user-agent
		field, so we provide one */ 
		curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
		
		struct curl_httppost* post = NULL;
		struct curl_httppost* last = NULL;

		
		wstring params;
		for(std::vector<std::pair<std::wstring, std::wstring>>::iterator it = formData.begin(); 
			it != formData.end();
			it++) {			
				//curl_formadd(&post, &last, CURLFORM_COPYNAME, wide2char(it->first.c_str()), CURLFORM_COPYCONTENTS, wide2char(it->second.c_str()), CURLFORM_END);
				params += it->first;
				params += L"=";
				params += it->second;
				params += L"&";
		}

		params = params.substr(0,params.length()-1);
					
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, wide2char(params.c_str()));		 
		//curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);

		/* Perform the request, res will get the return code */ 
		res = curl_easy_perform(curl);
		/* Check for errors */ 
		if(res != CURLE_OK) {
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		} else {
			// chunk has data!!
		}

		/* always cleanup */ 
		curl_easy_cleanup(curl);
	}
 
	curl_global_cleanup();
	HttpResponse* response = new HttpResponse();
	response->data = chunk;
	response->code = res;

	return response;
}
Example #11
0
int test(char *URL)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  FILE *hd_src ;
  int hd ;
  struct_stat file_info;
  struct curl_slist *hl;
  int error;

  struct curl_slist *headerlist=NULL;
  const char *buf_1 = "RNFR 505";
  const char *buf_2 = "RNTO 505-forreal";

  if (!libtest_arg2) {
    fprintf(stderr, "Usage: <url> <file-to-upload>\n");
    return -1;
  }

  /* get the file size of the local file */
  hd = stat(libtest_arg2, &file_info);
  if(hd == -1) {
    /* can't open file, bail out */
    error = ERRNO;
    fprintf(stderr, "stat() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "WARNING: cannot open file %s\n", libtest_arg2);
    return -1;
  }

  if(! file_info.st_size) {
    fprintf(stderr, "WARNING: file %s has no size!\n", libtest_arg2);
    return -4;
  }

  /* get a FILE * of the same file, could also be made with
     fdopen() from the previous descriptor, but hey this is just
     an example! */
  hd_src = fopen(libtest_arg2, "rb");
  if(NULL == hd_src) {
    error = ERRNO;
    fprintf(stderr, "fopen() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "Error opening file: %s\n", libtest_arg2);
    return -2; /* if this happens things are major weird */
  }

  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  /* get a curl handle */
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  /* build a list of commands to pass to libcurl */

  if ((hl = curl_slist_append(headerlist, buf_1)) == NULL) {
    fprintf(stderr, "curl_slist_append() failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }
  if ((headerlist = curl_slist_append(hl, buf_2)) == NULL) {
    fprintf(stderr, "curl_slist_append() failed\n");
    curl_slist_free_all(hl);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }
  headerlist = hl;

  /* enable uploading */
  test_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* enable verbose */
  test_setopt(curl, CURLOPT_VERBOSE, 1L);

  /* specify target */
  test_setopt(curl,CURLOPT_URL, URL);

  /* pass in that last of FTP commands to run after the transfer */
  test_setopt(curl, CURLOPT_POSTQUOTE, headerlist);

  /* now specify which file to upload */
  test_setopt(curl, CURLOPT_INFILE, hd_src);

  /* and give the size of the upload (optional) */
  test_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                   (curl_off_t)file_info.st_size);

  /* Now run off and do what you've been told! */
  res = curl_easy_perform(curl);

test_cleanup:

  /* clean up the FTP commands list */
  curl_slist_free_all(headerlist);

  /* close the local file */
  fclose(hd_src);

  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return res;
}
Example #12
0
HttpResponse* HttpClient::request(const wstring& url) {
	CURLcode res;	

	struct MemoryStruct chunk; 
	chunk.memory = (char*) malloc(1);  /* will be grown as needed by the realloc above */ 
	chunk.size = 0;    /* no data at this point */
	
	if(curl) {
		curl_easy_setopt(curl, CURLOPT_URL, wide2char(url.c_str()));
		
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);

		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

		/// HEADERS
		struct curl_slist *headerList = NULL;
 
		//headers = curl_slist_append(headers, "Authorization: OAuth ya29.AHES6ZSbVSgkJ89BmU0UlkqYGUtD979p35N1w8HD7JFm6w");
		//headers = curl_slist_append(headers, "Content-type: application/json");
		for(std::vector<std::wstring>::iterator it = headers.begin(); 
			it != headers.end();
			it++)
		{
			char* header;			
			//header = wide2char(&(*it->c_str()));
			header = wide2char(it->c_str());

			headerList = curl_slist_append(headerList, header);
		}

		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList);
		/// HEADERS

		/* send all data to this function  */ 
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
 
		/* we pass our 'chunk' struct to the callback function */ 
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
 
		/* some servers don't like requests that are made without a user-agent
		field, so we provide one */ 
		curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
		
		 /* Perform the request, res will get the return code */ 
		res = curl_easy_perform(curl);
		/* Check for errors */ 
		if(res != CURLE_OK) {
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		} else {
			// chunk has data!!
		}

		/* always cleanup */ 
		curl_easy_cleanup(curl);
	}
 
	curl_global_cleanup();
	HttpResponse* response = new HttpResponse();
	response->data = chunk;
	response->code = res;

	return response;
}
Example #13
0
int main(void)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  struct curl_slist *headers = NULL;
  struct curl_slist *recipients = NULL;
  struct curl_slist *slist = NULL;
  curl_mime *mime;
  curl_mime *alt;
  curl_mimepart *part;
  const char **cpp;

  curl = curl_easy_init();
  if(curl) {
    /* This is the URL for your mailserver */
    curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com");

    /* Note that this option isn't strictly required, omitting it will result
     * in libcurl sending the MAIL FROM command with empty sender data. All
     * autoresponses should have an empty reverse-path, and should be directed
     * to the address in the reverse-path which triggered them. Otherwise,
     * they could cause an endless loop. See RFC 5321 Section 4.5.5 for more
     * details.
     */
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);

    /* Add two recipients, in this particular case they correspond to the
     * To: and Cc: addressees in the header, but they could be any kind of
     * recipient. */
    recipients = curl_slist_append(recipients, TO);
    recipients = curl_slist_append(recipients, CC);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

    /* Build and set the message header list. */
    for(cpp = headers_text; *cpp; cpp++)
      headers = curl_slist_append(headers, *cpp);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    /* Build the mime message. */
    mime = curl_mime_init(curl);

    /* The inline part is an alternative proposing the html and the text
       versions of the e-mail. */
    alt = curl_mime_init(curl);

    /* HTML message. */
    part = curl_mime_addpart(alt);
    curl_mime_data(part, inline_html, CURL_ZERO_TERMINATED);
    curl_mime_type(part, "text/html");

    /* Text message. */
    part = curl_mime_addpart(alt);
    curl_mime_data(part, inline_text, CURL_ZERO_TERMINATED);

    /* Create the inline part. */
    part = curl_mime_addpart(mime);
    curl_mime_subparts(part, alt);
    curl_mime_type(part, "multipart/alternative");
    slist = curl_slist_append(NULL, "Content-Disposition: inline");
    curl_mime_headers(part, slist, 1);

    /* Add the current source program as an attachment. */
    part = curl_mime_addpart(mime);
    curl_mime_filedata(part, "smtp-mime.c");
    curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);

    /* Send the message */
    res = curl_easy_perform(curl);

    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* Free lists. */
    curl_slist_free_all(recipients);
    curl_slist_free_all(headers);

    /* curl won't send the QUIT command until you call cleanup, so you should
     * be able to re-use this connection for additional messages (setting
     * CURLOPT_MAIL_FROM and CURLOPT_MAIL_RCPT as required, and calling
     * curl_easy_perform() again. It may not be a good idea to keep the
     * connection open for a very long time though (more than a few minutes
     * may result in the server timing out the connection), and you do want to
     * clean up in the end.
     */
    curl_easy_cleanup(curl);

    /* Free multipart message. */
    curl_mime_free(mime);
  }

  return (int)res;
}
int main( int argc, char **argv ) {
	CURL *curl;
	CURLcode res;
	FILE *ftpfile;
	FILE * hd_src ;
	int hd ;
	struct stat file_info;

	struct curl_slist *headerlist = NULL;
	char buf_1 [] = "RNFR " UPLOAD_FILE_AS;
	char buf_2 [] = "RNTO " RENAME_FILE_TO;

	/* get the file size of the local file */
	hd = open( LOCAL_FILE, O_RDONLY ) ;
	fstat( hd, &file_info );
	close( hd ) ;

	/* get a FILE * of the same file, could also be made with
	   fdopen() from the previous descriptor, but hey this is just
	   an example! */
	hd_src = fopen( LOCAL_FILE, "rb" );

	/* In windows, this will init the winsock stuff */
	curl_global_init( CURL_GLOBAL_ALL );

	/* get a curl handle */
	curl = curl_easy_init();
	if ( curl ) {
		/* build a list of commands to pass to libcurl */
		headerlist = curl_slist_append( headerlist, buf_1 );
		headerlist = curl_slist_append( headerlist, buf_2 );

		/* enable uploading */
		curl_easy_setopt( curl, CURLOPT_UPLOAD, TRUE ) ;

		/* specify target */
		curl_easy_setopt( curl,CURLOPT_URL, REMOTE_URL );

		/* pass in that last of FTP commands to run after the transfer */
		curl_easy_setopt( curl, CURLOPT_POSTQUOTE, headerlist );

		/* now specify which file to upload */
		curl_easy_setopt( curl, CURLOPT_READDATA, hd_src );

		/* and give the size of the upload (optional) */
		curl_easy_setopt( curl, CURLOPT_INFILESIZE_LARGE, file_info.st_size );

		/* Now run off and do what you've been told! */
		res = curl_easy_perform( curl );

		/* clean up the FTP commands list */
		curl_slist_free_all( headerlist );

		/* always cleanup */
		curl_easy_cleanup( curl );
	}
	fclose( hd_src ); /* close the local file */

	curl_global_cleanup();
	return 0;
}
Example #15
0
void HttpConnection::proxyize(HttpSession *httpSession) {
	CurlSession *curlSession;
	char fullUrl[2048];
	char httpArguments[256];
	int *arguments[5];
	int *arguments2[5];
	int returnCode;
	struct timeval sendTimeout;
	socklen_t sendTimeoutSize = sizeof(sendTimeout);
	int clientSocket;
	int httpReturnCode;
	char vxferLog[64];
	int originServerUrlNumber = 0;
	char header = 1;
	char data = 0;
	struct curl_slist *slist = NULL;
	char headerByteRange[64];
	char *pChar;

	if (httpSession->byteRange.start != -1) {
		httpSession->seekPosition = httpSession->byteRange.start;
		if (httpSession->byteRange.end != -1)
			snprintf(headerByteRange, sizeof(headerByteRange), "Range: bytes=%d-%d", httpSession->byteRange.start, httpSession->byteRange.end);
		else
			snprintf(headerByteRange, sizeof(headerByteRange), "Range: bytes=%d-", httpSession->byteRange.start);
		slist = curl_slist_append(slist, headerByteRange);
	}
	while (originServerUrlNumber < 16) {
		sendTimeout.tv_sec = 30;
		sendTimeout.tv_usec = 0;
		returnCode = setsockopt(httpSession->httpExchange->getOutput(), SOL_SOCKET, SO_SNDTIMEO, &sendTimeout, sendTimeoutSize);
		if (returnCode < 0) {
			systemLog->sysLog(ERROR, "cannot setsockopt with SO_SNDTIMEO on socket %d: %s", httpSession->httpExchange->getOutput(), strerror(errno));
			clientSocket = httpSession->httpExchange->getOutput();
			httpSession->destroy(true);
			close(clientSocket);
			return;
		}
		curlSession = curl->createSession();
		if (! curlSession) {
			clientSocket = httpSession->httpExchange->getOutput();
			httpSession->destroy(true);
			close(clientSocket);
			return;
		}

		// Add Additional Headers
		if (httpSession->byteRange.start != -1)
			returnCode = curl->setRequestHeader(curlSession, slist);

		// XXX Boundary checking
		/*if (httpSession->seekSeconds) {
			snprintf(httpArguments, sizeof(httpArguments), "seekseconds=%f", httpSession->seekSeconds);
			httpArgumentsPresent = true;
		}
		if (httpSession->seekPosition) {
			snprintf(httpArguments, sizeof(httpArguments), "seek=%d", httpSession->seekPosition);
			httpArgumentsPresent = true;
		}*/
		if (! strstr(httpSession->httpRequest, "getSmil")) {
			pChar = strstr(httpSession->httpRequest, "?");
			if (pChar) {
				snprintf(httpArguments, sizeof(httpArguments), "%s", pChar);
				pChar = strstr(httpArguments, " ");
				if (pChar)
					*pChar = '\0';
				snprintf(fullUrl, sizeof(fullUrl), "%s%s%s", configuration->originServerUrl[originServerUrlNumber], httpSession->videoName, httpArguments);
			}
			else
				snprintf(fullUrl, sizeof(fullUrl), "%s%s", configuration->originServerUrl[originServerUrlNumber], httpSession->videoName);
		}
		else
			snprintf(fullUrl, sizeof(fullUrl), "%s", httpSession->httpFullRequest);

		arguments[0] = (int *)httpSession;
		arguments[1] = (int *)this;
		arguments[2] = (int *)curl;
		arguments[3] = (int *)curlSession;
		arguments[4] = (int *)&data;
		arguments2[0] = (int *)httpSession;
		arguments2[1] = (int *)this;
		arguments2[2] = (int *)curl;
		arguments2[3] = (int *)curlSession;
		arguments2[4] = (int *)&header;
		returnCode = curl->fetchHttpUrlWithCallback(curlSession, (void *)callbackFunctionProxy, (void *)arguments, (void *)callbackFunctionProxy, (void *)arguments2, fullUrl);
		if (returnCode < 0) {
			curl->deleteSession(curlSession);
                        delete curlSession;
			httpSession->destroy(true);
			close(clientSocket);

			return;
		}
		httpReturnCode = curl->getHttpCode(curlSession);

		if (httpReturnCode == 200) {
			if (httpSession->multicastData) {
				unsigned int position;
				bool mustLog = false;

				if (httpSession->mp4Position)
					position = httpSession->mp4Position;
				else
					position = httpSession->seekPosition;
				
				switch (httpSession->multicastData->commandType) {
					case 0:
						char *typeId;
						if (httpSession->multicastData->tagId >= 1 && httpSession->multicastData->tagId <= 3)
							typeId = stringType[httpSession->multicastData->tagId];
						else
							typeId = stringType[0];

						snprintf(vxferLog, sizeof(vxferLog), "VXFER %u;%s;%u;%s;%d;%u;%u", httpSession->multicastData->itemId, httpSession->multicastData->countryCode, httpSession->multicastData->productId, typeId, (int)httpSession->fileOffset, position, httpSession->multicastData->encodingFormatId);
						mustLog = true;
						break;
					case 1:
						snprintf(vxferLog, sizeof(vxferLog), "VX %u;%u;%u;%d;%u;%u", httpSession->multicastData->itemId, httpSession->multicastData->productId, httpSession->multicastData->tagId, (int)httpSession->fileOffset, position, httpSession->multicastData->encodingFormatId);
						mustLog = true;
						break;
				}
				if (mustLog == true)
					combinedLog(httpSession, vxferLog, curl->getContentLength(curlSession), LOG_NOTICE);
			}

			if (slist)
				curl_slist_free_all(slist);
			curl->deleteSession(curlSession);

			clientSocket = httpSession->httpExchange->getOutput();
			delete curlSession;
			httpSession->destroy(true);
			close(clientSocket);
			return;
		}
		else {
			curl->deleteSession(curlSession);
			delete curlSession;

			originServerUrlNumber++;
		}
		if (configuration->originServerUrl[originServerUrlNumber][0] == '\0')
			break;
	}

	if (slist)
		curl_slist_free_all(slist);
	systemLog->sysLog(ERROR, "cannot found file '%s' on origin server urls", httpSession->videoName);
	clientSocket = httpSession->httpExchange->getOutput();
	httpSession->destroy(true);
	close(clientSocket);

	return;
}
Example #16
0
HTTPFetchOngoing::HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
	pool(pool_),
	curl(NULL),
	multi(NULL),
	request(request_),
	result(request_),
	oss(std::ios::binary),
	http_header(NULL),
	post(NULL)
{
	curl = pool->alloc();
	if (curl == NULL) {
		return;
	}

	// Set static cURL options
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);

	std::string bind_address = g_settings->get("bind_address");
	if (!bind_address.empty()) {
		curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
	}

#if LIBCURL_VERSION_NUM >= 0x071304
	// Restrict protocols so that curl vulnerabilities in
	// other protocols don't affect us.
	// These settings were introduced in curl 7.19.4.
	long protocols =
		CURLPROTO_HTTP |
		CURLPROTO_HTTPS |
		CURLPROTO_FTP |
		CURLPROTO_FTPS;
	curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
	curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
#endif

	// Set cURL options based on HTTPFetchRequest
	curl_easy_setopt(curl, CURLOPT_URL,
			request.url.c_str());
	curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
			request.timeout);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
			request.connect_timeout);

	if (request.useragent != "")
		curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());

	// Set up a write callback that writes to the
	// ostringstream ongoing->oss, unless the data
	// is to be discarded
	if (request.caller == HTTPFETCH_DISCARD) {
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
				httpfetch_discardfunction);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
	} else {
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
				httpfetch_writefunction);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
	}

	// Set POST (or GET) data
	if (request.post_fields.empty()) {
		curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
	} else if (request.multipart) {
		curl_httppost *last = NULL;
		for (StringMap::iterator it = request.post_fields.begin();
				it != request.post_fields.end(); ++it) {
			curl_formadd(&post, &last,
					CURLFORM_NAMELENGTH, it->first.size(),
					CURLFORM_PTRNAME, it->first.c_str(),
					CURLFORM_CONTENTSLENGTH, it->second.size(),
					CURLFORM_PTRCONTENTS, it->second.c_str(),
					CURLFORM_END);
		}
		curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
		// request.post_fields must now *never* be
		// modified until CURLOPT_HTTPPOST is cleared
	} else if (request.post_data.empty()) {
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		std::string str;
		for (StringMap::iterator it = request.post_fields.begin();
				it != request.post_fields.end(); ++it) {
			if (str != "")
				str += "&";
			str += urlencode(it->first);
			str += "=";
			str += urlencode(it->second);
		}
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
				str.size());
		curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
				str.c_str());
	} else {
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
				request.post_data.size());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
				request.post_data.c_str());
		// request.post_data must now *never* be
		// modified until CURLOPT_POSTFIELDS is cleared
	}
	// Set additional HTTP headers
	for (std::vector<std::string>::iterator it = request.extra_headers.begin();
			it != request.extra_headers.end(); ++it) {
		http_header = curl_slist_append(http_header, it->c_str());
	}
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);

	if (!g_settings->getBool("curl_verify_cert")) {
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
	}
}
Example #17
0
/**
 * @brief [brief description]
 * @details [long description]
 */
void* ocs_message_manager_distributor(void* do_not_use)
{
  while(1)
  {
    pthread_mutex_lock(&message_queue_mutex);
    while ((ocs_queue_count(message_queue.queue) == 0) && (message_queue.terminate == 0)) 
    {
      /* No messages so wait for one. */
      pthread_cond_wait(&message_queue.cond, &message_queue_mutex);
    }

    /* About terminating? */
    if (message_queue.terminate != 0)
    {
      /* About therminating so unlock the mutex and get out of here. */
      pthread_mutex_unlock(&message_queue_mutex);
      break;
    }

    if (ocs_queue_count(message_queue.queue) > 0)
    {
      /* Retrieve one message from the queue. */
      char* message = ocs_queue_dequeue(message_queue.queue);
      printf("dequeue %s\n", message);
      printf("posting %s ...\n", message);

      CURL *curl;
      CURLcode res;
     
      /* In windows, this will init the winsock stuff */ 
      res = curl_global_init(CURL_GLOBAL_DEFAULT);
      /* Check for errors */ 
      if(res != CURLE_OK) 
      {
        fprintf(stderr, "curl_global_init() failed: %s\n", curl_easy_strerror(res));
        return(NULL);
      }
 
      /* get a curl handle */ 
      curl = curl_easy_init();
      if(curl != NULL) 
      {
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Accept: application/json");
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "charsets: utf-8");

        /* First set the URL that is about to receive our POST. This URL can
           just as well be a https:// URL if that is what should receive the
           data. */ 
        curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080");
        curl_easy_setopt(curl, CURLOPT_PORT, 80);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POSTT"); /* !!! */

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, message); /* data goes here */

        /* Perform the request, res will get the return code */ 
        res = curl_easy_perform(curl);
        /* Check for errors */ 
        if(res != CURLE_OK)
        {
          fprintf(stderr, "curl_easy_perform() failed: %s\n",
                  curl_easy_strerror(res));
        }

        curl_slist_free_all(headers);

        /* always cleanup */ 
        curl_easy_cleanup(curl);
      }
      curl_global_cleanup();

      /* jansson.h library requires the return value of json_dumps to be freed. */
      printf("free message (posting thread)\n"); fflush(stdout);
      free(message);
        
      /* Finished with lock. */
      pthread_mutex_unlock(&message_queue_mutex);
    }
    else
    {
      /* Nothing to do so we're finished with the lock. */
      pthread_mutex_unlock(&message_queue_mutex);
    } 
  }

  pthread_exit(NULL);
}
Example #18
0
bool Curl::doPost(const string& url, const rcp::Collection& params, bool multiPart) {
	CURLcode r;
	struct curl_slist* curl_header = NULL;
	struct curl_httppost* post_curr = NULL;
	struct curl_httppost* post_last = NULL;
	string use_url = url; // @todo make url not const!s
			
	// Make sure userpass/callback is set.
	reset();
	
	// Remove the Expect: from header, can give problems... (when you get a 417 error)
	static const char buf[] = "Expect:";
  	curl_header = curl_slist_append(curl_header,buf);
	
	// Add fields to post.
	// ------------------------------------------------------
	if(!multiPart) {
		const list<rcp::Parameter*>& pars = params.getParameters();
		string data_str = createQueryString(pars);
		
		r = curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1);
		CHECK_CURL_ERROR(r);
		
		r = curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, data_str.c_str());
		CHECK_CURL_ERROR(r);

	}	
	else {
		// handling a multi part post.
		const list<rcp::Parameter*>& post_params = params.getParameters(); 
		list<rcp::Parameter*>::const_iterator it = post_params.begin();	
	
		while(it != post_params.end()) {
			switch((*it)->type) {
				case rcp::Parameter::PARAM_STRING: {
					curl_formadd(
							 &post_curr
							,&post_last
							,CURLFORM_COPYNAME
							,(*it)->getName().c_str()
							,CURLFORM_COPYCONTENTS
							,(*it)->getStringValue().c_str()
							,CURLFORM_END
					);
					break;
				}				
				
				case rcp::Parameter::PARAM_FILE: {
					curl_formadd(
							 &post_curr
							,&post_last
							,CURLFORM_COPYNAME
							,(*it)->getName().c_str()
							,CURLFORM_FILE
							,(*it)->getStringValue().c_str()
							,CURLFORM_END
					);
					break;
				}
				default: {
					printf("error type not handled: %d\n", (*it)->type);
					break;
				}
			}
			++it;
		}
		
		r = curl_easy_setopt(curl, CURLOPT_HTTPPOST, post_curr); // only for multi-part
		CHECK_CURL_ERROR(r);
	}
	
	// no CA verification
	r  = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); 
	CHECK_CURL_ERROR(r);
		
	
	// set URL
	r = curl_easy_setopt(curl, CURLOPT_URL, use_url.c_str());
	CHECK_CURL_ERROR(r);
	
	// set header
	if(headers.size()) {
		setHeaders(&curl_header);
	}
	if(curl_header) {
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_header);
	}
			
	// perform request.
	bool result = true;
	r = curl_easy_perform(curl);
	if(r != CURLE_OK) {
		result = false;
	}
	
	curl_formfree(post_curr);

	// clear header.
	curl_slist_free_all(curl_header);
	headers.clear();
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL); // opts are sticky
	return result;
}
Example #19
0
void add_header(curl_slist **headers, const char *name, const char *value)
{
  char x_header[MAX_HEADER_SIZE];
  snprintf(x_header, sizeof(x_header), "%s: %s", name, value);
  *headers = curl_slist_append(*headers, x_header);
}
Example #20
0
File: dvcs.c Project: unizeto/bmd
/*
countHashFlag brane jset tylko pod uwage dla SERVICE_TYPE_CCPD
 countHashFlag rowne 0 oznacza, ze dane wejsciowe to juz gotowy skrot SHA-1 (BMDDVCS_HASH_AT_INPUT)
 countHashFlag > 0 oznacza, ze funkcja ma policzyc skrot SHA-1 z wejsciowych danych (BMDDVCS_COUNT_HASH)
*/
long call_DVCSservice_signed(long service_type, bmd_crypt_ctx_t *context, bmdDVCS_t *input, long *result, long countHashFlag)
{
struct curl_slist *headers=NULL;
CURL *curl_handle=NULL;
GenBuf_t *request=NULL;
GenBuf_t chunk;
long ret_val=0;
DVCSResponse_t *response=NULL;
long resp_stat=0;
long iter=0;
long num_err_strings=0;
char *err_string=NULL; //blad podczas przetwarzania zadania DVCS
char *err_tmp=NULL;
long httpCode=0;

	PRINT_INFO("LIBBMDDVCS Calling dvcs service\n");
	/********************************/
	/*	walidacja parametrów	*/
	/********************************/
	if(context == NULL)
	{
		PRINT_ERROR("LIBBMDDVCSERR Invalid second parameter value. Error=%i\n",-1);
		return -1;
	}
	if(input == NULL)
	{
		PRINT_ERROR("LIBBMDDVCSERR Invalid third parameter value. Error=%i\n",-2);
		return -2;
	}
	if(result == NULL)
	{
		PRINT_ERROR("LIBBMDDVCSERR Invalid fourth parameter value. Error=%i\n",-3);
		return -3;
	}


	//bmd_crypt_ctx_t *context=NULL;
	chunk.buf=NULL;
	chunk.size=0;

	free_gen_buf(&(input->dvcsCert));
	free(input->errorString); input->errorString=NULL;

	ret_val=_prepare_DVCSReq_to_send(input, service_type, context, &request, countHashFlag);
	if(ret_val != 0)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in preparing DVCS request to send. Error=%i\n",-4);
		return -4;
	}
	//! zapisywanie do pliku wygenerowanego zadania
	/*bmd_save_buf(request, "dvcs.req");*/

	//
	curl_handle = curl_easy_init();

	headers = curl_slist_append(headers, "Content-Type: application/dvcs");

	/*!*///ret_val=curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, cont_temp->content.buf);

	ret_val=curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, request->buf);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-5);
		return -5;
	}
	/*!*///ret_val=curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, cont_temp->content.size);
	ret_val=curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, request->size);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-6);
		return -6;
	}
	ret_val=curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-7);
		return -7;
	}
	ret_val=curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_to_gen_buf_callback);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-8);
		return -8;
	}
	ret_val=curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-9);
		return -9;
	}

	ret_val=curl_easy_setopt(curl_handle, CURLOPT_URL,input->url);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in setting curl option. Error=%i\n",-10);
		return -10;
	}

	if(input->connectionTimeout > 0)
	{
		ret_val=curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, input->connectionTimeout);
		if(ret_val!=CURLE_OK)
		{
			PRINT_ERROR("LIBBMDDVCSERR Error in setting curl timeout. Error=%i\n",-11);
			return -11;
		}
	}

	ret_val=curl_easy_perform(curl_handle);
	if(ret_val!=CURLE_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in performing curl operation. Error=%i\n",-12);
		return -12;
	}

	free_gen_buf(&request);

	curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &httpCode);
	asprintf( &(input->errorString), "HTTP RESPONSE CODE: %li", httpCode);

	//! zapisywanie odpowiedzi servera DVCS do odpowiedniego pliku
	/*
	switch(service_type)
	{
		case SERVICE_TYPE_CPD:
			{ bmd_save_buf(&chunk, "dvcs_cpd.resp"); break; }
		case SERVICE_TYPE_CCPD:
			{ bmd_save_buf(&chunk, "dvcs__ccpd.resp"); break;}
		case SERVICE_TYPE_VSD:
			{ bmd_save_buf(&chunk, "dvcs_vsd.resp"); break; }
		case SERVICE_TYPE_VPKC:
			{ bmd_save_buf(&chunk, "dvcs_vpkc.resp"); break; }
		default: { printf ("nierozpoznana usluga\n"); }
	}
	*/


	curl_slist_free_all(headers);
	curl_easy_cleanup(curl_handle);

	ret_val=decode_DVCSResponse(&chunk, &response);
	if(ret_val != 0)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in decoding DVCS response. Error=%i\n",-13);
		return -13;
	}

	//przypisywanie poswiadczenia
	ret_val=set_gen_buf2(chunk.buf, chunk.size, &(input->dvcsCert));
	if(ret_val != BMD_OK)
	{
		PRINT_ERROR("LIBBMDDVCSERR Error in assigning DVCS certificate. Error=%i\n",-14);
		return -14;
	}
	chunk.buf=NULL;
	chunk.size=0;


	ret_val=_get_respStatus(response, &resp_stat);
	if(ret_val != 0)
	{
		if(response->present == DVCSResponse_PR_dvErrorNote)
		{
			if(response->choice.dvErrorNote.transactionStatus.statusString != NULL)
			{
				num_err_strings=response->choice.dvErrorNote.transactionStatus.statusString->list.count;
				for(iter=0; iter<num_err_strings; iter++)
				{
					if(iter == 0)
					{
						asprintf(&err_tmp, "%s\nDVCS ERROR NOTICE: ", input->errorString); //kod odpowiedzi HTTP
						free(input->errorString);
						input->errorString=NULL;
					}
					asprintf(&err_string, "%s%s\n", err_tmp,  response->choice.dvErrorNote.transactionStatus.statusString->list.array[iter]->buf);
					free(err_tmp);
					err_tmp=err_string;
				}
				err_tmp=NULL;
			}
			if(err_string != NULL)
			{
				free(input->errorString);
				input->errorString=err_string;
			}
		}
		PRINT_ERROR("LIBBMDDVCSERR Error in getting response status. Error=%i\n",-15);
		_destroy_DVCSResponse(&response);
		return -15;
	}

	_destroy_DVCSResponse(&response);

	if(resp_stat > 1)
	{
		*result=-1;
	}
	else //ok
	{
		*result=resp_stat; //0 lub 1 odpowiednio dla kwalifikowanego lub zwyklego
	}
	return 0;
}
Example #21
0
smcp_status_t
smcp_curl_proxy_request_handler(
    smcp_curl_proxy_node_t		node
) {
    smcp_status_t ret = SMCP_STATUS_NOT_ALLOWED;
    smcp_curl_request_t request = NULL;
    struct curl_slist *headerlist=NULL;
    smcp_method_t method = smcp_inbound_get_code();

    //require_action(method<=COAP_METHOD_DELETE,bail,ret = SMCP_STATUS_NOT_ALLOWED);

    //require_action(COAP_OPTION_URI_PATH!=smcp_inbound_peek_option(NULL,NULL),bail,ret=SMCP_STATUS_NOT_FOUND);

    node->interface = smcp_get_current_instance();

    smcp_inbound_reset_next_option();

    request = smcp_curl_request_create();
    request->proxy_node = node;

    require_action(request!=NULL,bail,ret = SMCP_STATUS_MALLOC_FAILURE);

    switch(method) {
    case COAP_METHOD_GET:
        curl_easy_setopt(request->curl, CURLOPT_CUSTOMREQUEST, "GET");
        break;
    case COAP_METHOD_PUT:
        curl_easy_setopt(request->curl, CURLOPT_PUT, 1L);
        break;
    case COAP_METHOD_POST:
        curl_easy_setopt(request->curl, CURLOPT_POST, 1L);
        break;
    case COAP_METHOD_DELETE:
        curl_easy_setopt(request->curl, CURLOPT_CUSTOMREQUEST, "DELETE");
        break;
    default:
        ret = SMCP_STATUS_NOT_ALLOWED;
        break;
    }

    {
        coap_option_key_t key;
        const uint8_t* value;
        coap_size_t value_len;
        while((key=smcp_inbound_next_option(&value, &value_len))!=COAP_OPTION_INVALID) {
            if(key==COAP_OPTION_PROXY_URI) {
                char uri[value_len+1];
                memcpy(uri,value,value_len);
                uri[value_len] = 0;
                curl_easy_setopt(request->curl, CURLOPT_URL, uri);
                assert_printf("CuRL URL: \"%s\"",uri);
                ret = 0;
            } else if(key==COAP_OPTION_URI_HOST) {
            } else if(key==COAP_OPTION_URI_PORT) {
            } else if(key==COAP_OPTION_URI_PATH) {
            } else if(key==COAP_OPTION_URI_QUERY) {
            } else if(key==COAP_OPTION_CONTENT_TYPE || key==COAP_OPTION_ACCEPT) {
                const char* option_name = coap_option_key_to_cstr(key, false);
                const char* value_string = coap_content_type_to_cstr(value[1]);
                char header[strlen(option_name)+strlen(value_string)+3];
                strcpy(header,option_name);
                strcat(header,": ");
                strcat(header,value_string);
                headerlist = curl_slist_append(headerlist, header);
                assert_printf("CuRL HEADER: \"%s\"",header);
            } else {
                if(coap_option_value_is_string(key)) {
                    const char* option_name = coap_option_key_to_cstr(key, false);
                    char header[strlen(option_name)+value_len+3];
                    strcpy(header,option_name);
                    strcat(header,": ");
                    strncat(header,(const char*)value,value_len);
                    assert_printf("CuRL HEADER: \"%s\"",header);
                    headerlist = curl_slist_append(headerlist, header);
                }
            }
        }
    }

    require_noerr(ret,bail);

    if(smcp_inbound_get_content_len()) {
        coap_size_t len = smcp_inbound_get_content_len();
        request->output_content = calloc(1,len+1);
        request->output_content_len = len;
        memcpy(request->output_content,smcp_inbound_get_content_ptr(),len);
        curl_easy_setopt(request->curl, CURLOPT_READFUNCTION, ReadMemoryCallback);
        curl_easy_setopt(request->curl, CURLOPT_READDATA, (void *)request);
    }

    curl_easy_setopt(request->curl, CURLOPT_USERAGENT, "smcp-curl-proxy/1.0");
    curl_easy_setopt(request->curl, CURLOPT_HTTPHEADER, headerlist),headerlist=NULL;
    curl_easy_setopt(request->curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(request->curl, CURLOPT_WRITEDATA, (void *)request);

    ret = smcp_start_async_response(&request->async_response,0);
    require_noerr(ret,bail);

    if(node->curl_multi_handle)
        curl_multi_add_handle(node->curl_multi_handle, request->curl);
    else
        curl_easy_perform(request->curl);

bail:
    if(headerlist)
        curl_slist_free_all(headerlist);

    if(ret && request)
        smcp_curl_request_release(request);

    return ret;
}
Example #22
0
int SendMailtest(void)
{
  CURL *curl;
  CURLcode res;
  struct curl_slist *recipients = NULL;
  struct upload_status upload_ctx;

  upload_ctx.lines_read = 0;

  curl = curl_easy_init();
  if (curl) {
    /* This is the URL for your mailserver. Note the use of port 587 here,
     * instead of the normal SMTP port (25). Port 587 is commonly used for
     * secure mail submission (see RFC4403), but you should use whatever
     * matches your server configuration. */
    curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587");

    /* In this example, we'll start with a plain text connection, and upgrade
     * to Transport Layer Security (TLS) using the STARTTLS command. Be careful
     * of using CURLUSESSL_TRY here, because if TLS upgrade fails, the transfer
     * will continue anyway - see the security discussion in the libcurl
     * tutorial for more details. */
    curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);

    /* If your server doesn't have a valid certificate, then you can disable
     * part of the Transport Layer Security protection by setting the
     * CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false).
     *   curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
     *   curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
     * That is, in general, a bad idea. It is still better than sending your
     * authentication details in plain text though.
     * Instead, you should get the issuer certificate (or the host certificate
     * if the certificate is self-signed) and add it to the set of certificates
     * that are known to libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See
     * docs/SSLCERTS for more information.
     */
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  //  curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");

    /* A common reason for requiring transport security is to protect
     * authentication details (user names and passwords) from being "snooped"
     * on the network. Here is how the user name and password are provided: */
    curl_easy_setopt(curl, CURLOPT_USERNAME, "*****@*****.**");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "linhungyi");

    /* value for envelope reverse-path */
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);
    /* Add two recipients, in this particular case they correspond to the
     * To: and Cc: addressees in the header, but they could be any kind of
     * recipient. */
    recipients = curl_slist_append(recipients, TO);
    recipients = curl_slist_append(recipients, CC);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

    /* In this case, we're using a callback function to specify the data. You
     * could just use the CURLOPT_READDATA option to specify a FILE pointer to
     * read from.
     */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
    curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);

    /* Since the traffic will be encrypted, it is very useful to turn on debug
     * information within libcurl to see what is happening during the transfer.
     */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    /* send the message (including headers) */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* free the list of recipients and clean up */
    curl_slist_free_all(recipients);
    curl_easy_cleanup(curl);
  }
  return 0;
}
Example #23
0
/**
 *  step.1: https://developers.google.com/photos/library/guides/upload-media#uploading-bytes
 *  step.2: https://developers.google.com/photos/library/guides/upload-media#creating-media-item
 */
static const gchar *gphoto_upload_photo_to_album(dt_gphoto_context_t *ctx, gchar *albumid, gchar *fname,
                                                 gchar *title, gchar *summary, const int imgid)
{
  // step.1 : upload raw data

  gchar *basename = g_path_get_basename(fname);

  JsonObject *response = NULL;
  gchar *photo_id = NULL;
  gchar *upload_token = NULL;

  gchar *filename = dt_util_dstrcat(NULL, "X-Goog-Upload-File-Name: %s", basename);
  g_free(basename);

  struct curl_slist *headers = curl_slist_append(NULL, "Content-type: application/octet-stream");
  headers = curl_slist_append(headers, filename);
  headers = curl_slist_append(headers, "X-Goog-Upload-Protocol: raw");

  // Open the temp file and read image to memory
  GMappedFile *imgfile = g_mapped_file_new(fname, FALSE, NULL);
  const int size = g_mapped_file_get_length(imgfile);
  gchar *data = g_mapped_file_get_contents(imgfile);

  response = gphoto_query_post(ctx, GOOGLE_GPHOTO "v1/uploads", headers, NULL, data, size);

  if(!response)
  {
    // all good, the body is the upload-token
    upload_token = g_strdup(ctx->response->str);
  }
  else
    return NULL;

  // step.2 : add raw data into an album

  headers = NULL;

  headers = curl_slist_append(headers, "Content-type: application/json");

  gchar *jbody = dt_util_dstrcat(NULL, "{ \"albumId\": \"%s\", "
                                         "\"newMediaItems\": [ "
                                           "{ \"description\": \"%s\", "
                                           "  \"simpleMediaItem\": { \"uploadToken\": \"%s\"} "
                                           "} ] }", albumid, summary, upload_token);

  response = gphoto_query_post(ctx, GOOGLE_GPHOTO "v1/mediaItems:batchCreate", headers, NULL, jbody, strlen(jbody));

  g_free(jbody);

  // check that the upload was correct and return the photo_id

  if(response)
  {
    if(json_object_has_member(response, "newMediaItemResults"))
    {
      JsonArray *results = json_object_get_array_member(response, "newMediaItemResults");
      // get first element, we have uploaded a single pciture
      JsonObject *root = json_array_get_object_element(results, 0);
      JsonObject *o = root;
      if(json_object_has_member(o, "status"))
      {
        o = json_node_get_object(json_object_get_member(o, "status"));
        if(json_object_has_member(o, "message"))
        {
          if(g_strcmp0(json_object_get_string_member(o, "message"), "OK"))
            return NULL;
        }
        else
          return NULL;
      }
      else
        return NULL;

      if(json_object_has_member(root, "mediaItem"))
      {
        o = json_node_get_object(json_object_get_member(root, "mediaItem"));
        if(json_object_has_member(o, "id"))
          photo_id = g_strdup(json_object_get_string_member(o, "id"));
      }
    }
  }

  return photo_id;
}
static CURLcode check_telnet_options(struct connectdata *conn)
{
  struct curl_slist *head;
  struct curl_slist *beg;
  char option_keyword[128];
  char option_arg[256];
  struct SessionHandle *data = conn->data;
  struct TELNET *tn = (struct TELNET *)conn->data->state.proto.telnet;
  CURLcode result = CURLE_OK;
  int binary_option;

  /* Add the user name as an environment variable if it
     was given on the command line */
  if(conn->bits.user_passwd) {
    snprintf(option_arg, sizeof(option_arg), "USER,%s", conn->user);
    beg = curl_slist_append(tn->telnet_vars, option_arg);
    if(!beg) {
      curl_slist_free_all(tn->telnet_vars);
      tn->telnet_vars = NULL;
      return CURLE_OUT_OF_MEMORY;
    }
    tn->telnet_vars = beg;
    tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
  }

  for(head = data->set.telnet_options; head; head=head->next) {
    if(sscanf(head->data, "%127[^= ]%*[ =]%255s",
              option_keyword, option_arg) == 2) {

      /* Terminal type */
      if(Curl_raw_equal(option_keyword, "TTYPE")) {
        strncpy(tn->subopt_ttype, option_arg, 31);
        tn->subopt_ttype[31] = 0; /* String termination */
        tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES;
        continue;
      }

      /* Display variable */
      if(Curl_raw_equal(option_keyword, "XDISPLOC")) {
        strncpy(tn->subopt_xdisploc, option_arg, 127);
        tn->subopt_xdisploc[127] = 0; /* String termination */
        tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES;
        continue;
      }

      /* Environment variable */
      if(Curl_raw_equal(option_keyword, "NEW_ENV")) {
        beg = curl_slist_append(tn->telnet_vars, option_arg);
        if(!beg) {
          result = CURLE_OUT_OF_MEMORY;
          break;
        }
        tn->telnet_vars = beg;
        tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
        continue;
      }

          /* Window Size */
      if(Curl_raw_equal(option_keyword, "WS")) {
        if(sscanf(option_arg, "%hu%*[xX]%hu",
                  &tn->subopt_wsx, &tn->subopt_wsy) == 2)
          tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES;
        else {
          failf(data, "Syntax error in telnet option: %s", head->data);
          result = CURLE_TELNET_OPTION_SYNTAX;
          break;
        }
        continue;
      }

      /* To take care or not of the 8th bit in data exchange */
      if(Curl_raw_equal(option_keyword, "BINARY")) {
        binary_option=atoi(option_arg);
        if(binary_option!=1) {
          tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO;
          tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO;
        }
        continue;
      }

      failf(data, "Unknown telnet option %s", head->data);
      result = CURLE_UNKNOWN_TELNET_OPTION;
      break;
    }
    else {
      failf(data, "Syntax error in telnet option: %s", head->data);
      result = CURLE_TELNET_OPTION_SYNTAX;
      break;
    }
  }

  if(result) {
    curl_slist_free_all(tn->telnet_vars);
    tn->telnet_vars = NULL;
  }

  return result;
}
Example #25
0
File: http.c Project: lexaurin/git
void http_init(struct remote *remote, const char *url, int proactive_auth)
{
	char *low_speed_limit;
	char *low_speed_time;
	char *normalized_url;
	struct urlmatch_config config = { STRING_LIST_INIT_DUP };

	config.section = "http";
	config.key = NULL;
	config.collect_fn = http_options;
	config.cascade_fn = git_default_config;
	config.cb = NULL;

	http_is_verbose = 0;
	normalized_url = url_normalize(url, &config.url);

	git_config(urlmatch_config_entry, &config);
	free(normalized_url);

	if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
		die("curl_global_init failed");

	http_proactive_auth = proactive_auth;

	if (remote && remote->http_proxy)
		curl_http_proxy = xstrdup(remote->http_proxy);

	pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
	no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");

#ifdef USE_CURL_MULTI
	{
		char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
		if (http_max_requests != NULL)
			max_requests = atoi(http_max_requests);
	}

	curlm = curl_multi_init();
	if (!curlm)
		die("curl_multi_init failed");
#endif

	if (getenv("GIT_SSL_NO_VERIFY"))
		curl_ssl_verify = 0;

	set_from_env(&ssl_cert, "GIT_SSL_CERT");
#if LIBCURL_VERSION_NUM >= 0x070903
	set_from_env(&ssl_key, "GIT_SSL_KEY");
#endif
#if LIBCURL_VERSION_NUM >= 0x070908
	set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
#endif
	set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");

	set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");

	low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
	if (low_speed_limit != NULL)
		curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
	low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
	if (low_speed_time != NULL)
		curl_low_speed_time = strtol(low_speed_time, NULL, 10);

	if (curl_ssl_verify == -1)
		curl_ssl_verify = 1;

	curl_session_count = 0;
#ifdef USE_CURL_MULTI
	if (max_requests < 1)
		max_requests = DEFAULT_MAX_REQUESTS;
#endif

	if (getenv("GIT_CURL_FTP_NO_EPSV"))
		curl_ftp_no_epsv = 1;

	if (url) {
		credential_from_url(&http_auth, url);
		if (!ssl_cert_password_required &&
		    getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
		    starts_with(url, "https://"))
			ssl_cert_password_required = 1;
	}

#ifndef NO_CURL_EASY_DUPHANDLE
	curl_default = get_curl_handle();
#endif
}
Example #26
0
void HTTPCallback::worker_thread_entry_point()
{
  CURL* curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_POST, 1);
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

  Timer* timer;
  while (_q.pop(timer))
  {
    // Set up the request details.
    curl_easy_setopt(curl, CURLOPT_URL, timer->callback_url.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, timer->callback_body.data());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, timer->callback_body.length());

    // Include the sequence number header.
    struct curl_slist* headers = NULL;
    headers = curl_slist_append(headers, (std::string("X-Sequence-Number: ") +
                                          std::to_string(timer->sequence_number)).c_str());
    headers = curl_slist_append(headers, "Content-Type: application/octet-stream");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    // Send the request
    CURLcode curl_rc = curl_easy_perform(curl);
    if (curl_rc == CURLE_OK)
    {
      // Check if the next pop occurs before the repeat-for interval and,
      // if not, convert to a tombstone to indicate the timer is dead.
      if ((timer->sequence_number + 1) * timer->interval > timer->repeat_for)
      {
        timer->become_tombstone();
      }
      _replicator->replicate(timer);
      _handler->add_timer(timer);
      timer = NULL; // We relinquish control of the timer when we give
                    // it to the store.
      if (_timer_pop_alarm)
      {
        _timer_pop_alarm->clear();
      }
    }
    else
    {
      if (curl_rc == CURLE_HTTP_RETURNED_ERROR)
      {
        long http_rc = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_rc);
        TRC_WARNING("Got HTTP error %d from %s", http_rc, timer->callback_url.c_str());
      }

      TRC_WARNING("Failed to process callback for %lu: URL %s, curl error was: %s", timer->id,
                  timer->callback_url.c_str(),
                  curl_easy_strerror(curl_rc));

      if (_timer_pop_alarm && timer->is_last_replica())
      {
        _timer_pop_alarm->set();
      }

      delete timer;
    }

    // Tidy up request-speciifc objects
    curl_slist_free_all(headers);
    headers = NULL;
  }

  // Tidy up thread-specific objects
  curl_easy_cleanup(curl);

  return;
}
Example #27
0
static int http_post(void *handle, char *uri, const char *clientid, const char *username, const char *password, const char *topic, int acc, int method)
{
	struct http_backend *conf = (struct http_backend *)handle;
	CURL *curl;
	struct curl_slist *headerlist=NULL;
	int re;
	int respCode = 0;
	int ok = FALSE;
	char *url;
	char *data;

	if (username == NULL) {
		return (FALSE);
	}

	clientid = (clientid && *clientid) ? clientid : "";
	password = (password && *password) ? password : "";
	topic    = (topic && *topic) ? topic : "";

	if ((curl = curl_easy_init()) == NULL) {
		_fatal("create curl_easy_handle fails");
		return (FALSE);
	}
	if (conf->hostheader != NULL)
		headerlist = curl_slist_append(headerlist, conf->hostheader);
	headerlist = curl_slist_append(headerlist, "Expect:");

	//_log(LOG_NOTICE, "u=%s p=%s t=%s acc=%d", username, password, topic, acc);

	url = (char *)malloc(strlen(conf->ip) + strlen(uri) + 20);
	if (url == NULL) {
		_fatal("ENOMEM");
		return (FALSE);
	}

	// enable the https
	if (strcmp(conf->with_tls, "true") == 0){
		sprintf(url, "https://%s:%d%s", conf->ip, conf->port, uri);
	}else{
		sprintf(url, "http://%s:%d%s", conf->ip, conf->port, uri);
	}

	char* escaped_username = curl_easy_escape(curl, username, 0);
	char* escaped_password = curl_easy_escape(curl, password, 0);
	char* escaped_topic = curl_easy_escape(curl, topic, 0);
	char* escaped_clientid = curl_easy_escape(curl, clientid, 0);

	char string_acc[20];
	snprintf(string_acc, 20, "%d", acc);

	char *string_envs = (char *)malloc(MAXPARAMSLEN);
	if (string_envs == NULL) {
		_fatal("ENOMEM");
		return (FALSE);
	}

	memset(string_envs, 0, MAXPARAMSLEN);

	//get the sys_env from here
	int env_num = 0;
	if ( method == METHOD_GETUSER && conf->getuser_envs != NULL ){
		env_num = get_string_envs(curl, conf->getuser_envs, string_envs);
	}else if ( method == METHOD_SUPERUSER && conf->superuser_envs != NULL ){
		env_num = get_string_envs(curl, conf->superuser_envs, string_envs);
	} else if ( method == METHOD_ACLCHECK && conf->aclcheck_envs != NULL ){
		env_num = get_string_envs(curl, conf->aclcheck_envs, string_envs);
	}
	if( env_num == -1 ){
		return (FALSE);
	}
	//---- over ----

	data = (char *)malloc(strlen(string_envs) + strlen(escaped_username) + strlen(escaped_password) + strlen(escaped_topic) + strlen(string_acc) + strlen(escaped_clientid) + 50);
	if (data == NULL) {
		_fatal("ENOMEM");
		return (FALSE);
	}
	sprintf(data, "%susername=%s&password=%s&topic=%s&acc=%s&clientid=%s",
		string_envs,
		escaped_username,
		escaped_password,
		escaped_topic,
		string_acc,
		clientid);

	_log(LOG_DEBUG, "url=%s", url);
	_log(LOG_DEBUG, "data=%s", data);
	// curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_POST, 1L);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
	curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_easy_setopt(curl, CURLOPT_USERNAME, username);
	curl_easy_setopt(curl, CURLOPT_PASSWORD, password);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

	re = curl_easy_perform(curl);
	if (re == CURLE_OK) {
		re = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respCode);
		if (re == CURLE_OK && respCode >= 200 && respCode < 300) {
			ok = TRUE;
		} else if (re == CURLE_OK && respCode >= 500) {
			ok = BACKEND_ERROR;
		} else {
			//_log(LOG_NOTICE, "http auth fail re=%d respCode=%d", re, respCode);
		}
	} else {
		_log(LOG_DEBUG, "http req fail url=%s re=%s", url, curl_easy_strerror(re));
		ok = BACKEND_ERROR;
	}

	curl_easy_cleanup(curl);
	curl_slist_free_all (headerlist);
	free(url);
	free(data);
	free(string_envs);
	free(escaped_username);
	free(escaped_password);
	free(escaped_topic);
	free(escaped_clientid);
	return (ok);
}
Example #28
0
json_t *json_rpc_call(const char *url, const char *userpass, const char *rpc_req)
{
	CURL *curl;
	json_t *val;
	int rc;
	struct data_buffer all_data = { };
	struct upload_buffer upload_data;
	json_error_t err = { };
	struct curl_slist *headers = NULL;
	char len_hdr[64];

	curl = curl_easy_init();
	if (!curl)
		return NULL;

	if (opt_protocol)
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_ENCODING, "");
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
	curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
	if (userpass) {
		curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
		curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	}
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	if (opt_protocol)
		printf("JSON protocol request:\n%s\n", rpc_req);

	upload_data.buf = rpc_req;
	upload_data.len = strlen(rpc_req);
	sprintf(len_hdr, "Content-Length: %lu",
		(unsigned long) upload_data.len);

	headers = curl_slist_append(headers,
		"Content-type: application/json");
	headers = curl_slist_append(headers, len_hdr);
	headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/

	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

	rc = curl_easy_perform(curl);
	if (rc)
		goto err_out;

	val = json_loads(all_data.buf, &err);
	if (!val) {
		fprintf(stderr, "JSON failed(%d): %s\n", err.line, err.text);
		goto err_out;
	}

	if (opt_protocol) {
		char *s = json_dumps(val, JSON_INDENT(3));
		printf("JSON protocol response:\n%s\n", s);
		free(s);
	}

	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_cleanup(curl);
	return val;

err_out:
	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_cleanup(curl);
	return NULL;
}
Example #29
0
static char *request(const char *url) {
    CURL *curl = NULL;
    CURLcode status;
    struct curl_slist *headers = NULL;
    char *data = NULL;
    long code;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (!curl) {
        goto error;
    }

    data = malloc(BUFFER_SIZE);
    if (!data) {
        goto error;
    }

    struct write_result write_result = {
            .data = data,
            .pos = 0
    };

    curl_easy_setopt(curl, CURLOPT_URL, url);

    /* GitHub commits API v3 requires a User-Agent header */
    headers = curl_slist_append(headers, "User-Agent: Jansson-Tutorial");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);

    status = curl_easy_perform(curl);
    if (status != 0) {
        fprintf(stderr, "error: unable to request data from %s:\n", url);
        fprintf(stderr, "%s\n", curl_easy_strerror(status));
        goto error;
    }

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
    if (code != 200) {
        fprintf(stderr, "error: server responded with code %ld\n", code);
        goto error;
    }

    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    curl_global_cleanup();

    /* zero-terminate the result */
    data[write_result.pos] = '\0';

    return data;

    error:
    if (data) {
        free(data);
    }
    if (curl) {
        curl_easy_cleanup(curl);
    }
    if (headers) {
        curl_slist_free_all(headers);
    }
    curl_global_cleanup();
    return NULL;
}

int main(int argc, char *argv[]) {
    size_t i;
    char *text;
    char url[URL_SIZE];

    json_t *root;
    json_error_t error;

    if (argc != 3) {
        fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
        fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
        return 2;
    }

    snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);

    printf("Query url: %s\n", url);

    text = request(url);
    if (!text) {
        return 1;
    }

    root = json_loads(text, 0, &error);
    free(text);

    if (!root) {
        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
        return 1;
    }

    if (!json_is_array(root)) {
        fprintf(stderr, "error: root is not an array\n");
        json_decref(root);
        return 1;
    }

    for (i = 0; i < json_array_size(root); i++) {
        json_t *data, *sha, *commit, *message;
        const char *message_text;

        data = json_array_get(root, i);
        if (!json_is_object(data)) {
            fprintf(stderr, "error: commit data %d is not an object\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        sha = json_object_get(data, "sha");
        if (!json_is_string(sha)) {
            fprintf(stderr, "error: commit %d: sha is not a string\n", (int) (i + 1));
            return 1;
        }

        commit = json_object_get(data, "commit");
        if (!json_is_object(commit)) {
            fprintf(stderr, "error: commit %d: commit is not an object\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        message = json_object_get(commit, "message");
        if (!json_is_string(message)) {
            fprintf(stderr, "error: commit %d: message is not a string\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        message_text = json_string_value(message);
        printf("%.8s %.*s\n",
               json_string_value(sha),
               newline_offset(message_text),
               message_text);
    }

    json_decref(root);
    return 0;
}
//Process POST Request
int processPostTask(CCHttpRequest *request, write_callback callback, void *stream, int32_t *responseCode)
{
    CURLcode code = CURL_LAST;
    CURL *curl = curl_easy_init();
    
    do {
        if (!configureCURL(curl)) {
            break;
        }
        
        /* handle custom header data */
        /* create curl linked list */
        struct curl_slist *cHeaders=NULL;
        /* get custom header data (if set) */
      		std::vector<std::string> headers=request->getHeaders();
      		if(!headers.empty())
      		{      			
        			for(std::vector<std::string>::iterator it=headers.begin();it!=headers.end();it++)
        			{
              /* append custom headers one by one */
          				cHeaders=curl_slist_append(cHeaders,it->c_str());
        			}
           /* set custom headers for curl */
        			code = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, cHeaders);
        			if (code != CURLE_OK) {
          				break;
        			}
      		}
              
        code = curl_easy_setopt(curl, CURLOPT_URL, request->getUrl());
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_setopt(curl, CURLOPT_WRITEDATA, stream);
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_setopt(curl, CURLOPT_POST, 1);
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request->getRequestData());
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request->getRequestDataSize());
        if (code != CURLE_OK) {
            break;
        }
        code = curl_easy_perform(curl);
        if (code != CURLE_OK) {
            break;
        }
        
        /* free the linked list for header data */
        curl_slist_free_all(cHeaders);

        code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, responseCode); 
        if (code != CURLE_OK || *responseCode != 200) {
            code = CURLE_HTTP_RETURNED_ERROR;
        }
    } while (0);
    if (curl) {
        curl_easy_cleanup(curl);
    }
    
    return (code == CURLE_OK ? 0 : 1);    
}