Exemplo n.º 1
0
Arquivo: smtp-tls.c Projeto: 2px/curl
int main(void)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  struct curl_slist *recipients = NULL;
  struct upload_status upload_ctx;

  upload_ctx.lines_read = 0;

  curl = curl_easy_init();
  if(curl) {
    /* Set username and password */
    curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");

    /* 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://mainserver.example.net: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_ALL);

    /* 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_CAINFO, "/path/to/certificate.pem");

    /* 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);

    /* 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 */
    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 */
    curl_slist_free_all(recipients);

    /* Always cleanup */
    curl_easy_cleanup(curl);
  }

  return (int)res;
}
Exemplo n.º 2
0
static int http_post(void *handle, char *uri, const char *clientid, const char *username,const char *password, const char *topic, int acc)
{
	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)
		curl_slist_append(headerlist, conf->hostheader);
	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);
	}
	sprintf(url, "http://%s:%d%s", conf->ip, conf->port, uri);

	/* Hoping the 1024 is sufficient for curl_easy_escapes ... */
	data = (char *)malloc(strlen(username) + strlen(password) + strlen(topic) + strlen(clientid) + 1024);
	if (data == NULL) {
		_fatal("ENOMEM");
		return (FALSE);
	}
	sprintf(data, "username=%s&password=%s&topic=%s&acc=%d&clientid=%s",
			curl_easy_escape(curl, username, 0),
			curl_easy_escape(curl, password, 0),
			curl_easy_escape(curl, topic, 0),
			acc,
			curl_easy_escape(curl, clientid, 0));

	_log(LOG_DEBUG, "url=%s", url);
	// 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_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) {
			ok = TRUE;
		} 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));
	}
	
	curl_easy_cleanup(curl);
	curl_slist_free_all (headerlist);
	free(url);
	free(data);
	return (ok);
}
Exemplo n.º 3
0
int main(int argc, char **argv) {
	extern int optind;
	extern char *optarg;
	int i;

	char *outfile = NULL;
	int de = 0;

	while ((i = getopt(argc, argv, "o:d")) != -1) {
		switch (i) {
		case 'o':
			outfile = optarg;
			break;

		case 'd':
			de = 1;
			break;

		default:
			usage(argv);
			exit(EXIT_FAILURE);
		}
	}

	if (argc - optind != 1) {
		usage(argv);
		exit(EXIT_FAILURE);
	}

	if (outfile == NULL && isatty(1)) {
		fprintf(stderr, "Didn't specify -o and standard output is a terminal\n");
		exit(EXIT_FAILURE);
	}
	FILE *outfp = stdout;
	if (outfile != NULL) {
		outfp = fopen(outfile, "wb");
		if (outfp == NULL) {
			perror(outfile);
			exit(EXIT_FAILURE);
		}
	}

	int width, height;
	unsigned char *buf;

	{
		{
			{
				char *url = argv[optind];

				CURL *curl = curl_easy_init();
				if (curl == NULL) {
					fprintf(stderr, "Curl won't start\n");
					exit(EXIT_FAILURE);
				}

				struct data data;
				data.buf = NULL;
				data.len = 0;
				data.nalloc = 0;

				curl_easy_setopt(curl, CURLOPT_URL, url);
				curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
				curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
				curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_receive);

				CURLcode res = curl_easy_perform(curl);
				if (res != CURLE_OK) {
					fprintf(stderr, "Can't retrieve %s: %s\n", url,
						curl_easy_strerror(res));
					exit(EXIT_FAILURE);
				}

				struct image *i;

				if (data.len >= 4 && memcmp(data.buf, "\x89PNG", 4) == 0) {
					i = read_png(data.buf, data.len);
				} else if (data.len >= 2 && memcmp(data.buf, "\xFF\xD8", 2) == 0) {
					i = read_jpeg(data.buf, data.len);
				} else {
					fprintf(stderr, "Don't recognize file format\n");

					free(data.buf);
					curl_easy_cleanup(curl);
					exit(EXIT_FAILURE);
				}

				free(data.buf);
				curl_easy_cleanup(curl);

				width = i->width;
				height = i->height;
				buf = malloc(i->width * i->height * 4);

				int x, y;
				for (y = 0; y < i->height; y++) {
					for (x = 0; x < i->width; x++) {
						if (i->depth == 4) {
							double as = buf[((y) * width + x) * 4 + 3] / 255.0;
							double rs = buf[((y) * width + x) * 4 + 0] / 255.0 * as;
							double gs = buf[((y) * width + x) * 4 + 1] / 255.0 * as;
							double bs = buf[((y) * width + x) * 4 + 2] / 255.0 * as;

							double ad = i->buf[(y * i->width + x) * 4 + 3] / 255.0;
							double rd = i->buf[(y * i->width + x) * 4 + 0] / 255.0 * ad;
							double gd = i->buf[(y * i->width + x) * 4 + 1] / 255.0 * ad;
							double bd = i->buf[(y * i->width + x) * 4 + 2] / 255.0 * ad;

							// https://code.google.com/p/pulpcore/wiki/TutorialBlendModes
							double ar = as * (1 - ad) + ad;
							double rr = rs * (1 - ad) + rd;
							double gr = gs * (1 - ad) + gd;
							double br = bs * (1 - ad) + bd;

							buf[((y) * width + x) * 4 + 3] = ar * 255.0;
							buf[((y) * width + x) * 4 + 0] = rr / ar * 255.0;
							buf[((y) * width + x) * 4 + 1] = gr / ar * 255.0;
							buf[((y) * width + x) * 4 + 2] = br / ar * 255.0;
						} else if (i->depth == 3) {
							buf[((y) * width + x) * 4 + 0] = i->buf[(y * i->width + x) * 3 + 0];
							buf[((y) * width + x) * 4 + 1] = i->buf[(y * i->width + x) * 3 + 1];
							buf[((y) * width + x) * 4 + 2] = i->buf[(y * i->width + x) * 3 + 2];
							buf[((y) * width + x) * 4 + 3] = 255;
						} else {
							buf[((y) * width) * 4 + 0] = i->buf[(y * i->width + x) * i->depth + 0];
							buf[((y) * width) * 4 + 1] = i->buf[(y * i->width + x) * i->depth + 0];
							buf[((y) * width) * 4 + 2] = i->buf[(y * i->width + x) * i->depth + 0];
							buf[((y) * width) * 4 + 3] = 255;
						}
					}
				}

				free(i->buf);
				free(i);
			}
		}
	}

	unsigned char *rows[height];
	for (i = 0; i < height; i++) {
		rows[i] = buf + i * (4 * width);
	}

	convert(buf, width, height, de);

	png_structp png_ptr;
	png_infop info_ptr;

	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, fail, fail, fail);
	if (png_ptr == NULL) {
		fprintf(stderr, "PNG failure (write struct)\n");
		exit(EXIT_FAILURE);
	}
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		png_destroy_write_struct(&png_ptr, NULL);
		fprintf(stderr, "PNG failure (info struct)\n");
		exit(EXIT_FAILURE);
	}

	png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
	png_set_rows(png_ptr, info_ptr, rows);
	png_init_io(png_ptr, outfp);
	png_write_png(png_ptr, info_ptr, 0, NULL);
	png_destroy_write_struct(&png_ptr, &info_ptr);

	if (outfile != NULL) {
		fclose(outfp);
	}

	return 0;
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
    int res = 0;
    CURLcode curlerr;

    VCHI_INSTANCE_T vchiq_instance;
    VCHI_CONNECTION_T *vchi_connection;
    CEC_AllDevices_T logical_address;
    uint16_t physical_address;

    /* Make sure logs are written to disk */
    setlinebuf(stdout);
    setlinebuf(stderr);


    if (argc > 2) {
        printf("usage: %s [port]\n", argv[0]);
        return -1;
    }

    if (argc == 2) {
        port = atoi(argv[1]);
    }

    curlerr = curl_global_init(CURL_GLOBAL_NOTHING);
    if ( curlerr ) {
        printf("failed to init curl error=%d \"%s\"\n", curlerr,
                curl_easy_strerror(curlerr));
        return -1;
    }



    res = vchi_initialise(&vchiq_instance);
    if ( res != VCHIQ_SUCCESS ) {
        printf("failed to open vchiq instance\n");
        return -1;
    }

    res = vchi_connect( NULL, 0, vchiq_instance );
    if ( res != 0 ) {
        printf( "VCHI connection failed\n" );
        return -1;
    }

    vc_vchi_cec_init(vchiq_instance, &vchi_connection, 1);
    if ( res != 0 ) {
        printf( "VCHI CEC connection failed\n" );
        return -1;
    }

    vc_cec_register_callback(((CECSERVICE_CALLBACK_T) cec_callback), NULL);

#if 0
    vc_cec_register_all();
#endif

    vc_cec_get_logical_address(&logical_address);
    printf("logical_address: 0x%x\n", logical_address);

    vc_cec_set_vendor_id(CEC_VENDOR_ID_BROADCOM);
    vc_cec_set_osd_name("XBMC");

    vc_cec_get_physical_address(&physical_address);
    printf("physical_address: 0x%x\n", physical_address);

    vc_cec_send_ActiveSource(physical_address, 0);


    while (1) {
        might_be_dimmed = 1;
        sleep(10);
    }

    vchi_exit();

    curl_global_cleanup();

    return 0;
}
Exemplo n.º 5
0
int main(int argc, char* const argv[])
{
  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, "smtps://smtp.exmail.qq.com:465");

    /* 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_ALL);
    curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);

    /* 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_CAINFO, "/path/to/certificate.pem");
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

    /* 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, argv[1]);
    curl_easy_setopt(curl, CURLOPT_PASSWORD, argv[2]);

    /* 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;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
  CURL *curl;
  CURLcode res;

  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  const char buf[] = "Expect:";

  curl_global_init(CURL_GLOBAL_ALL);

  /* Fill in the file upload field */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "sendfile",
               CURLFORM_FILE, "postit2.c",
               CURLFORM_END);

  /* Fill in the filename field */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "filename",
               CURLFORM_COPYCONTENTS, "postit2.c",
               CURLFORM_END);


  /* Fill in the submit field too, even if this is rarely needed */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "submit",
               CURLFORM_COPYCONTENTS, "send",
               CURLFORM_END);

  curl = curl_easy_init();
  /* initalize custom header list (stating that Expect: 100-continue is not
     wanted */
  headerlist = curl_slist_append(headerlist, buf);
  if(curl) {
    /* what URL that receives this POST */
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/examplepost.cgi");
    if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) )
      /* only disable 100-continue header if explicitly requested */
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    /* 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));

    /* always cleanup */
    curl_easy_cleanup(curl);

    /* then cleanup the formpost chain */
    curl_formfree(formpost);
    /* free slist */
    curl_slist_free_all (headerlist);
  }
  return 0;
}
Exemplo n.º 7
0
Arquivo: fb.c Projeto: zaibon/fbdl
char *request(const char *url)
{
    CURL *curl;
    CURLcode status;
    char *data;
    long code;

    curl = curl_easy_init();
    data = malloc(BUFFER_SIZE);
    if(!curl || !data)
        return NULL;

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

    curl_easy_setopt(curl, CURLOPT_URL, url);
    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));
        return NULL;
    }

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

    curl_easy_cleanup(curl);
    curl_global_cleanup();

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

    return data;
}

list_t* getAlbums(const char* username)
{
	char url[URL_SIZE];
    char query[URL_SIZE];
	char* response = NULL;

	json_error_t error;
	json_t *root;

	json_t *album;
	json_t *aid;
	json_t *uid;
	json_t *name;
	json_t *count;

    album_t *content;

	list_t *list = NULL;
	list_t* tmp = NULL;
	list_t* prev = NULL;

    CURL *curl;

    if( (curl = curl_easy_init()) == NULL)
    {
        fprintf(stderr, "%s\n", "erreur curl_easy_init");
        return NULL;
    }

    snprintf(query, URL_SIZE, QUERY_ALBUM,username,username);
    strcpy(query,curl_easy_escape(curl, query, 0));
	snprintf(url,URL_SIZE, FB_QUERY_URL,query,FB_TOKEN);
    
    curl_easy_cleanup(curl);

	response = request(url);
	if(!response)
    {
        fprintf(stderr, "%s\n", "Erreur request");
		return NULL;
    }

	root = json_loads(response,0,&error);
	if(!root)
	free(response);

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


    for (int i = 0; i < json_array_size(root); i++)	
    {
    	album = json_array_get(root, i);

    	aid = json_object_get(album, "aid");
    	uid = json_object_get(album, "owner");
    	name = json_object_get(album, "name");
    	count = json_object_get(album, "photo_count");
    	

        content = (album_t*) malloc(sizeof(album_t));
    	tmp = (list_t*) malloc(sizeof(list_t));
        tmp->element = content;

        strncpy(content->aid, json_string_value(aid), 256);
    	content->uid = json_integer_value(uid);    	
        strncpy(content->name, json_string_value(name), 256);
    	content->count = json_integer_value(count);
    	tmp->next = NULL;

    	if(list == NULL) /* premier passage*/
		{	
    		list = tmp;
    		prev = tmp;
    	}
    	else
    	{
    		prev->next = tmp;
    		prev = tmp;
    	}
    }

    json_decref(root);
    return list;
}
Exemplo n.º 8
0
int main(void)
{
  int i;
  CURL *curl;
  CURLcode res;
  FILE *headerfile;
  const char *pPassphrase = NULL;

  static const char *pCertFile = "testcert.pem";
  static const char *pCACertFile="cacert.pem";

  const char *pKeyName;
  const char *pKeyType;

  const char *pEngine;

#ifdef USE_ENGINE
  pKeyName  = "rsa_test";
  pKeyType  = "ENG";
  pEngine   = "chil";            /* for nChiper HSM... */
#else
  pKeyName  = "testkey.pem";
  pKeyType  = "PEM";
  pEngine   = NULL;
#endif

  headerfile = fopen("dumpit", "w");

  curl_global_init(CURL_GLOBAL_DEFAULT);

  curl = curl_easy_init();
  if(curl) {
    /* what call to write: */
    curl_easy_setopt(curl, CURLOPT_URL, "HTTPS://your.favourite.ssl.site");
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, headerfile);

    for(i = 0; i < 1; i++) /* single-iteration loop, just to break out from */
    {
      if (pEngine)             /* use crypto engine */
      {
        if (curl_easy_setopt(curl, CURLOPT_SSLENGINE,pEngine) != CURLE_OK)
        {                     /* load the crypto engine */
          fprintf(stderr,"can't set crypto engine\n");
          break;
        }
        if (curl_easy_setopt(curl, CURLOPT_SSLENGINE_DEFAULT,1L) != CURLE_OK)
        { /* set the crypto engine as default */
          /* only needed for the first time you load
             a engine in a curl object... */
          fprintf(stderr,"can't set crypto engine as default\n");
          break;
        }
      }
      /* cert is stored PEM coded in file... */
      /* since PEM is default, we needn't set it for PEM */
      curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");

      /* set the cert for client authentication */
      curl_easy_setopt(curl,CURLOPT_SSLCERT,pCertFile);

      /* sorry, for engine we must set the passphrase
         (if the key has one...) */
      if (pPassphrase)
        curl_easy_setopt(curl,CURLOPT_KEYPASSWD,pPassphrase);

      /* if we use a key stored in a crypto engine,
         we must set the key type to "ENG" */
      curl_easy_setopt(curl,CURLOPT_SSLKEYTYPE,pKeyType);

      /* set the private key (file or ID in engine) */
      curl_easy_setopt(curl,CURLOPT_SSLKEY,pKeyName);

      /* set the file with the certs vaildating the server */
      curl_easy_setopt(curl,CURLOPT_CAINFO,pCACertFile);

      /* disconnect if we can't validate server's cert */
      curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,1L);

      /* 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));

      /* we are done... */
    }
    /* always cleanup */
    curl_easy_cleanup(curl);
  }

  curl_global_cleanup();

  return 0;
}
Exemplo n.º 9
0
static int
testExternalGet ()
{
  struct MHD_Daemon *d;
  CURL *c;
  char buf[2048];
  struct CBC cbc;
  CURLM *multi;
  CURLMcode mret;
  fd_set rs;
  fd_set ws;
  fd_set es;
  MHD_socket maxsock;
#ifdef MHD_WINSOCK_SOCKETS
  int maxposixs; /* Max socket number unused on W32 */
#else  /* MHD_POSIX_SOCKETS */
#define maxposixs maxsock
#endif /* MHD_POSIX_SOCKETS */
  int running;
  struct CURLMsg *msg;
  time_t start;
  struct timeval tv;

  multi = NULL;
  cbc.buf = buf;
  cbc.size = 2048;
  cbc.pos = 0;
  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
  if (d == NULL)
    return 256;
  c = curl_easy_init ();
  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
  /* note that the string below intentionally uses the
     various ways cookies can be specified to exercise the
     parser! Do not change! */
  curl_easy_setopt (c, CURLOPT_COOKIE,
                    "name1=var1; name2=var2,name3 ;name4=\"var4 with spaces\";");
  if (oneone)
    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  else
    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
  /* NOTE: use of CONNECTTIMEOUT without also
     setting NOSIGNAL results in really weird
     crashes on my system! */
  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);


  multi = curl_multi_init ();
  if (multi == NULL)
    {
      curl_easy_cleanup (c);
      MHD_stop_daemon (d);
      return 512;
    }
  mret = curl_multi_add_handle (multi, c);
  if (mret != CURLM_OK)
    {
      curl_multi_cleanup (multi);
      curl_easy_cleanup (c);
      MHD_stop_daemon (d);
      return 1024;
    }
  start = time (NULL);
  while ((time (NULL) - start < 5) && (multi != NULL))
    {
      maxsock = MHD_INVALID_SOCKET;
      maxposixs = -1;
      FD_ZERO (&rs);
      FD_ZERO (&ws);
      FD_ZERO (&es);
      curl_multi_perform (multi, &running);
      mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
      if (mret != CURLM_OK)
        {
          curl_multi_remove_handle (multi, c);
          curl_multi_cleanup (multi);
          curl_easy_cleanup (c);
          MHD_stop_daemon (d);
          return 2048;
        }
      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
        {
          curl_multi_remove_handle (multi, c);
          curl_multi_cleanup (multi);
          curl_easy_cleanup (c);
          MHD_stop_daemon (d);
          return 4096;
        }
      tv.tv_sec = 0;
      tv.tv_usec = 1000;
      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
        {
          if (EINTR != errno)
            abort ();
        }
      curl_multi_perform (multi, &running);
      if (running == 0)
        {
          msg = curl_multi_info_read (multi, &running);
          if (msg == NULL)
            break;
          if (msg->msg == CURLMSG_DONE)
            {
              if (msg->data.result != CURLE_OK)
                printf ("%s failed at %s:%d: `%s'\n",
                        "curl_multi_perform",
                        __FILE__,
                        __LINE__, curl_easy_strerror (msg->data.result));
              curl_multi_remove_handle (multi, c);
              curl_multi_cleanup (multi);
              curl_easy_cleanup (c);
              c = NULL;
              multi = NULL;
            }
        }
      MHD_run (d);
    }
  if (multi != NULL)
    {
      curl_multi_remove_handle (multi, c);
      curl_easy_cleanup (c);
      curl_multi_cleanup (multi);
    }
  MHD_stop_daemon (d);
  if (cbc.pos != strlen ("/hello_world"))
    return 8192;
  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
    return 16384;
  return 0;
}
Exemplo n.º 10
0
void delete_meta(int worker_no) {
    long http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json; charset=UTF-8");
    CURLcode curl_res;
    char request_url[255] = {0};

    snprintf(request_url, 255, "%s%s/%s", globals.elastic_path, current_data[worker_no].poolname, current_data[worker_no].filename);

    current_data[worker_no].elastic = curl_easy_init();
    if (NULL == current_data[worker_no].elastic) {
        return;
    }
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_USERAGENT, "WebRados");
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_SSL_VERIFYPEER, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_SSL_VERIFYHOST, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_FORBID_REUSE, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_FRESH_CONNECT, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_NOSIGNAL, true);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_WRITEFUNCTION, NULL);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_WRITEDATA, fopen("/dev/null", "w"));
#if LIBCURL_VERSION_MINOR >= 25
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_TCP_KEEPALIVE, true);
#endif
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_VERBOSE, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_URL, request_url);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_HTTPHEADER, headers);
    curl_res = curl_easy_perform(current_data[worker_no].elastic);

    curl_easy_getinfo(current_data[worker_no].elastic, CURLINFO_RESPONSE_CODE, &http_code);
    if (curl_res != CURLE_OK || http_code >= 400) {
        logger("Failed to open '%s' on remote server for delete - %s [HTTP code: %ld]", globals.elastic_path, curl_easy_strerror(curl_res), http_code);
    }
    if (headers != NULL) {
        curl_slist_free_all(headers);
    }
}
Exemplo n.º 11
0
static void handleError(CURLcode code) {
    if (code != CURLE_OK) {
        throw std::runtime_error(std::string("CURL easy error: ") + curl_easy_strerror(code));
    }
}
Exemplo n.º 12
0
void add_meta(int worker_no) {

    long http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json; charset=UTF-8");
    CURLcode curl_res;
    char request_url[255] = {0};
    char data[1024] = {0};

    snprintf(request_url, 255, "%s%s/%s", globals.elastic_path, current_data[worker_no].poolname, current_data[worker_no].filename);
    snprintf(data, 1024, "{\"Created\":\"%ld\",\"Bytes\":\"%ld\",\"Extension\":\"%s\",\"Mime\":\"%s\",\"Path\":\"%s\"}",
            current_data[worker_no].metadata.c_time,
            current_data[worker_no].metadata.f_size,
            current_data[worker_no].metadata.extension,
            current_data[worker_no].metadata.mime,
            current_data[worker_no].metadata.path
            );

    current_data[worker_no].elastic = curl_easy_init();
    if (NULL == current_data[worker_no].elastic) {
        return;
    }

    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_USERAGENT, "WebRados");
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_SSL_VERIFYPEER, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_SSL_VERIFYHOST, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_FORBID_REUSE, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_FRESH_CONNECT, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_NOSIGNAL, true);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_WRITEFUNCTION, NULL);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_WRITEDATA, fopen("/dev/null", "w"));
#if LIBCURL_VERSION_MINOR >= 25
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_TCP_KEEPALIVE, true);
#endif
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_VERBOSE, false);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_URL, request_url);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t) - 1);
    curl_easy_setopt(current_data[worker_no].elastic, CURLOPT_HTTPHEADER, headers);
    curl_res = curl_easy_perform(current_data[worker_no].elastic);

    curl_easy_getinfo(current_data[worker_no].elastic, CURLINFO_RESPONSE_CODE, &http_code);
    if (curl_res != CURLE_OK || http_code >= 400) {
        logger("Failed to open '%s' on remote server for indexing - %s [HTTP code: %ld]", globals.elastic_path, curl_easy_strerror(curl_res), http_code);
    }
    if (headers != NULL) {
        curl_slist_free_all(headers);
    }
}
Exemplo n.º 13
0
int main(void)
{
	CURLM *cm;
	CURLMsg *msg;
	long L;
	unsigned int C = 0;
	int M, Q, U = -1;
	fd_set R, W, E;
	struct timeval T;

	curl_global_init(CURL_GLOBAL_ALL);

	cm = curl_multi_init();

	/* we can optionally limit the total amount of connections this multi handle
	   uses */
	curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long)MAX);

	for (C = 0; C < MAX; ++C) {
		init(cm, C);
	}

	while (U) {
		curl_multi_perform(cm, &U);

		if (U) {
			FD_ZERO(&R);
			FD_ZERO(&W);
			FD_ZERO(&E);

			if (curl_multi_fdset(cm, &R, &W, &E, &M)) {
				fprintf(stderr, "E: curl_multi_fdset\n");
				return EXIT_FAILURE;
			}

			if (curl_multi_timeout(cm, &L)) {
				fprintf(stderr, "E: curl_multi_timeout\n");
				return EXIT_FAILURE;
			}
			if (L == -1)
				L = 100;

			if (M == -1) {
#ifdef WIN32
				Sleep(L);
#else
				sleep(L / 1000);
#endif
			} else {
				T.tv_sec = L / 1000;
				T.tv_usec = (L % 1000) * 1000;

				if (0 > select(M + 1, &R, &W, &E, &T)) {
					fprintf(stderr,
						"E: select(%i,,,,%li): %i: %s\n",
						M + 1, L, errno,
						strerror(errno));
					return EXIT_FAILURE;
				}
			}
		}

		while ((msg = curl_multi_info_read(cm, &Q))) {
			if (msg->msg == CURLMSG_DONE) {
				char *url;
				CURL *e = msg->easy_handle;
				curl_easy_getinfo(msg->easy_handle,
						  CURLINFO_PRIVATE, &url);
				fprintf(stderr, "R: %d - %s <%s>\n",
					msg->data.result,
					curl_easy_strerror(msg->data.result),
					url);
				curl_multi_remove_handle(cm, e);
				curl_easy_cleanup(e);
			} else {
				fprintf(stderr, "E: CURLMsg (%d)\n", msg->msg);
			}
			if (C < CNT) {
				init(cm, C++);
				U++;	/* just to prevent it from remaining at 0 if there are more
					   URLs to get */
			}
		}
	}

	curl_multi_cleanup(cm);
	curl_global_cleanup();

	return EXIT_SUCCESS;
}
Exemplo n.º 14
0
int main()
{
  char name1[] = "simple_COPYCONTENTS";
  char name2[] = "COPYCONTENTS_+_CONTENTTYPE";
  char name3[] = "PTRNAME_+_NAMELENGTH_+_COPYNAME_+_CONTENTSLENGTH";
  char name4[] = "simple_PTRCONTENTS";
  char name5[] = "PTRCONTENTS_+_CONTENTSLENGTH";
  char name6[] = "PTRCONTENTS_+_CONTENTSLENGTH_+_CONTENTTYPE";
  char name7[] = "FILE1_+_CONTENTTYPE";
  char name8[] = "FILE1_+_FILE2";
  char name9[] = "FILE1_+_FILE2_+_FILE3";
  char name10[] = "ARRAY: FILE1_+_FILE2_+_FILE3";
  char name11[] = "FILECONTENT";
  char value1[] = "value for simple COPYCONTENTS";
  char value2[] = "value for COPYCONTENTS + CONTENTTYPE";
  char value3[] = "value for PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH";
  char value4[] = "value for simple PTRCONTENTS";
  char value5[] = "value for PTRCONTENTS + CONTENTSLENGTH";
  char value6[] = "value for PTRCOTNENTS + CONTENTSLENGTH + CONTENTTYPE";
  char value7[] = "inet_ntoa_r.h";
  char value8[] = "Makefile.b32";
  char type2[] = "image/gif";
  char type6[] = "text/plain";
  char type7[] = "text/html";
  int name3length = strlen(name3);
  int value3length = strlen(value3);
  int value5length = strlen(value4);
  int value6length = strlen(value5);
  int errors = 0;
  CURLcode rc;
  size_t size;
  size_t nread;
  char buffer[4096];
  struct curl_httppost *httppost=NULL;
  struct curl_httppost *last_post=NULL;
  struct curl_forms forms[4];

  struct FormData *form;
  struct Form formread;

  if (FormAddTest("simple COPYCONTENTS test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name1, CURLFORM_COPYCONTENTS, value1,
                  CURLFORM_END))
    ++errors;
  if (FormAddTest("COPYCONTENTS  + CONTENTTYPE test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name2, CURLFORM_COPYCONTENTS, value2,
                  CURLFORM_CONTENTTYPE, type2, CURLFORM_END))
    ++errors;
  /* make null character at start to check that contentslength works
     correctly */
  name3[1] = '\0';
  value3[1] = '\0';
  if (FormAddTest("PTRNAME + NAMELENGTH + COPYNAME + CONTENTSLENGTH test",
                  &httppost, &last_post,
                  CURLFORM_PTRNAME, name3, CURLFORM_COPYCONTENTS, value3,
                  CURLFORM_CONTENTSLENGTH, value3length,
                  CURLFORM_NAMELENGTH, name3length, CURLFORM_END))
    ++errors;
  if (FormAddTest("simple PTRCONTENTS test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name4, CURLFORM_PTRCONTENTS, value4,
                  CURLFORM_END))
    ++errors;
  /* make null character at start to check that contentslength works
     correctly */
  value5[1] = '\0';
  if (FormAddTest("PTRCONTENTS + CONTENTSLENGTH test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name5, CURLFORM_PTRCONTENTS, value5,
                  CURLFORM_CONTENTSLENGTH, value5length, CURLFORM_END))
    ++errors;
  /* make null character at start to check that contentslength works
     correctly */
  value6[1] = '\0';
  if (FormAddTest("PTRCONTENTS + CONTENTSLENGTH + CONTENTTYPE test",
                  &httppost, &last_post,
                  CURLFORM_COPYNAME, name6, CURLFORM_PTRCONTENTS, value6,
                  CURLFORM_CONTENTSLENGTH, value6length,
                  CURLFORM_CONTENTTYPE, type6, CURLFORM_END))
    ++errors;
  if (FormAddTest("FILE + CONTENTTYPE test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name7, CURLFORM_FILE, value7,
                  CURLFORM_CONTENTTYPE, type7, CURLFORM_END))
    ++errors;
  if (FormAddTest("FILE1 + FILE2 test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name8, CURLFORM_FILE, value7,
                  CURLFORM_FILE, value8, CURLFORM_END))
    ++errors;
  if (FormAddTest("FILE1 + FILE2 + FILE3 test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name9, CURLFORM_FILE, value7,
                  CURLFORM_FILE, value8, CURLFORM_FILE, value7, CURLFORM_END))
    ++errors;
  forms[0].option = CURLFORM_FILE;
  forms[0].value  = value7;
  forms[1].option = CURLFORM_FILE;
  forms[1].value  = value8;
  forms[2].option = CURLFORM_FILE;
  forms[2].value  = value7;
  forms[3].option  = CURLFORM_END;
  if (FormAddTest("FILE1 + FILE2 + FILE3 ARRAY test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name10, CURLFORM_ARRAY, forms,
                  CURLFORM_END))
    ++errors;
  if (FormAddTest("FILECONTENT test", &httppost, &last_post,
                  CURLFORM_COPYNAME, name11, CURLFORM_FILECONTENT, value7,
                  CURLFORM_END))
    ++errors;

  rc = Curl_getFormData(&form, httppost, NULL, &size);
  if(rc != CURLE_OK) {
    if(rc != CURLE_READ_ERROR) {
      const char *errortext = curl_easy_strerror(rc);
      fprintf(stdout, "\n==> Curl_getFormData error: %s\n", errortext);
    }
    return 0;
  }

  Curl_FormInit(&formread, form);

  do {
    nread = Curl_FormReader(buffer, 1, sizeof(buffer),
                            (FILE *)&formread);

    if(nread < 1)
      break;
    fwrite(buffer, nread, 1, stdout);
  } while(1);

  fprintf(stdout, "size: %d\n", size);
  if (errors)
    fprintf(stdout, "\n==> %d Test(s) failed!\n", errors);
  else
    fprintf(stdout, "\nAll Tests seem to have worked (please check output)\n");

  return 0;
}
Exemplo n.º 15
0
BtcRpcPacketPtr BtcRpcCurl::SendRpc(BtcRpcPacketPtr jsonString)
{
    if(!curl)
    {
        return BtcRpcPacketPtr();
    }

    WaitMutex();

    BtcRpcPacketPtr receivedData = BtcRpcPacketPtr(new BtcRpcPacket()); // used when receiving data

    /* Now specify we want to POST data */
    curl_easy_setopt(curl, CURLOPT_POST, 1L);

    /* we want to use our own read function (called when sending) */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
    /* pointer to pass to our read function (cointains data to send) */
    curl_easy_setopt(curl, CURLOPT_READDATA, jsonString.get());

    /* we want to use our own write function (called when receiving) */
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    /* pointer to pass to our write function (we'll write received data into it) */
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, receivedData.get());

    /* get verbose debug output please */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);

    /*
        If you use POST to a HTTP 1.1 server, you can send data without knowing
        the size before starting the POST if you use chunked encoding. You
        enable this by adding a header like "Transfer-Encoding: chunked" with
        CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must
        specify the size in the request.
    */
    #ifdef USE_CHUNKED
    {
        struct curl_slist *chunk = NULL;

        chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        /* use curl_slist_free_all() after the *perform() call to free this
            list again */
    }
    #else
        /* Set the expected POST size. If you want to POST large amounts of data,
            consider CURLOPT_POSTFIELDSIZE_LARGE */
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonString->size());
    #endif

    #ifdef DISABLE_EXPECT
    {
        /*
            Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue"
            header.  You can disable this header with CURLOPT_HTTPHEADER as usual.
            NOTE: if you want chunked transfer too, you need to combine these two
            since you can only set one list of headers with CURLOPT_HTTPHEADER. */

        /* A less good option would be to enforce HTTP 1.0, but that might also
            have other implications. */
        struct curl_slist *chunk = NULL;

        chunk = curl_slist_append(chunk, "Expect:");
        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        /* use curl_slist_free_all() after the *perform() call to free this
            list again */
    }
    #endif

    /* 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));

        mutex = false;
        return BtcRpcPacketPtr();
    }

    //if(receivedData->data != NULL)
    //    opentxs::Log::Output(0, receivedData->data);

    // we have to copy the response because for some reason the next few lines set the smart pointer to NULL (?!?!??)
    BtcRpcPacketPtr packetCopy = BtcRpcPacketPtr(new BtcRpcPacket(receivedData));

    receivedData.reset();

    int httpcode = 0;
    curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &httpcode);
    if (httpcode == 401)
    {
        std::printf("Error connecting to bitcoind: Wrong username or password\n");
        std::cout.flush();
        mutex = false;
        return BtcRpcPacketPtr();
    }
    else if (httpcode == 500)
    {
        std::printf("Bitcoind internal server error\n");
        std::cout.flush();
        // don't return
    }
    else if (httpcode != 200)
    {
        std::printf("BtcRpc curl error:\nHTTP response code %d\n", httpcode);
        std::cout.flush();
        mutex = false;
        return BtcRpcPacketPtr();
    }

    mutex = false;
    return packetCopy;
}
Exemplo n.º 16
0
int RD_ListGroup(struct rd_group *grp[],
		  	const char hostname[],
			const char username[],
			const char passwd[],
			const char ticket[],
			const char groupname[],
                        const char user_agent[],
                  	unsigned *numrecs)
{
  char url[1500];
  CURL *curl=NULL;
  XML_Parser parser;
  struct xml_data xml_data;
  long response_code;
  char errbuf[CURL_ERROR_SIZE];
  CURLcode res;
  char user_agent_string[255];
  struct curl_httppost *first=NULL;
  struct curl_httppost *last=NULL;

   /* set number of recs so if fail already set */
  *numrecs = 0;

  if((curl=curl_easy_init())==NULL) {
    curl_easy_cleanup(curl);
    return -1;
  }

  /*
   * Setup the CURL call
   */
  memset(&xml_data,0,sizeof(xml_data));
  parser=XML_ParserCreate(NULL);
  XML_SetUserData(parser,&xml_data);
  XML_SetElementHandler(parser,__ListGroupElementStart,
			__ListGroupElementEnd);
  XML_SetCharacterDataHandler(parser,__ListGroupElementData);
  snprintf(url,1500,"http://%s/rd-bin/rdxport.cgi",hostname);

  curl_formadd(&first,
	&last,
	CURLFORM_PTRNAME,
	"COMMAND",
        CURLFORM_COPYCONTENTS,
        "5",
        CURLFORM_END);

  curl_formadd(&first,
	&last,
	CURLFORM_PTRNAME,
	"LOGIN_NAME",
	CURLFORM_COPYCONTENTS,
	username,
	CURLFORM_END); 

  curl_formadd(&first,
	&last,
	CURLFORM_PTRNAME,
	"PASSWORD",
        CURLFORM_COPYCONTENTS,
	passwd,
	CURLFORM_END);

  curl_formadd(&first,
	&last,
	CURLFORM_PTRNAME,
	"TICKET",
        CURLFORM_COPYCONTENTS,
        ticket,
	CURLFORM_END);

  curl_formadd(&first,
	&last,
	CURLFORM_PTRNAME,
	"GROUP_NAME",
        CURLFORM_COPYCONTENTS,
        groupname,
	CURLFORM_END);

  //
  // Check if User Agent Present otherwise set to default
  if (strlen(user_agent)> 0){
    curl_easy_setopt(curl, CURLOPT_USERAGENT,user_agent);
  }
  else
  {
    strcpy(user_agent_string, RD_GetUserAgent());
    strcat(user_agent_string,VERSION);
    curl_easy_setopt(curl, CURLOPT_USERAGENT,user_agent_string);
  }
  curl_easy_setopt(curl,CURLOPT_WRITEDATA,parser);
  curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,__ListGroupCallback);
  curl_easy_setopt(curl,CURLOPT_URL,url);
  curl_easy_setopt(curl,CURLOPT_POST,1);
  curl_easy_setopt(curl,CURLOPT_HTTPPOST,first);
  curl_easy_setopt(curl,CURLOPT_NOPROGRESS,1);
  curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,errbuf);
  //  curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
  res = curl_easy_perform(curl);
  if(res != CURLE_OK) {
    #ifdef RIVC_DEBUG_OUT
        size_t len = strlen(errbuf);
        fprintf(stderr, "\nlibcurl error: (%d)", res);
        if (len)
            fprintf(stderr, "%s%s", errbuf,
                ((errbuf[len-1] != '\n') ? "\n" : ""));
        else
            fprintf(stderr, "%s\n", curl_easy_strerror(res));
    #endif
    curl_easy_cleanup(curl);
    return -1;
  }

/* The response OK - so figure out if we got what we wanted.. */

  curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&response_code);
  curl_formfree(first);
  curl_easy_cleanup(curl);
  
  if (response_code > 199 && response_code < 300) {
    *grp=xml_data.group;
    *numrecs = 1;
    return 0;
  }
  else {
    #ifdef RIVC_DEBUG_OUT
        fprintf(stderr," rd_listgroup Call Returned Error: %s\n",xml_data.strbuf);
    #endif
    return (int)response_code;
  }
}
Exemplo n.º 17
0
int main(void)
{
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl) {
        char nline[256];

        curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/");
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); /* just to start the cookie engine */
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res));
            return 1;
        }

        print_cookies(curl);

        printf("Erasing curl's knowledge of cookies!\n");
        curl_easy_setopt(curl, CURLOPT_COOKIELIST, "ALL");

        print_cookies(curl);

        printf("-----------------------------------------------\n" "Setting a cookie \"PREF\" via cookie interface:\n");
#ifdef WIN32
# define snprintf _snprintf
#endif
        /* Netscape format cookie */
        snprintf(nline, sizeof(nline), "%s\t%s\t%s\t%s\t%lu\t%s\t%s",
                 ".google.com", "TRUE", "/", "FALSE", (unsigned long)time(NULL) + 31337UL, "PREF",
                 "hello google, i like you very much!");
        res = curl_easy_setopt(curl, CURLOPT_COOKIELIST, nline);
        if (res != CURLE_OK) {
            fprintf(stderr, "Curl curl_easy_setopt failed: %s\n", curl_easy_strerror(res));
            return 1;
        }

        /* HTTP-header style cookie */
        snprintf(nline, sizeof(nline),
                 "Set-Cookie: OLD_PREF=3d141414bf4209321; " "expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com");
        res = curl_easy_setopt(curl, CURLOPT_COOKIELIST, nline);
        if (res != CURLE_OK) {
            fprintf(stderr, "Curl curl_easy_setopt failed: %s\n", curl_easy_strerror(res));
            return 1;
        }

        print_cookies(curl);

        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res));
            return 1;
        }
    } else {
        fprintf(stderr, "Curl init failed!\n");
        return 1;
    }

    curl_global_cleanup();
    return 0;
}
bool cURL_SM::SDK_OnLoad(char *error, size_t maxlength, bool late)
{
    shutdown = false;

    CURLcode code;

    code = curl_global_init(CURL_GLOBAL_ALL);

    if(code)
    {
        smutils->Format(error, maxlength, "%s", curl_easy_strerror(code));
        return false;
    }

    myself_Identity = myself->GetIdentity();

    bool valid = true;

    HandleError err_file, err_handle, err_webform, err_slist;
    g_cURLFile = handlesys->CreateType("cURLFile", this, 0, NULL, NULL, myself_Identity, &err_file);
    g_cURLHandle = handlesys->CreateType("cURLHandle", this, 0, NULL, NULL, myself_Identity, &err_handle);
    g_WebForm = handlesys->CreateType("cURLWebForm", this, 0, NULL, NULL, myself_Identity, &err_webform);
    g_cURLSlist = handlesys->CreateType("cURLSlist", this, 0, NULL, NULL, myself_Identity, &err_slist);

    if(g_cURLFile == 0)
    {
        handlesys->RemoveType(g_cURLFile, myself_Identity);
        g_cURLFile = 0;
        snprintf(error, maxlength, "Could not create CURL file type (err: %d)", err_file);
        valid = false;
    }

    if(g_cURLHandle == 0)
    {
        handlesys->RemoveType(g_cURLHandle, myself_Identity);
        g_cURLHandle = 0;
        snprintf(error, maxlength, "Could not create CURL handle type (err: %d)", err_handle);
        valid = false;
    }

    if(g_WebForm == 0)
    {
        handlesys->RemoveType(g_WebForm, myself_Identity);
        g_WebForm = 0;
        snprintf(error, maxlength, "Could not create CURL WebForm type (err: %d)", err_webform);
        valid = false;
    }

    if(g_cURLSlist == 0)
    {
        handlesys->RemoveType(g_cURLSlist, myself_Identity);
        g_cURLSlist = 0;
        snprintf(error, maxlength, "Could not create CURL Slist type (err: %d)", err_slist);
        valid = false;
    }

    if(!valid)
        return false;

    sharesys->AddNatives(myself, g_cURLNatives);

    g_cURLManager.SDK_OnLoad();

    g_OpensslManager.SDK_OnLoad();

    return true;
}
int main(int argc, char *argv[])
{
    CURL *curl;
    CURLcode res;

    struct curl_httppost *formpost=NULL;
    struct curl_httppost *lastptr=NULL;
    struct curl_slist *headerlist=NULL;
    static const char buf[] = "Expect:";
    
    ftp_get();

    curl_global_init(CURL_GLOBAL_ALL);

    /* Fill in the file upload field */
    curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "sendfile",
             CURLFORM_FILE, "./00-13.jpg",
             CURLFORM_END);

    /* Fill in the filename field */
    //curl_formadd(&formpost,
    //         &lastptr,
    //         CURLFORM_COPYNAME, "filename",
    //         CURLFORM_COPYCONTENTS, "00-13.jpg",
    //         CURLFORM_END);
    // char *memblock = "asdfkasfkjaskdjfkajsdfkjaklsdjffkl;ja";
    // long memblock_length = strlen(memblock);
    //curl_formadd(&formpost, &lastptr, 
    //         CURLFORM_COPYNAME, "file", 
    //         CURLFORM_BUFFER, "unnamed.jpg", 
    //         CURLFORM_BUFFERPTR, memblock,     
    //         CURLFORM_BUFFERLENGTH, memblock_length, 
    //         CURLFORM_CONTENTTYPE, "image/jpg",
    //         CURLFORM_END); 

    /* Fill in the submit field too, even if this is rarely needed */
    curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "submit",
             CURLFORM_COPYCONTENTS, "Submit",
             CURLFORM_END);

    curl = curl_easy_init();
    
    /* initalize custom header list (stating that Expect: 100-continue is not wanted */
    headerlist = curl_slist_append(headerlist, buf);
    if(curl) {
        /* what URL that receives this POST */
            curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/upload");
        if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) )
          /* only disable 100-continue header if explicitly requested */
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
        
        /* 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));
        
        /* always cleanup */
        curl_easy_cleanup(curl);
        
        /* then cleanup the formpost chain */
        curl_formfree(formpost);
        /* free slist */
        curl_slist_free_all (headerlist);
    }
    return 0;
}
Exemplo n.º 20
0
void ecurl_auto_init(void) {
     CURLcode code;
     code = curl_global_init(CURL_GLOBAL_ALL);
     if (code) {
          fprintf(stderr, "**** ecurl_auto_init: global init returned %d (%s)\n", code, curl_easy_strerror(code));
     } else {
          register_handler(ecurl_se_handler);
     }
}
Exemplo n.º 21
0
// Fetch JSON from OpenWeatherMap
struct json_write_result *
owm_fetch_remote (const char method, const char * location, const char scale,
                  const char * file_cache_path, const char * api_key) {

    CURL * handle;
    CURLcode result;

    char * data = calloc(1, BUFFER_SIZE);
    static struct json_write_result written_result;
    written_result.data = data;
    written_result.position = 0;

    char url [256] = {'\0'};
    char * fetch_method;
    char * fetch_scale;

    switch ( method ) {
        case 'i':
            fetch_method = "id";
            break;

        default:
            fetch_method = "q";
            break;
    }

    switch ( scale ) {
        case 'i':
            fetch_scale = "imperial";
            break;

        default:
            fetch_scale = "metric";
            break;
    }

    handle = curl_easy_init();

    if ( handle ) {
        const char * provider =
            "http://api.openweathermap.org/data/2.5/weather";

        char * encoded_location = curl_easy_escape(handle, location, 0);

        snprintf(url, sizeof(url), "%s?%s=%s&units=%s&APPID=%s", provider,
                 fetch_method, encoded_location, fetch_scale, api_key);

        curl_easy_setopt(handle, CURLOPT_URL, url);
        curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data_buffer);
        curl_easy_setopt(handle, CURLOPT_WRITEDATA, &written_result);

        result = curl_easy_perform(handle);
        if ( result != CURLE_OK ) {
            fprintf(stderr, "Failed to retrieve data (%s)\n",
                    curl_easy_strerror(result));

            curl_easy_cleanup(handle);
            curl_free(encoded_location);
            exit(1);
        }

        curl_free(encoded_location);
    }

    if ( file_cache_path ) {
        json_error_t err;
        json_t * resjson = json_loads(written_result.data, 0, &err);
        size_t flags = JSON_PRESERVE_ORDER | JSON_INDENT(2);
        if ( resjson && json_dump_file(resjson, file_cache_path, flags) == -1 ) {
            fprintf(stderr, "Error caching file\n");
            exit(1);
        }
    } curl_easy_cleanup(handle);

    return &written_result;
}
Exemplo n.º 22
0
int uploadFile(const char* file){
    int ret;

    CURL *curl;
    CURLcode res;

    FILE* in;
    char* file_content;
    struct stat file_info;

    curl_off_t file_size;
    long post_size;
    char upload_url[1024];
    
    stat(file, &file_info);
    file_size = (curl_off_t) file_info.st_size;
    post_size = (long)       file_info.st_size;

    file_content = malloc(file_size * sizeof(char));
    if (file_content == NULL){
        sprintf(MSG_BUFFER, "%s", "upload: tried buffer a file but out of memory");
        display_msg(LOG_ERR, MSG_BUFFER);
        exit(1);
    }

    in = fopen(file, "rb");
    fread(file_content, sizeof(char), file_size, in);

    sprintf(upload_url, "%s?%s=%s&%s=%s", server_url, HTTP_ARG_USERNAME, server_username, HTTP_ARG_FILENAME, file);
    sprintf(MSG_BUFFER, "station infomation uploading to %s", upload_url);
    display_msg(LOG_INFO, MSG_BUFFER);

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if (curl){
        //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // for debugging
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post_size);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_content);
        curl_easy_setopt(curl, CURLOPT_URL, upload_url);
        
        res = curl_easy_perform(curl);

        if (res != CURLE_OK){
            sprintf(MSG_BUFFER, "curl_easy_perform() failed: %s", curl_easy_strerror(res));
            display_msg(LOG_ERR, MSG_BUFFER);
            ret = -1;
        }
        else {
            ret = 0;
        }

        curl_easy_cleanup(curl);
    }

    free(file_content);
    fclose(in);

    curl_global_cleanup();

    return ret;
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
  CURL *curl_handle;
  CURLcode res;
  int prtall = 0, prtsep = 0, prttime = 0;
  const char *url = URL_1M;
  char *appname = argv[0];

  if(argc > 1) {
    /* parse input parameters */
    for(argc--, argv++; *argv; argc--, argv++) {
      if(strncasecmp(*argv, "-", 1) == 0) {
        if(strncasecmp(*argv, "-H", 2) == 0) {
          fprintf(stderr,
                  "\rUsage: %s [-m=1|2|5|10|20|50|100] [-t] [-x] [url]\n",
                  appname);
          exit(1);
        }
        else if(strncasecmp(*argv, "-V", 2) == 0) {
          fprintf(stderr, "\r%s %s - %s\n",
                  appname, CHKSPEED_VERSION, curl_version());
          exit(1);
        }
        else if(strncasecmp(*argv, "-A", 2) == 0) {
          prtall = 1;
        }
        else if(strncasecmp(*argv, "-X", 2) == 0) {
          prtsep = 1;
        }
        else if(strncasecmp(*argv, "-T", 2) == 0) {
          prttime = 1;
        }
        else if(strncasecmp(*argv, "-M=", 3) == 0) {
          long m = strtol((*argv) + 3, NULL, 10);
          switch(m) {
          case 1:
            url = URL_1M;
            break;
          case 2:
            url = URL_2M;
            break;
          case 5:
            url = URL_5M;
            break;
          case 10:
            url = URL_10M;
            break;
          case 20:
            url = URL_20M;
            break;
          case 50:
            url = URL_50M;
            break;
          case 100:
            url = URL_100M;
            break;
          default:
            fprintf(stderr, "\r%s: invalid parameter %s\n",
                    appname, *argv + 3);
            exit(1);
          }
        }
        else {
          fprintf(stderr, "\r%s: invalid or unknown option %s\n",
                  appname, *argv);
          exit(1);
        }
      }
      else {
        url = *argv;
      }
    }
  }

  /* print separator line */
  if(prtsep) {
    printf("-------------------------------------------------\n");
  }
  /* print localtime */
  if(prttime) {
    time_t t = time(NULL);
    printf("Localtime: %s", ctime(&t));
  }

  /* init libcurl */
  curl_global_init(CURL_GLOBAL_ALL);

  /* init the curl session */
  curl_handle = curl_easy_init();

  /* specify URL to get */
  curl_easy_setopt(curl_handle, CURLOPT_URL, url);

  /* send all data to this function  */
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteCallback);

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

  /* get it! */
  res = curl_easy_perform(curl_handle);

  if(CURLE_OK == res) {
    double val;

    /* check for bytes downloaded */
    res = curl_easy_getinfo(curl_handle, CURLINFO_SIZE_DOWNLOAD, &val);
    if((CURLE_OK == res) && (val>0))
      printf("Data downloaded: %0.0f bytes.\n", val);

    /* check for total download time */
    res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &val);
    if((CURLE_OK == res) && (val>0))
      printf("Total download time: %0.3f sec.\n", val);

    /* check for average download speed */
    res = curl_easy_getinfo(curl_handle, CURLINFO_SPEED_DOWNLOAD, &val);
    if((CURLE_OK == res) && (val>0))
      printf("Average download speed: %0.3f kbyte/sec.\n", val / 1024);

    if(prtall) {
      /* check for name resolution time */
      res = curl_easy_getinfo(curl_handle, CURLINFO_NAMELOOKUP_TIME, &val);
      if((CURLE_OK == res) && (val>0))
        printf("Name lookup time: %0.3f sec.\n", val);

      /* check for connect time */
      res = curl_easy_getinfo(curl_handle, CURLINFO_CONNECT_TIME, &val);
      if((CURLE_OK == res) && (val>0))
        printf("Connect time: %0.3f sec.\n", val);
    }
  }
  else {
    fprintf(stderr, "Error while fetching '%s' : %s\n",
            url, curl_easy_strerror(res));
  }

  /* cleanup curl stuff */
  curl_easy_cleanup(curl_handle);

  /* we're done with libcurl, so clean it up */
  curl_global_cleanup();

  return 0;
}
Exemplo n.º 24
0
int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
{
/* See
http://msdn.microsoft.com/en-us/library/windows/desktop/aa380138(v=vs.85).aspx
   Shutting Down an Schannel Connection */
  struct SessionHandle *data = conn->data;
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];

  infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n",
        conn->host.name, conn->remote_port);

  if(connssl->ctxt) {
    SecBufferDesc BuffDesc;
    SecBuffer Buffer;
    SECURITY_STATUS sspi_status;
    SecBuffer outbuf;
    SecBufferDesc outbuf_desc;
    CURLcode code;
    TCHAR *host_name;
    DWORD dwshut = SCHANNEL_SHUTDOWN;

    InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
    InitSecBufferDesc(&BuffDesc, &Buffer, 1);

    sspi_status = s_pSecFn->ApplyControlToken(&connssl->ctxt->ctxt_handle,
                                              &BuffDesc);

    if(sspi_status != SEC_E_OK)
      failf(data, "schannel: ApplyControlToken failure: %s",
            Curl_sspi_strerror(conn, sspi_status));

#ifdef UNICODE
    host_name = Curl_convert_UTF8_to_wchar(conn->host.name);
    if(!host_name)
      return CURLE_OUT_OF_MEMORY;
#else
    host_name = conn->host.name;
#endif

    /* setup output buffer */
    InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
    InitSecBufferDesc(&outbuf_desc, &outbuf, 1);

    sspi_status = s_pSecFn->InitializeSecurityContext(
         &connssl->cred->cred_handle,
         &connssl->ctxt->ctxt_handle,
         host_name,
         connssl->req_flags,
         0,
         0,
         NULL,
         0,
         &connssl->ctxt->ctxt_handle,
         &outbuf_desc,
         &connssl->ret_flags,
         &connssl->ctxt->time_stamp);

#ifdef UNICODE
    free(host_name);
#endif

    if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
      /* send close message which is in output buffer */
      ssize_t written;
      code = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer,
                              outbuf.cbBuffer, &written);

      s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
      if((code != CURLE_OK) || (outbuf.cbBuffer != (size_t)written)) {
        infof(data, "schannel: failed to send close msg: %s"
              " (bytes written: %zd)\n", curl_easy_strerror(code), written);
      }
    }
    /* free SSPI Schannel API security context handle */
    if(connssl->ctxt) {
      s_pSecFn->DeleteSecurityContext(&connssl->ctxt->ctxt_handle);
      free(connssl->ctxt);
      connssl->ctxt = NULL;
    }
  }

  /* free internal buffer for received encrypted data */
  if(connssl->encdata_buffer != NULL) {
    free(connssl->encdata_buffer);
    connssl->encdata_buffer = NULL;
    connssl->encdata_length = 0;
    connssl->encdata_offset = 0;
  }

  /* free internal buffer for received decrypted data */
  if(connssl->decdata_buffer != NULL) {
    free(connssl->decdata_buffer);
    connssl->decdata_buffer = NULL;
    connssl->decdata_length = 0;
    connssl->decdata_offset = 0;
  }

  return CURLE_OK;
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
  struct MHD_Daemon *d;
  fd_set rs;
  fd_set ws;
  fd_set es;
  MHD_socket max;
  CURL *c;
  CURLM *multi;
  CURLMcode mret;
  struct CURLMsg *msg;
  int running;
  struct timeval tv;
  int extra;

  d = MHD_start_daemon(0,
		       8000,
		       NULL,
		       NULL,
		       &callback,
		       NULL,
		       MHD_OPTION_END);
  c = curl_easy_init ();
  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:8000/");
  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &discard_buffer);
  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
  multi = curl_multi_init ();
  if (multi == NULL)
    {
      curl_easy_cleanup (c);
      MHD_stop_daemon (d);
      return 1;
    }
  mret = curl_multi_add_handle (multi, c);
  if (mret != CURLM_OK)
    {
      curl_multi_cleanup (multi);
      curl_easy_cleanup (c);
      MHD_stop_daemon (d);
      return 2;
    }
  extra = 10;
  while ( (c != NULL) || (--extra > 0) )
    {
      max = MHD_INVALID_SOCKET;
      FD_ZERO(&ws);
      FD_ZERO(&rs);
      FD_ZERO(&es);
      curl_multi_perform (multi, &running);
      if (NULL != multi)
	{
	  mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
	  if (mret != CURLM_OK)
	    {
	      curl_multi_remove_handle (multi, c);
	      curl_multi_cleanup (multi);
	      curl_easy_cleanup (c);
	      MHD_stop_daemon (d);
	      return 3;
	    }
	}
      if (MHD_YES !=
	  MHD_get_fdset(d, &rs, &ws, &es, &max))
	{
          curl_multi_remove_handle (multi, c);
          curl_multi_cleanup (multi);
          curl_easy_cleanup (c);
          MHD_stop_daemon (d);
	  return 4;
	}
      tv.tv_sec = 0;
      tv.tv_usec = 1000;
      select(max + 1, &rs, &ws, &es, &tv);
      if (NULL != multi)
	{
	  curl_multi_perform (multi, &running);
	  if (running == 0)
	    {
	      msg = curl_multi_info_read (multi, &running);
	      if (msg == NULL)
		break;
	      if (msg->msg == CURLMSG_DONE)
		{
		  if (msg->data.result != CURLE_OK)
		    printf ("%s failed at %s:%d: `%s'\n",
			    "curl_multi_perform",
			    __FILE__,
			    __LINE__, curl_easy_strerror (msg->data.result));
		  curl_multi_remove_handle (multi, c);
		  curl_multi_cleanup (multi);
		  curl_easy_cleanup (c);
		  c = NULL;
		  multi = NULL;
		}
	    }
	}
      MHD_run(d);
    }
  MHD_stop_daemon(d);
  return 0;
}
void * requestFrag(void * tempthreaddata)
{
	CURL *curl;
	CURLcode res;
	png_structp png_ptr;
	png_infop info_ptr;
	
	bool received_all_fragments = false;

	struct threaddata * temp = (struct threaddata *) tempthreaddata;
#ifdef _DEBUG_1_
	printf("\n###0###\n");
	printf("%s", temp->url);
	fflush(stdout);
#endif
//Making URL for thread
	char * temp_url = malloc(256);
	#ifdef _DEBUG_1_
	printf("\n###566###\n");
	//printf("%s", sizeof(temp->url));
	fflush(stdout);
#endif
	strcpy(temp_url, temp->url);
	
	
#ifdef _DEBUG_1_
	printf("\n###555###\n");
	printf("%s", temp_url);
	fflush(stdout);
#endif

	curl = curl_easy_init();
	if (!curl)
		abort_("[main] could not initialize curl");

  
	png_bytep input_buffer = malloc(sizeof(png_byte)*BUF_SIZE);
	struct bufdata bd; 
	bd.buf = input_buffer; 
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bd);

	struct headerdata hd; hd.received_fragments = temp->received_fragments;
	curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hd);
	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_cb);
  
	//set url
	curl_easy_setopt(curl, CURLOPT_URL, temp_url);


	do {
		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		if (!png_ptr)
		  abort_("[main] png_create_read_struct failed");

		// reset input buffer
		bd.len = bd.pos = 0; bd.max_size = BUF_SIZE;

		// do curl request; check for errors
		//pthread_mutex_lock(&lock);
		res = curl_easy_perform(curl);
		//pthread_mutex_unlock(&lock);
		if(res != CURLE_OK)
		  abort_("[main] curl_easy_perform() failed: %s\n",
				  curl_easy_strerror(res));

		// read PNG (as downloaded from network) and copy it to output buffer
		png_bytep* row_pointers = read_png_file(png_ptr, &info_ptr, &bd);
		pthread_mutex_lock(&lock);
		paint_destination(png_ptr, row_pointers, hd.n*BUF_WIDTH, 0, temp->output_buffer);
		pthread_mutex_unlock(&lock);

		// free allocated memory
		for (int y=0; y<BUF_HEIGHT; y++)
		  free(row_pointers[y]);
		free(row_pointers);
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

		// check for unreceived fragments
		received_all_fragments = true;
		for (int i = 0; i < N; i++)
		  if (!temp->received_fragments[i])
			received_all_fragments = false;
  } while (!received_all_fragments);
  
  #ifdef _DEBUG_1_
	printf("\n###1###\n");
	fflush(stdout);
#endif
free(temp_url);
  free(input_buffer);
    curl_easy_cleanup(curl);
}
Exemplo n.º 27
0
int webhdfs_req_exec (webhdfs_req_t *req, int type) {
    struct curl_slist *headers = NULL;
    CURLcode err;
    CURL *curl;

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

    curl_easy_setopt(curl, CURLOPT_URL, req->buffer.blob);
    buffer_clear(&(req->buffer));

    curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req->upload == NULL);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, __webhdfs_req_write);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, req);

    switch (type) {
      case WEBHDFS_REQ_GET:
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
        break;
      case WEBHDFS_REQ_PUT:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
      case WEBHDFS_REQ_POST:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
      case WEBHDFS_REQ_DELETE:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
        break;
    }

    /* Upload Require two steps */
    if (req->upload != NULL) {
        char *url;

        if ((err = curl_easy_perform(curl)))
            fprintf(stderr, "%s\n", curl_easy_strerror(err));

        curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &url);

        curl_easy_setopt(curl, CURLOPT_URL, url);

        headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_READFUNCTION, __webhdfs_req_read);
        curl_easy_setopt(curl, CURLOPT_READDATA, req);

        switch (type) {
          case WEBHDFS_REQ_PUT:
            curl_easy_setopt(curl, CURLOPT_PUT, 1);
            break;
          case WEBHDFS_REQ_POST:
            curl_easy_setopt(curl, CURLOPT_POST, 1);
            break;
        }
    }

    buffer_clear(&(req->buffer));
    if ((err = curl_easy_perform(curl)))
        fprintf(stderr, "%s\n", curl_easy_strerror(err));

    if (headers != NULL)
        curl_slist_free_all(headers);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &(req->rcode));
    curl_easy_cleanup(curl);

    return(err != 0);
}
Exemplo n.º 28
0
	std::string curl_category_impl::message(int ev) const
	{
		return curl_easy_strerror(static_cast<CURLcode>(ev));
	}
Exemplo n.º 29
0
/**
 * Connect and set position values from focuser response.
**/
bool IpFocus::Connect()
{

    if (FocuserEndpointT[0].text == NULL)
    {
        DEBUG(INDI::Logger::DBG_ERROR, "Focuser HTTP API endpoint is not available. Set it in the options tab");
        return false;
    }

    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, FocuserEndpointT[0].text);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); //10 sec timeout
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        /* Check for errors */
        if(res != CURLE_OK) {
            DEBUGF(INDI::Logger::DBG_ERROR, "Connecttion to FOCUSER failed:%s",curl_easy_strerror(res));
            DEBUG(INDI::Logger::DBG_ERROR, "Is the HTTP API endpoint correct? Set it in the options tab. Can you ping the focuser?");
            return false;
        }
        /* always cleanup */
        curl_easy_cleanup(curl);

        char srcBuffer[readBuffer.size()];
        strncpy(srcBuffer, readBuffer.c_str(), readBuffer.size());
        char *source = srcBuffer;
        // do not forget terminate source string with 0
        char *endptr;
        JsonValue value;
        JsonAllocator allocator;
        int status = jsonParse(source, &endptr, &value, allocator);
        if (status != JSON_OK)
        {
            DEBUGF(INDI::Logger::DBG_ERROR, "%s at %zd", jsonStrError(status), endptr - source);
            DEBUGF(INDI::Logger::DBG_DEBUG, "%s", readBuffer.c_str());
            return IPS_ALERT;
        }
        DEBUGF(INDI::Logger::DBG_DEBUG, "Focuser response %s", readBuffer.c_str());
        JsonIterator it;
        for (it = begin(value); it!= end(value); ++it) {
            DEBUGF(INDI::Logger::DBG_DEBUG, "iterating %s", it->key);
            if (!strcmp(it->key, "absolutePosition")) {
                DEBUGF(INDI::Logger::DBG_DEBUG, "Setting absolute position from response %g", it->value.toNumber());
                FocusAbsPosN[0].value = it->value.toNumber();
            }
            if (!strcmp(it->key, "maxPosition")) {
                DEBUGF(INDI::Logger::DBG_DEBUG, "Setting max position from response %g", it->value.toNumber());
                FocusAbsPosN[0].max = it->value.toNumber();
            }
            if (!strcmp(it->key, "minPosition")) {
                DEBUGF(INDI::Logger::DBG_DEBUG, "Setting min position from response %g", it->value.toNumber());
                FocusAbsPosN[0].min = it->value.toNumber();
            }
        }
    }

    return true;
}
Exemplo n.º 30
0
Arquivo: io.c Projeto: brentp/bigwig
URL_t *urlOpen(char *fname, CURLcode (*callBack)(CURL*)) {
    URL_t *URL = calloc(1, sizeof(URL_t));
    if(!URL) return NULL;
    char *url = NULL, *req = NULL;
    CURLcode code;
    char range[1024];

    URL->fname = fname;

    //Set the protocol
    if(strncmp(fname, "http://", 7) == 0) URL->type = BWG_HTTP;
    else if(strncmp(fname, "https://", 8) == 0) URL->type = BWG_HTTPS;
    else if(strncmp(fname, "ftp://", 6) == 0) URL->type = BWG_FTP;
    else URL->type = BWG_FILE;

    //local file?
    if(URL->type == BWG_FILE) {
        URL->filePos = -1; //This signals that nothing has been read
        URL->x.fp = fopen(fname, "rb");
        if(!(URL->x.fp)) {
            free(URL);
            fprintf(stderr, "[urlOpen] Couldn't open %s\n", fname);
            return NULL;
        }
    } else {
        //Remote file, set up the memory buffer and get CURL ready
        URL->memBuf = malloc(GLOBAL_DEFAULTBUFFERSIZE);
        if(!(URL->memBuf)) {
            free(URL);
            fprintf(stderr, "[urlOpen] Couldn't allocate enough space for the file buffer!\n");
            return NULL;
        }
        URL->bufSize = GLOBAL_DEFAULTBUFFERSIZE;
        URL->x.curl = curl_easy_init();
        if(!(URL->x.curl)) {
            fprintf(stderr, "[urlOpen] curl_easy_init() failed!\n");
            goto error;
        }
        //Follow redirects
        if(curl_easy_setopt(URL->x.curl, CURLOPT_FOLLOWLOCATION, 1L) != CURLE_OK) {
            fprintf(stderr, "[urlOpen] Failed instructing curl to follow redirects!\n");
            goto error;
        }
        //Set the URL
        if(curl_easy_setopt(URL->x.curl, CURLOPT_URL, fname) != CURLE_OK) {
            fprintf(stderr, "[urlOpen] Couldn't set CURLOPT_URL!\n");
            goto error;
        }
        //Set the range, which doesn't do anything for HTTP
        sprintf(range, "0-%"PRIu64, URL->bufSize-1);
        if(curl_easy_setopt(URL->x.curl, CURLOPT_RANGE, range) != CURLE_OK) {
            fprintf(stderr, "[urlOpen] Couldn't set CURLOPT_RANGE (%s)!\n", range);
            goto error;
        }
        //Set the callback info, which means we no longer need to directly deal with sockets and header!
        if(curl_easy_setopt(URL->x.curl, CURLOPT_WRITEFUNCTION, bwFillBuffer) != CURLE_OK) {
            fprintf(stderr, "[urlOpen] Couldn't set CURLOPT_WRITEFUNCTION!\n");
            goto error;
        }
        if(curl_easy_setopt(URL->x.curl, CURLOPT_WRITEDATA, (void*)URL) != CURLE_OK) {
            fprintf(stderr, "[urlOpen] Couldn't set CURLOPT_WRITEDATA!\n");
            goto error;
        }
        if(callBack) {
            code = callBack(URL->x.curl);
            if(code != CURLE_OK) {
                fprintf(stderr, "[urlOpen] The user-supplied call back function returned an error: %s\n", curl_easy_strerror(code));
                goto error;
            }
        }
        code = curl_easy_perform(URL->x.curl);
        if(code != CURLE_OK) {
            fprintf(stderr, "[urlOpen] curl_easy_perform received an error: %s\n", curl_easy_strerror(code));
            goto error;
        }
    }
    if(url) free(url);
    if(req) free(req);
    return URL;

error:
    if(url) free(url);
    if(req) free(req);
    free(URL->memBuf);
    curl_easy_cleanup(URL->x.curl);
    free(URL);
    return NULL;
}