virtual ~orderbot()
	{
		curl_easy_cleanup(m_curl);
		curl_global_cleanup();
	}
Example #2
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;
}
Example #3
0
int gurls( FILE* fin, uint32_t threads )
{
    struct thread_pool *pool;
    uint32_t i;
    char url[1024];
    char saftey_ext[5] = "txt\0";

    /* validate threads */
    threads = threads > 30 ? 30 :
              threads == 0 ? 5  :
              threads;

    pool = thread_pool_new( threads );
    if( !pool ) {
        return -1;
    }

    /* initialize curl */
    curl_global_init( CURL_GLOBAL_ALL );

    for( i = 0; fgets(url, 1024, fin) ; i++ )
    {
        gurl_url_t* u;
        char* aux;

        if( *url == '\n' || *url == '\0' ) {
            break;
        }

        if( !is_url(url) ) {
            i--;
            continue;
        }

        /* create url object */
        u = malloc( sizeof(gurl_url_t) );
        if( !u ) {
            break;
        }

        /* remove trailing newline */
        for( aux = url; aux-url < 1024 && *aux != '\n' && *aux != '\0'; aux++ );
        *aux = '\0';

        /* fill up url object */
        strncpy( u->url, url, 1024 );
        aux = get_extension( url );
        if( !aux )
            aux = saftey_ext;
        snprintf( u->filename, 1024, "file-%010d.%s", i, aux );

        thread_pool_push( pool, gurl_url_download, u );
    }

    /* send term signal to children */
    thread_pool_terminate( pool );

    /* cleanup */
    thread_pool_free( pool );
    curl_global_cleanup();
    return 0;
}
Example #4
0
int main(int argc, char **argv)
{
  CURL *curl;
  CURLcode res;
  FILE *hd_src;
  struct stat file_info;
  curl_off_t fsize;

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

  /* get the file size of the local file */
  if(stat(LOCAL_FILE, &file_info)) {
    printf("Couldnt open '%s': %s\n", LOCAL_FILE, strerror(errno));
    return 1;
  }
  fsize = (curl_off_t)file_info.st_size;

  printf("Local file size: %" CURL_FORMAT_CURL_OFF_T " bytes.\n", fsize);

  /* get a FILE * of the same file */
  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);

    /* we want to use our own read function */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

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

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

    /* Set the size of the file to upload (optional).  If you give a *_LARGE
       option you MUST make sure that the type of the passed-in argument is a
       curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must
       make sure that to pass in a type 'long' argument. */
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                     (curl_off_t)fsize);

    /* 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 #5
0
int Send_Mail_From_Ssl(const char* pUser, const char* pPass, const char* pFrom, const char* pTo, const char* pUrl, const char* pTitle, const char* pData)
{
#ifdef __THREE_LIBRARY_CURL__
    CURL* curl;
    CURLM* mcurl;
    int still_running = 1;
    struct timeval mp_start;
    struct WriteThis pooh;
    struct curl_slist* rcpt_list = NULL;

    //组装发送内容
    char** textList = new char* [5];

    for (int i = 0; i < 5; i++)
    {
        textList[i] = new char[1024];
        memset(textList[i], 0, 1024);
    }

    sprintf(textList[0], "Subject: %s\n", pTitle);
    sprintf(textList[1], "\n");
    sprintf(textList[2], "%s\n", pData);
    sprintf(textList[3], "\n");
    textList[4] = NULL;

    pooh.counter = 0;
    pooh.pText = textList;

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();

    if (!curl)
    {
        return 1;
    }

    mcurl = curl_multi_init();

    if (!mcurl)
    {
        return 2;
    }

    rcpt_list = curl_slist_append(rcpt_list, pTo);
    /* more addresses can be added here
    rcpt_list = curl_slist_append(rcpt_list, "<*****@*****.**>");
    */

    curl_easy_setopt(curl, CURLOPT_URL, pUrl); // 此处的要带上smtp端口
    curl_easy_setopt(curl, CURLOPT_USERNAME, pUser);
    curl_easy_setopt(curl, CURLOPT_PASSWORD, pPass);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, pFrom);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, rcpt_list);
    curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_SSLVERSION, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_multi_add_handle(mcurl, curl);

    mp_start = tvnow();

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

    while (still_running)
    {
        struct timeval timeout;
        int rc; /* select() return code */

        fd_set fdread;
        fd_set fdwrite;
        fd_set fdexcep;
        int maxfd = -1;

        long curl_timeo = -1;

        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 */
        curl_multi_fdset(mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);

        /* In a real-world program you OF COURSE check the return code of the
        function calls.  On success, the value of maxfd is guaranteed to be
        greater or equal than -1.  We call select(maxfd + 1, ...), specially in
        case of (maxfd == -1), we call select(0, ...), which is basically equal
        to sleep. */

        rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);

        if (tvdiff(tvnow(), mp_start) > MULTI_PERFORM_HANG_TIMEOUT)
        {
            fprintf(stderr, "ABORTING TEST, since it seems "
                    "that it 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;
        }
    }


    for (int i = 0; i < 5; i++)
    {
        delete[] textList[i];
    }

    delete[] textList;

    curl_slist_free_all(rcpt_list);
    curl_multi_remove_handle(mcurl, curl);
    curl_multi_cleanup(mcurl);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return 0;
#else
    return 0;
#endif
}
Example #6
0
int test(char *URL)
{
  int res = 0;
  CURL *curl;
  FILE *hd_src ;
  int hd ;
  int error;
  struct_stat file_info;
  CURLM *m = NULL;
  struct timeval ml_start;
  char ml_timedout = FALSE;
  struct ReadWriteSockets sockets = {{0, 0}, {0, 0}};
  struct timeval timeout = {-1, 0};
  int success = 0;

  if (!libtest_arg3) {
    fprintf(stderr, "Usage: lib582 [url] [filename] [username]\n");
    return -1;
  }

  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 TEST_ERR_MAJOR_BAD;
  }

  /* get the file size of the local file */
  hd = fstat(fileno(hd_src), &file_info);
  if(hd == -1) {
    /* can't open file, bail out */
    error = ERRNO;
    fprintf(stderr, "fstat() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "ERROR: cannot open file %s\n", libtest_arg2);
    fclose(hd_src);
    return -1;
  }
  fprintf(stderr, "Set to upload %d bytes\n", (int)file_info.st_size);

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

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

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

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

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

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

  test_setopt(curl, CURLOPT_USERPWD, libtest_arg3);
  test_setopt(curl, CURLOPT_SSH_PUBLIC_KEYFILE, "curl_client_key.pub");
  test_setopt(curl, CURLOPT_SSH_PRIVATE_KEYFILE, "curl_client_key");

  test_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                   (curl_off_t)file_info.st_size);

  if ((m = curl_multi_init()) == NULL) {
    fprintf(stderr, "curl_multi_init() failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }
  test_multi_setopt(m, CURLMOPT_SOCKETFUNCTION, curlSocketCallback);
  test_multi_setopt(m, CURLMOPT_SOCKETDATA, &sockets);

  test_multi_setopt(m, CURLMOPT_TIMERFUNCTION, curlTimerCallback);
  test_multi_setopt(m, CURLMOPT_TIMERDATA, &timeout);

  if ((res = (int)curl_multi_add_handle(m, curl)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  while (!checkForCompletion(m, &success))
  {
    fd_set readSet, writeSet;
    curl_socket_t maxFd = 0;
    struct timeval tv = {10, 0};

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }

    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);
    updateFdSet(&sockets.read, &readSet, &maxFd);
    updateFdSet(&sockets.write, &writeSet, &maxFd);

    if (timeout.tv_sec != -1)
    {
      int usTimeout = getMicroSecondTimeout(&timeout);
      tv.tv_sec = usTimeout / 1000000;
      tv.tv_usec = usTimeout % 1000000;
    }
    else if (maxFd <= 0)
    {
      tv.tv_sec = 0;
      tv.tv_usec = 100000;
    }

    select_test(maxFd, &readSet, &writeSet, NULL, &tv);

    /* Check the sockets for reading / writing */
    checkFdSet(m, &sockets.read, &readSet, CURL_CSELECT_IN, "read");
    checkFdSet(m, &sockets.write, &writeSet, CURL_CSELECT_OUT, "write");

    if (timeout.tv_sec != -1 && getMicroSecondTimeout(&timeout) == 0)
    {
      /* Curl's timer has elapsed. */
      notifyCurl(m, CURL_SOCKET_TIMEOUT, 0, "timeout");
    }
  }

  if (!success)
  {
    fprintf(stderr, "Error uploading file.\n");
    res = TEST_ERR_MAJOR_BAD;
  }
  else if (ml_timedout) {
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

test_cleanup:

  if(m)
    curl_multi_remove_handle(m, curl);
  curl_easy_cleanup(curl);
  if(m) {
    fprintf(stderr, "Now multi-cleanup!\n");
    curl_multi_cleanup(m);
  }

  fclose(hd_src); /* close the local file */
  if (sockets.read.sockets != 0)
    free(sockets.read.sockets);
  if (sockets.write.sockets != 0)
    free(sockets.write.sockets);

  curl_global_cleanup();
  return res;
}
Example #7
0
int main(int argc, char **argv) {
  bstring info_page;
  info_t info;
  yajl_gen yajl;
  const unsigned char *json;
  size_t json_len;

  curl_global_init(CURL_GLOBAL_NOTHING);

  for (size_t i = 0; argv[i]; i += 1) {
    if (strcmp(argv[i], "-r") == 0) {
      modem_touch(MODEM_RESTART_URL);
      return EXIT_SUCCESS;
    }
  }

  info_page = modem_fetch(MODEM_INFO_URL);

  if (!info_page) {
    fprintf(stderr, "hektor: Couldn't fetch '%s'\n", MODEM_INFO_URL);
    return EXIT_FAILURE;
  }

  info_init(&info, info_page);

  yajl = yajl_gen_alloc(NULL);
  assert(yajl);

  yajl_gen_config(yajl, yajl_gen_beautify, true);

#define yajl_gen_strst(y, s) yajl_gen_string((y), (s), sizeof(s) - 1)

  yajl_gen_map_open(yajl);
    yajl_gen_strst(yajl, "connection");
    yajl_gen_integer(yajl, info.conn);

    yajl_gen_strst(yajl, "fapped");
    yajl_gen_bool(yajl, info.fap == FAP_ACTIVE);

    yajl_gen_strst(yajl, "refill_secs");
    yajl_gen_integer(yajl, info.refill_secs);

    yajl_gen_strst(yajl, "refill_ts");
    yajl_gen_integer(yajl, info.refill_ts);

    yajl_gen_strst(yajl, "usage_allowed");
    yajl_gen_integer(yajl, info.usage_allowed);

    yajl_gen_strst(yajl, "usage_remain");
    yajl_gen_integer(yajl, info.usage_remain);
  yajl_gen_map_close(yajl);

#undef yajl_gen_strst

  yajl_gen_get_buf(yajl, &json, &json_len);
  printf("%s", json);

  bdestroy(info_page);
  yajl_gen_free(yajl);
  curl_global_cleanup();

  return EXIT_SUCCESS;
}
Example #8
0
static void destroy(void)
{
	curl_global_cleanup();
	if(xcap_db != NULL)
		xcap_dbf.close(xcap_db);
}
Example #9
0
int main(int argc, char** argv) {
  std::cout << "Blackbird Bitcoin Arbitrage" << std::endl;
  std::cout << "DISCLAIMER: USE THE SOFTWARE AT YOUR OWN RISK\n" << std::endl;

  std::locale mylocale("");

  Parameters params("blackbird.conf");

  if (!params.demoMode) {
    if (!params.useFullCash) {
      if (params.cashForTesting < 10.0) {
        std::cout << "WARNING: Minimum test cash recommended: $10.00\n" << std::endl;
      }
      if (params.cashForTesting > params.maxExposure) {
        std::cout << "ERROR: Test cash ($" << params.cashForTesting << ") is above max exposure ($" << params.maxExposure << ")\n" << std::endl;
        return -1;
      }
    }
  }

  if (params.useDatabase) {
    if (createDbConnection(params) != 0) {
      std::cout << "ERROR: cannot connect to the database \'" << params.dbName << "\'\n" << std::endl;
      return -1;
    }
  }

  getQuoteType getQuote[10];
  getAvailType getAvail[10];
  sendOrderType sendOrder[10];
  isOrderCompleteType isOrderComplete[10];
  getActivePosType getActivePos[10];
  getLimitPriceType getLimitPrice[10];
  std::string dbTableName[10];
  int index = 0;

  if (params.bitfinexApi.empty() == false || params.demoMode == true) {
    params.addExchange("Bitfinex", params.bitfinexFees, params.bitfinexCanShort, true);
    getQuote[index] = Bitfinex::getQuote;
    getAvail[index] = Bitfinex::getAvail;
    sendOrder[index] = Bitfinex::sendOrder;
    isOrderComplete[index] = Bitfinex::isOrderComplete;
    getActivePos[index] = Bitfinex::getActivePos;
    getLimitPrice[index] = Bitfinex::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "bitfinex";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.okcoinApi.empty() == false || params.demoMode == true) {
    params.addExchange("OKCoin", params.okcoinFees, params.okcoinCanShort, true);
    getQuote[index] = OkCoin::getQuote;
    getAvail[index] = OkCoin::getAvail;
    sendOrder[index] = OkCoin::sendOrder;
    isOrderComplete[index] = OkCoin::isOrderComplete;
    getActivePos[index] = OkCoin::getActivePos;
    getLimitPrice[index] = OkCoin::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "okcoin";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.bitstampClientId.empty() == false || params.demoMode == true) {
    params.addExchange("Bitstamp", params.bitstampFees, params.bitstampCanShort, true);
    getQuote[index] = Bitstamp::getQuote;
    getAvail[index] = Bitstamp::getAvail;
    sendOrder[index] = Bitstamp::sendOrder;
    isOrderComplete[index] = Bitstamp::isOrderComplete;
    getActivePos[index] = Bitstamp::getActivePos;
    getLimitPrice[index] = Bitstamp::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "bitstamp";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.geminiApi.empty() == false || params.demoMode == true) {
    params.addExchange("Gemini", params.geminiFees, params.geminiCanShort, true);
    getQuote[index] = Gemini::getQuote;
    getAvail[index] = Gemini::getAvail;
    sendOrder[index] = Gemini::sendOrder;
    isOrderComplete[index] = Gemini::isOrderComplete;
    getActivePos[index] = Gemini::getActivePos;
    getLimitPrice[index] = Gemini::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "gemini";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.krakenApi.empty() == false || params.demoMode == true) {
    params.addExchange("Kraken", params.krakenFees, params.krakenCanShort, true);
    getQuote[index] = Kraken::getQuote;
    getAvail[index] = Kraken::getAvail;
    sendOrder[index] = Kraken::sendOrder;
    isOrderComplete[index] = Kraken::isOrderComplete;
    getActivePos[index] = Kraken::getActivePos;
    getLimitPrice[index] = Kraken::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "kraken";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.itbitApi.empty() == false || params.demoMode == true) {
    params.addExchange("ItBit", params.itbitFees, params.itbitCanShort, false);
    getQuote[index] = ItBit::getQuote;
    getAvail[index] = ItBit::getAvail;
    // sendOrder[index] = ItBit::sendOrder;
    // isOrderComplete[index] = ItBit::isOrderComplete;
    getActivePos[index] = ItBit::getActivePos;
    getLimitPrice[index] = ItBit::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "itbit";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.btceApi.empty() == false || params.demoMode == true) {
    params.addExchange("BTC-e", params.btceFees, params.btceCanShort, false);
    getQuote[index] = BTCe::getQuote;
    getAvail[index] = BTCe::getAvail;
    // sendOrder[index] = BTCe::sendOrder;
    // isOrderComplete[index] = BTCe::isOrderComplete;
    getActivePos[index] = BTCe::getActivePos;
    getLimitPrice[index] = BTCe::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "btce";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.sevennintysixApi.empty() == false || params.demoMode == true) {
    params.addExchange("796.com", params.sevennintysixFees, params.sevennintysixCanShort, true);
    getQuote[index] = SevenNintySix::getQuote;
    getAvail[index] = SevenNintySix::getAvail;
    sendOrder[index] = SevenNintySix::sendOrder;
    isOrderComplete[index] = SevenNintySix::isOrderComplete;
    getActivePos[index] = SevenNintySix::getActivePos;
    getLimitPrice[index] = SevenNintySix::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "796_com";
      createTable(dbTableName[index], params);
    }
    index++;
  }


  if (index < 2) {
    std::cout << "ERROR: Blackbird needs at least two Bitcoin exchanges. Please edit the config.json file to add new exchanges\n" << std::endl;
    return -1;
  }

  std::string currDateTime = printDateTimeFileName();
  std::string csvFileName = "blackbird_result_" + currDateTime + ".csv";
  std::ofstream csvFile;
  csvFile.open(csvFileName.c_str(), std::ofstream::trunc);
  csvFile << "TRADE_ID,EXCHANGE_LONG,EXHANGE_SHORT,ENTRY_TIME,EXIT_TIME,DURATION,TOTAL_EXPOSURE,BALANCE_BEFORE,BALANCE_AFTER,RETURN\n";
  csvFile.flush();

  std::string logFileName = "blackbird_log_" + currDateTime + ".log";
  std::ofstream logFile;
  logFile.open(logFileName.c_str(), std::ofstream::trunc);
  logFile.imbue(mylocale);
  logFile.precision(2);
  logFile << std::fixed;
  params.logFile = &logFile;
  logFile << "--------------------------------------------" << std::endl;
  logFile << "|   Blackbird Bitcoin Arbitrage Log File   |" << std::endl;
  logFile << "--------------------------------------------\n" << std::endl;
  logFile << "Blackbird started on " << printDateTime() << "\n" << std::endl;


  if (params.useDatabase) {
    logFile << "Connected to database \'" << params.dbName << "\'\n" << std::endl;
  }

  if (params.demoMode) {
    logFile << "Demo mode: trades won't be generated\n" << std::endl;
  }

  std::cout << "Log file generated: " << logFileName << "\nBlackbird is running... (pid " << getpid() << ")\n" << std::endl;

  std::vector<Bitcoin*> btcVec;
  int num_exchange = params.nbExch();

  for (int i = 0; i < num_exchange; ++i) {
    btcVec.push_back(new Bitcoin(i, params.exchName[i], params.fees[i], params.canShort[i], params.isImplemented[i]));
  }
  curl_global_init(CURL_GLOBAL_ALL);
  params.curl = curl_easy_init();

  logFile << "[ Targets ]" << std::endl;
  logFile << "   Spread Entry:  " << params.spreadEntry * 100.0 << "%" << std::endl;
  logFile << "   Spread Target: " << params.spreadTarget * 100.0  << "%" << std::endl;
  if (params.spreadEntry <= 0.0) {
    logFile << "   WARNING: Spread Entry should be positive" << std::endl;
  }
  if (params.spreadTarget <= 0.0) {
    logFile << "   WARNING: Spread Target should be positive" << std::endl;
  }
  logFile << std::endl;
  // store current balances
  logFile << "[ Current balances ]" << std::endl;
  double* balanceUsd = (double*)malloc(sizeof(double) * num_exchange);
  double* balanceBtc = (double*)malloc(sizeof(double) * num_exchange);
  for (int i = 0; i < num_exchange; ++i) {
    if (params.demoMode) {
      balanceUsd[i] = 0.0;
      balanceBtc[i] = 0.0;
    } else {
      balanceUsd[i] = getAvail[i](params, "usd");
      balanceBtc[i] = getAvail[i](params, "btc");
    }
  }
  // contains balances after a completed trade
  double* newBalUsd = (double*)malloc(sizeof(double) * num_exchange);
  double* newBalBtc = (double*)malloc(sizeof(double) * num_exchange);
  memset(newBalUsd, 0.0, sizeof(double) * num_exchange);
  memset(newBalBtc, 0.0, sizeof(double) * num_exchange);

  for (int i = 0; i < num_exchange; ++i) {
    logFile << "   " << params.exchName[i] << ":\t";
    if (params.demoMode) {
      logFile << "n/a (demo mode)" << std::endl;
    } else if (!params.isImplemented[i]) {
      logFile << "n/a (API not implemented)" << std::endl;
    } else { 
      logFile << balanceUsd[i] << " USD\t" << std::setprecision(6) << balanceBtc[i]  << std::setprecision(2) << " BTC" << std::endl;
    }
    if (balanceBtc[i] > 0.0300) {
      logFile << "ERROR: All BTC accounts must be empty before starting Blackbird" << std::endl;
      return -1;
    }
  }
  logFile << std::endl;
  logFile << "[ Cash exposure ]" << std::endl;
  if (params.demoMode) {
    logFile << "   No cash - Demo mode" << std::endl;
  } else {
    if (params.useFullCash) {
      logFile << "   FULL cash used!" << std::endl;
    } else {
      logFile << "   TEST cash used\n   Value: $" << params.cashForTesting << std::endl;
    }
  }
  logFile << std::endl;

  time_t rawtime;
  rawtime = time(NULL);
  struct tm* timeinfo;
  timeinfo = localtime(&rawtime);
  // wait the next gapSec seconds before starting
  time(&rawtime);
  timeinfo = localtime(&rawtime);
  while ((int)timeinfo->tm_sec % params.gapSec != 0) {
    sleep(0.01);
    time(&rawtime);
    timeinfo = localtime(&rawtime);
  }
  // main loop
  if (!params.verbose) {
    logFile << "Running..." << std::endl;
  }
  bool inMarket = false;
  int resultId = 0;
  Result res;
  res.clear();
  unsigned currIteration = 0;
  bool stillRunning = true;
  time_t currTime;
  time_t diffTime;
  while (stillRunning) {

    currTime = mktime(timeinfo);
    time(&rawtime);
    diffTime = difftime(rawtime, currTime);
    // check if we are already too late
    if (diffTime > 0) {
      logFile << "WARNING: " << diffTime << " second(s) too late at " << printDateTime(currTime) << std::endl;
      timeinfo->tm_sec = timeinfo->tm_sec + (ceil(diffTime / params.gapSec) + 1) * params.gapSec;
      currTime = mktime(timeinfo);
      sleep(params.gapSec - (diffTime % params.gapSec));
      logFile << std::endl;
    }
    else if (diffTime < 0) {
      sleep(-difftime(rawtime, currTime));  // sleep until the next iteration
    }
    if (params.verbose) {
      if (!inMarket) {
        logFile << "[ " << printDateTime(currTime) << " ]" << std::endl;
      } else {
        logFile << "[ " << printDateTime(currTime) << " IN MARKET: Long " << res.exchNameLong << " / Short " << res.exchNameShort << " ]" << std::endl;
      }
    }
    for (int e = 0; e < num_exchange; ++e) {
      double bid = getQuote[e](params, true);
      double ask = getQuote[e](params, false);
      if (params.useDatabase) {
        addBidAskToDb(dbTableName[e], printDateTimeDb(currTime), bid, ask, params);
      }
      if (bid == 0.0) {
        logFile << "   WARNING: " << params.exchName[e] << " bid is null, use previous one" << std::endl;
      }
      if (ask == 0.0) {
        logFile << "   WARNING: " << params.exchName[e] << " ask is null, use previous one" << std::endl;
      }
      if (params.verbose) {
        logFile << "   " << params.exchName[e] << ": \t" << bid << " / " << ask << std::endl;
      }
      btcVec[e]->updateData(bid, ask, 0.0);
      curl_easy_reset(params.curl);
    }
    if (params.verbose) {
      logFile << "   ----------------------------" << std::endl;
    }

    // compute entry point
    if (!inMarket) {
      for (int i = 0; i < num_exchange; ++i) {
        for (int j = 0; j < num_exchange; ++j) {
          if (i != j) {
            if (checkEntry(btcVec[i], btcVec[j], res, params)) {
              // entry opportunity found
              res.exposure = std::min(balanceUsd[res.idExchLong], balanceUsd[res.idExchShort]);
              if (params.demoMode) {
                logFile << "INFO: Opportunity found but no trade will be generated (Demo mode)" << std::endl;
                break;
              }
              if (res.exposure == 0.0) {
                logFile << "WARNING: Opportunity found but no cash available. Trade canceled" << std::endl;
                break;
              }
              if (params.useFullCash == false && res.exposure <= params.cashForTesting) {
                logFile << "WARNING: Opportunity found but no enough cash. Need more than TEST cash (min. $" << params.cashForTesting << "). Trade canceled" << std::endl;
                break;
              }
              if (params.useFullCash) {
                res.exposure -= params.untouchedCash * res.exposure;  // leave untouchedCash
                if (res.exposure > params.maxExposure) {
                  logFile << "WARNING: Opportunity found but exposure ($" << res.exposure << ") above the limit" << std::endl;
                  logFile << "         Max exposure will be used instead ($" << params.maxExposure << ")" << std::endl;
                  res.exposure = params.maxExposure;
                }
              } else {
                res.exposure = params.cashForTesting;  // use test money
              }
              double volumeLong = res.exposure / btcVec[res.idExchLong]->getAsk();
              double volumeShort = res.exposure / btcVec[res.idExchShort]->getBid();
              double limPriceLong = getLimitPrice[res.idExchLong](params, volumeLong, false);
              double limPriceShort = getLimitPrice[res.idExchShort](params, volumeShort, true);
              if (limPriceLong - res.priceLongIn > params.priceDeltaLim || res.priceShortIn - limPriceShort > params.priceDeltaLim) {
                logFile << "WARNING: Opportunity found but not enough liquidity. Trade canceled" << std::endl;
                logFile << "         Target long price:  " << res.priceLongIn << ", Real long price:  " << limPriceLong << std::endl;
                logFile << "         Target short price: " << res.priceShortIn << ", Real short price: " << limPriceShort << std::endl;
                res.trailing[res.idExchLong][res.idExchShort] = -1.0;
                break;
              }
              inMarket = true;
              resultId++;
              // update result
              res.id = resultId;
              res.entryTime = currTime;
              res.priceLongIn = limPriceLong;
              res.priceShortIn = limPriceShort;
              res.printEntry(*params.logFile);
              res.maxSpread[res.idExchLong][res.idExchShort] = -1.0;
              res.minSpread[res.idExchLong][res.idExchShort] = 1.0;
              res.trailing[res.idExchLong][res.idExchShort] = 1.0;
              int longOrderId = 0;
              int shortOrderId = 0;
              // send orders
              longOrderId = sendOrder[res.idExchLong](params, "buy", volumeLong, btcVec[res.idExchLong]->getAsk());
              shortOrderId = sendOrder[res.idExchShort](params, "sell", volumeShort, btcVec[res.idExchShort]->getBid());
              // wait for the orders to be filled
              logFile << "Waiting for the two orders to be filled..." << std::endl;
              sleep(3.0);
              while (!isOrderComplete[res.idExchLong](params, longOrderId) || !isOrderComplete[res.idExchShort](params, shortOrderId)) {
                sleep(3.0);
              }
              logFile << "Done" << std::endl;
              longOrderId = 0;
              shortOrderId = 0;
              break;
            }
          }
        }
        if (inMarket) {
          break;
        }
      }
      if (params.verbose) {
        logFile << std::endl;
      }
    }
    // in market, looking to exit
    else if (inMarket) {
      if (checkExit(btcVec[res.idExchLong], btcVec[res.idExchShort], res, params, currTime)) {
        // exit opportunity found
        // check current exposure
        double* btcUsed = (double*)malloc(sizeof(double) * num_exchange);
        for (int i = 0; i < num_exchange; ++i) {
          btcUsed[i] = getActivePos[i](params);
        }
        double volumeLong = btcUsed[res.idExchLong];
        double volumeShort = btcUsed[res.idExchShort];
        double limPriceLong = getLimitPrice[res.idExchLong](params, volumeLong, true);
        double limPriceShort = getLimitPrice[res.idExchShort](params, volumeShort, false);

        if (res.priceLongOut - limPriceLong > params.priceDeltaLim || limPriceShort - res.priceShortOut > params.priceDeltaLim) {
          logFile << "WARNING: Opportunity found but not enough liquidity. Trade canceled" << std::endl;
          logFile << "         Target long price:  " << res.priceLongOut << ", Real long price:  " << limPriceLong << std::endl;
          logFile << "         Target short price: " << res.priceShortOut << ", Real short price: " << limPriceShort << std::endl;
          res.trailing[res.idExchLong][res.idExchShort] = 1.0;
        } else {
          res.exitTime = currTime;
          res.priceLongOut = limPriceLong;
          res.priceShortOut = limPriceShort;
          res.printExit(*params.logFile);
          int longOrderId = 0;
          int shortOrderId = 0;
          logFile << std::setprecision(6) << "BTC exposure on " << params.exchName[res.idExchLong] << ": " << volumeLong << std::setprecision(2) << std::endl;
          logFile << std::setprecision(6) << "BTC exposure on " << params.exchName[res.idExchShort] << ": " << volumeShort << std::setprecision(2) << std::endl;
          logFile << std::endl;
          // send orders
          longOrderId = sendOrder[res.idExchLong](params, "sell", fabs(btcUsed[res.idExchLong]), btcVec[res.idExchLong]->getBid());
          shortOrderId = sendOrder[res.idExchShort](params, "buy", fabs(btcUsed[res.idExchShort]), btcVec[res.idExchShort]->getAsk());
          // wait for the orders to be filled
          logFile << "Waiting for the two orders to be filled..." << std::endl;
          sleep(3.0);
          while (!isOrderComplete[res.idExchLong](params, longOrderId) || !isOrderComplete[res.idExchShort](params, shortOrderId)) {
            sleep(3.0);
          }
          logFile << "Done\n" << std::endl;
          longOrderId = 0;
          shortOrderId = 0;
          inMarket = false;
          // new balances
          for (int i = 0; i < num_exchange; ++i) {
            newBalUsd[i] = getAvail[i](params, "usd");
            newBalBtc[i] = getAvail[i](params, "btc");
          }
          for (int i = 0; i < num_exchange; ++i) {
            logFile << "New balance on " << params.exchName[i] << ":  \t";
            logFile << newBalUsd[i] << " USD (perf $" << newBalUsd[i] - balanceUsd[i] << "), ";
            logFile << std::setprecision(6) << newBalBtc[i]  << std::setprecision(2) << " BTC" << std::endl;
          }
          logFile << std::endl;
          // update res with total balance
          for (int i = 0; i < num_exchange; ++i) {
            res.befBalUsd += balanceUsd[i];
            res.aftBalUsd += newBalUsd[i];
          }
          // update current balances with new values
          for (int i = 0; i < num_exchange; ++i) {
            balanceUsd[i] = newBalUsd[i];
            balanceBtc[i] = newBalBtc[i];
          }
          logFile << "ACTUAL PERFORMANCE: " << "$" << res.aftBalUsd - res.befBalUsd << " (" << res.totPerf() * 100.0 << "%)\n" << std::endl;
          csvFile << res.id << "," << res.exchNameLong << "," << res.exchNameShort << "," << printDateTimeCsv(res.entryTime) << "," << printDateTimeCsv(res.exitTime);
          csvFile << "," << res.getLength() << "," << res.exposure * 2.0 << "," << res.befBalUsd << "," << res.aftBalUsd << "," << res.totPerf() << "\n";
          csvFile.flush();
          if (params.sendEmail) {
            sendEmail(res, params);
            logFile << "Email sent" << std::endl;
          }
          res.clear();
          std::ifstream infile("stop_after_exit");
          if (infile.good()) {
            logFile << "Exit after last trade (file stop_after_exit found)" << std::endl;
            stillRunning = false;
          }
        }
      }
      if (params.verbose) {
        logFile << std::endl;
      }
    }
    timeinfo->tm_sec = timeinfo->tm_sec + params.gapSec;
    currIteration++;
    if (currIteration >= params.debugMaxIteration) {
      logFile << "Max iteration reached (" << params.debugMaxIteration << ")" <<std::endl;
      stillRunning = false;
    }
  }
  for (int i = 0; i < num_exchange; ++i) {
    delete(btcVec[i]);
  }
  curl_easy_cleanup(params.curl);
  curl_global_cleanup();
  if (params.useDatabase) {
    mysql_close(params.dbConn);
  }
  csvFile.close();
  logFile.close();

  return 0;
}
Example #10
0
/*
 * Source code in here hugely as reported in bug report 651464 by
 * Christopher R. Palmer.
 *
 * Use multi interface to get document over proxy with bad port number.
 * This caused the interface to "hang" in libcurl 7.10.2.
 */
int test(char *URL)
{
  CURL *c;
  int ret=0;
  CURLM *m;
  fd_set rd, wr, exc;
  CURLMcode res;
  char done = FALSE;
  int running;
  int max_fd;
  int rc;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;

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

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

  /* the point here being that there must not run anything on the given
     proxy port */
  curl_easy_setopt(c, CURLOPT_PROXY, arg2);
  curl_easy_setopt(c, CURLOPT_URL, URL);
  curl_easy_setopt(c, CURLOPT_VERBOSE, 1);

  if ((m = curl_multi_init()) == NULL) {
    fprintf(stderr, "curl_multi_init() failed\n");
    curl_easy_cleanup(c);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  if ((res = curl_multi_add_handle(m, c)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(c);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  while (!done) {
    struct timeval interval;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }
    mp_timedout = FALSE;
    mp_start = tutil_tvnow();

    fprintf(stderr, "curl_multi_perform()\n");

    res = CURLM_CALL_MULTI_PERFORM;

    while (res == CURLM_CALL_MULTI_PERFORM) {
      res = curl_multi_perform(m, &running);
      if (tutil_tvdiff(tutil_tvnow(), mp_start) >
          MULTI_PERFORM_HANG_TIMEOUT) {
        mp_timedout = TRUE;
        break;
      }
    }
    if (mp_timedout)
      break;

    if(!running) {
      /* This is where this code is expected to reach */
      int numleft;
      CURLMsg *msg = curl_multi_info_read(m, &numleft);
      fprintf(stderr, "Expected: not running\n");
      if(msg && !numleft)
        ret = 100; /* this is where we should be */
      else
        ret = 99; /* not correct */
      break;
    }
    fprintf(stderr, "running == %d, res == %d\n", running, res);

    if (res != CURLM_OK) {
      ret = 2;
      break;
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);
    max_fd = 0;

    fprintf(stderr, "curl_multi_fdset()\n");
    if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
      fprintf(stderr, "unexpected failured of fdset.\n");
      ret = 3;
      break;
    }
    rc = select_test(max_fd+1, &rd, &wr, &exc, &interval);
    fprintf(stderr, "select returned %d\n", rc);
  }

  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    ret = TEST_ERR_RUNS_FOREVER;
  }

  curl_multi_remove_handle(m, c);
  curl_easy_cleanup(c);
  curl_multi_cleanup(m);
  curl_global_cleanup();

  return ret;
}
Example #11
0
//------------------------------------------------------------------------------
// helper function to terminate Kraken API library's resources:
void terminate() 
{
   curl_global_cleanup();
}
  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) ;

      /* set user name and password */
      curl_easy_setopt(curl, CURLOPT_USERPWD, "rutul:topspin");

      /* 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_INFILE, hd_src);
  
      /* and give the size of the upload (optional) */
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_info.st_size);
  
      /* Switch on full protocol/debug output */
      curl_easy_setopt(curl, CURLOPT_VERBOSE, TRUE);

      /* 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 #13
0
int test(char *URL)
{
  int res = 0;
  CURL *curl;
  int running;
  char done=FALSE;
  CURLM *m = NULL;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;

  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;
  }

  test_setopt(curl, CURLOPT_URL, URL);
  test_setopt(curl, CURLOPT_VERBOSE, 1);
  test_setopt(curl, CURLOPT_PROXY, libtest_arg2);
  test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);

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

  if ((res = (int)curl_multi_add_handle(m, curl)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  fprintf(stderr, "Start at URL 0\n");

  while (!done) {
    fd_set rd, wr, exc;
    int max_fd;
    struct timeval interval;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }
    mp_timedout = FALSE;
    mp_start = tutil_tvnow();

    while (res == CURLM_CALL_MULTI_PERFORM) {
      res = (int)curl_multi_perform(m, &running);
      if (tutil_tvdiff(tutil_tvnow(), mp_start) >
          MULTI_PERFORM_HANG_TIMEOUT) {
        mp_timedout = TRUE;
        break;
      }
      if (running <= 0) {
        done = TRUE; /* bail out */
        break;
      }
    }
    if (mp_timedout || done)
      break;

    if (res != CURLM_OK) {
      fprintf(stderr, "not okay???\n");
      break;
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);
    max_fd = 0;

    if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
      fprintf(stderr, "unexpected failured of fdset.\n");
      res = 189;
      break;
    }

    if (select_test(max_fd+1, &rd, &wr, &exc, &interval) == -1) {
      fprintf(stderr, "bad select??\n");
      res = 195;
      break;
    }

    res = CURLM_CALL_MULTI_PERFORM;
  }

  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

test_cleanup:

  curl_easy_cleanup(curl);
  if(m)
    curl_multi_cleanup(m);
  curl_global_cleanup();

  return res;
}
Example #14
0
JNIEXPORT void JNICALL Java_com_netbirdtech_libcurl_Curl_curlGlobalCleanupNative
  (JNIEnv * env, jclass cls) {
    curl_global_cleanup();
}
Example #15
0
int test(char *URL)
{
  CURL* curls;
  CURLM* multi;
  int still_running;
  int i = -1;
  int res = 0;
  CURLMsg *msg;
  CURLMcode ret;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;

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

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

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

  test_setopt(curls, CURLOPT_URL, URL);

  if ((ret = curl_multi_add_handle(multi, curls)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", ret);
    curl_easy_cleanup(curls);
    curl_multi_cleanup(multi);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  mp_timedout = FALSE;
  mp_start = tutil_tvnow();

  do {
    ret = curl_multi_perform(multi, &still_running);
    if (tutil_tvdiff(tutil_tvnow(), mp_start) > 
        MULTI_PERFORM_HANG_TIMEOUT) {
      mp_timedout = TRUE;
      break;
    }
  } while (ret == CURLM_CALL_MULTI_PERFORM);

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  while ((!ml_timedout) && (!mp_timedout) && (still_running)) {
    struct timeval timeout;
    int rc;
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;
    int maxfd;

    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) > 
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }

    curl_multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd);
    rc = select_test(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
    switch(rc) {
      case -1:
        break;
      case 0:
      default:
        mp_timedout = FALSE;
        mp_start = tutil_tvnow();
        do {
          ret = curl_multi_perform(multi, &still_running);
          if (tutil_tvdiff(tutil_tvnow(), mp_start) > 
              MULTI_PERFORM_HANG_TIMEOUT) {
            mp_timedout = TRUE;
            break;
          }
        } while (ret == CURLM_CALL_MULTI_PERFORM);
        break;
    }
  }
  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    i = TEST_ERR_RUNS_FOREVER;
  }
  else {
    msg = curl_multi_info_read(multi, &still_running);
    if(msg)
      /* this should now contain a result code from the easy handle,
         get it */
      i = msg->data.result;
  }

test_cleanup:

  curl_multi_cleanup(multi);
  curl_easy_cleanup(curls);
  curl_global_cleanup();

  if(res)
    i = res;

  return i; /* return the final return code */
}
Example #16
0
int test(char *URL)
{
  int res;
  CURL *curl;
  int request=1;
  char *stream_uri = NULL;

  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;
  }

  test_setopt(curl, CURLOPT_HEADERDATA, stdout);
  test_setopt(curl, CURLOPT_WRITEDATA, stdout);
  test_setopt(curl, CURLOPT_VERBOSE, 1L);

  test_setopt(curl, CURLOPT_URL, URL);

  test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS);

  if((stream_uri = suburl(URL, request++)) == NULL) {
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }
  test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri);
  free(stream_uri);
  stream_uri = NULL;

  res = curl_easy_perform(curl);
  if(res != (int)CURLE_RTSP_CSEQ_ERROR) {
    fprintf(stderr, "Failed to detect CSeq mismatch");
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  test_setopt(curl, CURLOPT_RTSP_CLIENT_CSEQ, 999);
  test_setopt(curl, CURLOPT_RTSP_TRANSPORT,
                    "RAW/RAW/UDP;unicast;client_port=3056-3057");
  test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP);

  if((stream_uri = suburl(URL, request++)) == NULL) {
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }
  test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri);
  free(stream_uri);
  stream_uri = NULL;

  res = curl_easy_perform(curl);
  if(res)
    goto test_cleanup;

  test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY);

  if((stream_uri = suburl(URL, request++)) == NULL) {
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }
  test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri);
  free(stream_uri);
  stream_uri = NULL;

  res = curl_easy_perform(curl);
  if(res != CURLE_RTSP_SESSION_ERROR) {
    fprintf(stderr, "Failed to detect a Session ID mismatch");
  }

test_cleanup:

  if(stream_uri)
    free(stream_uri);

  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return res;
}
Example #17
0
int main(int argc, char* argv[])
{
	for(int i=1; i<argc; ++i)
	{
		if(strcmp(argv[i], "-help") == 0)
		{
			print_usage();
			return -1;
		}
		else if(strcmp(argv[i], "-nocontent") == 0)
		{
			bNoOutContent = true;
		}
		else if(strcmp(argv[i], "-status") == 0)
		{
			bOutHttpStatus = true;
		}
		else if(strcmp(argv[i], "-head") == 0)
		{
			bOutHeader = true;
		}
		else if(strcmp(argv[i], "-useragent") == 0)
		{
			++i;
			if(i < argc)
				szUserAgent = argv[i];
			else
			{
				print_usage();
				return -1;
			}
		}
		else
		{
			szUrl = argv[i];
		}
	}

	CURLcode retCode = CURLE_OK;
	RET_CURL(curl_global_init, CURL_GLOBAL_ALL);
	pstCURLHandle = curl_easy_init();
	if(pstCURLHandle == NULL)
	{
		printf("error[%s:%d]: create CURL handle fail.\n", __FILE__, __LINE__);
		return -1;
	}

	RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_HEADER, 0);
	RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_WRITEFUNCTION, HttpWriteCallback);
	RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_HEADERFUNCTION, HttpHeaderCallback);

	if(szUserAgent != NULL)
		RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_USERAGENT, szUserAgent);

	if(szUrl == NULL)
	{
		char buffer[4097];
		int size = 0;
		int len = 4096;
		int offset = 0;
		memset(buffer, 0, 4097);
		while(-1 != (size = read(STDIN_FILENO, buffer + offset, len)))
		{
			if(size == 0)
				break;

			char* pStart = buffer;
			char* pEnd = NULL;
			while((pEnd = strchr(pStart, '\n')) != NULL)
			{
				pEnd[0] = 0x0;

				RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_URL, pStart);
				RET_CURL(curl_easy_perform, pstCURLHandle);

				pStart = pEnd + 1;
			}

			strcpy(buffer, pStart);
			offset = strlen(pStart);
			len = 4096 - offset;
			memset(buffer + offset, 0, len);
		}
	}
	else
	{
		RET_CURL(curl_easy_setopt, pstCURLHandle, CURLOPT_URL, szUrl);
		RET_CURL(curl_easy_perform, pstCURLHandle);
		if(bOutHttpStatus)
		{
			boost::regex rgxHttpStatus("^HTTP/([^ ]+) ([0-9]+)");
			boost::smatch what;
			if(boost::regex_search(strHeader, what, rgxHttpStatus))
				printf("%d\n", atoi(what[2].str().c_str()));
			else
				printf("500\n");
		}
		if(bOutHeader)
			printf("%s", strHeader.c_str());
		if(!bNoOutContent)
			printf("%s", strContent.c_str());
	}

	curl_easy_cleanup(pstCURLHandle);
	curl_global_cleanup();
	return 0;
}
Example #18
0
int test(char *URL)
{
  int res = 0;
  CURLM *m = NULL;
  CURLMsg *msg; /* for picking up messages with the transfer status */
  int msgs_left; /* how many messages are left */
  int running;
  int handlenum = 0;
  struct timeval last_handle_add;

  if(parse_url_file("log/urls.txt") <= 0)
    goto test_cleanup;

  start_test_timing();

  curl_global_init(CURL_GLOBAL_ALL);

  m = curl_multi_init();

  create_handles();

  multi_setopt(m, CURLMOPT_PIPELINING, 1L);
  multi_setopt(m, CURLMOPT_MAX_HOST_CONNECTIONS, 2L);
  multi_setopt(m, CURLMOPT_MAX_PIPELINE_LENGTH, 3L);
  multi_setopt(m, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, 15000L);
  multi_setopt(m, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, 10000L);

  multi_setopt(m, CURLMOPT_PIPELINING_SITE_BL, site_blacklist);
  multi_setopt(m, CURLMOPT_PIPELINING_SERVER_BL, server_blacklist);

  last_handle_add = tutil_tvnow();

  for(;;) {
    struct timeval interval;
    struct timeval now;
    long int msnow, mslast;
    fd_set rd, wr, exc;
    int maxfd = -99;
    long timeout;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if(handlenum < num_handles) {
      now = tutil_tvnow();
      msnow = now.tv_sec * 1000 + now.tv_usec / 1000;
      mslast = last_handle_add.tv_sec * 1000 + last_handle_add.tv_usec / 1000;
      if(msnow - mslast >= urltime[handlenum] && handlenum < num_handles) {
        fprintf(stdout, "Adding handle %d\n", handlenum);
        setup_handle(URL, m, handlenum);
        last_handle_add = now;
        handlenum++;
      }
    }

    curl_multi_perform(m, &running);

    abort_on_test_timeout();

    /* See how the transfers went */
    while ((msg = curl_multi_info_read(m, &msgs_left))) {
      if (msg->msg == CURLMSG_DONE) {
        int i, found = 0;

        /* Find out which handle this message is about */
        for (i = 0; i < num_handles; i++) {
          found = (msg->easy_handle == handles[i]);
          if(found)
            break;
        }

        printf("Handle %d Completed with status %d\n", i, msg->data.result);
        curl_multi_remove_handle(m, handles[i]);
      }
    }

    if(handlenum == num_handles && !running) {
      break; /* done */
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);

    curl_multi_fdset(m, &rd, &wr, &exc, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    curl_multi_timeout(m, &timeout);

    if(timeout < 0)
      timeout = 1;

    interval.tv_sec = timeout / 1000;
    interval.tv_usec = (timeout % 1000) * 1000;

    interval.tv_sec = 0;
    interval.tv_usec = 1000;

    select_test(maxfd+1, &rd, &wr, &exc, &interval);

    abort_on_test_timeout();
  }

test_cleanup:

  remove_handles();

  /* undocumented cleanup sequence - type UB */

  curl_multi_cleanup(m);
  curl_global_cleanup();

  free_urls();
  return res;
}
Example #19
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
    PF_CONSOLE_INIT_ALL()

    // Set global handle
    gHInst = hInst;

    std::vector<plString> args;
    args.reserve(__argc);
    for (size_t i = 0; i < __argc; i++) {
        args.push_back(plString::FromUtf8(__argv[i]));
    }

    plCmdParser cmdParser(s_cmdLineArgs, arrsize(s_cmdLineArgs));
    cmdParser.Parse(args);

    bool doIntroDialogs = true;
#ifndef PLASMA_EXTERNAL_RELEASE
    if (cmdParser.IsSpecified(kArgSkipLoginDialog))
        doIntroDialogs = false;
    if (cmdParser.IsSpecified(kArgLocalData))
    {
        gDataServerLocal = true;
        gSkipPreload = true;
    }
    if (cmdParser.IsSpecified(kArgSkipPreload))
        gSkipPreload = true;
    if (cmdParser.IsSpecified(kArgPlayerId))
        NetCommSetIniPlayerId(cmdParser.GetInt(kArgPlayerId));
    if (cmdParser.IsSpecified(kArgStartUpAgeName))
        NetCommSetIniStartUpAge(cmdParser.GetString(kArgStartUpAgeName));
#endif

    plFileName serverIni = "server.ini";
    if (cmdParser.IsSpecified(kArgServerIni))
        serverIni = cmdParser.GetString(kArgServerIni);

    // check to see if we were launched from the patcher
    bool eventExists = false;
    // we check to see if the event exists that the patcher should have created
    HANDLE hPatcherEvent = CreateEventW(nil, TRUE, FALSE, L"UruPatcherEvent");
    if (hPatcherEvent != NULL)
    {
        // successfully created it, check to see if it was already created
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            // it already existed, so the patcher is waiting, signal it so the patcher can die
            SetEvent(hPatcherEvent);
            eventExists = true;
        }
    }

#ifdef PLASMA_EXTERNAL_RELEASE
    // if the client was started directly, run the patcher, and shutdown
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    si.cb = sizeof(si);

    if (!eventExists) // if it is missing, assume patcher wasn't launched
    {
        if(!CreateProcessW(s_patcherExeName, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
        {
            hsMessageBox("Failed to launch patcher", "Error", hsMessageBoxNormal);
        }
        CloseHandle( pi.hThread );
        CloseHandle( pi.hProcess );
        return PARABLE_NORMAL_EXIT;
    }
#endif

    // Load an optional general.ini
    plFileName gipath = plFileName::Join(plFileSystem::GetInitPath(), "general.ini");
    FILE *generalini = plFileSystem::Open(gipath, "rb");
    if (generalini)
    {
        fclose(generalini);
        pfConsoleEngine tempConsole;
        tempConsole.ExecuteFile(gipath);
    }

#ifdef PLASMA_EXTERNAL_RELEASE
    // If another instance is running, exit.  We'll automatically release our
    // lock on the mutex when our process exits
    HANDLE hOneInstance = CreateMutex(nil, FALSE, "UruExplorer");
    if (WaitForSingleObject(hOneInstance,0) != WAIT_OBJECT_0)
    {
        switch (plLocalization::GetLanguage())
        {
        case plLocalization::kFrench:
            hsMessageBox("Une autre copie d'URU est déjà en cours d'exécution", "Erreur", hsMessageBoxNormal);
            break;
        case plLocalization::kGerman:
            hsMessageBox("URU wird bereits in einer anderen Instanz ausgeführt", "Fehler", hsMessageBoxNormal);
            break;
        case plLocalization::kSpanish:
            hsMessageBox("En estos momentos se está ejecutando otra copia de URU", "Error", hsMessageBoxNormal);
            break;
        case plLocalization::kItalian:
            hsMessageBox("Un'altra copia di URU è già aperta", "Errore", hsMessageBoxNormal);
            break;
        // default is English
        default:
            hsMessageBox("Another copy of URU is already running", "Error", hsMessageBoxNormal);
            break;
        }
        return PARABLE_NORMAL_EXIT;
    }
#endif

    FILE *serverIniFile = plFileSystem::Open(serverIni, "rb");
    if (serverIniFile)
    {
        fclose(serverIniFile);
        pfConsoleEngine tempConsole;
        tempConsole.ExecuteFile(serverIni);
    }
    else
    {
        hsMessageBox("No server.ini file found.  Please check your URU installation.", "Error", hsMessageBoxNormal);
        return PARABLE_NORMAL_EXIT;
    }

    NetCliAuthAutoReconnectEnable(false);
    InitNetClientComm();

    curl_global_init(CURL_GLOBAL_ALL);

    bool                needExit = false;
    LoginDialogParam    loginParam;
    memset(&loginParam, 0, sizeof(loginParam));
    LoadUserPass(&loginParam);

    if (!doIntroDialogs && loginParam.remember) {
        ENetError auth;

        NetCommSetAccountUsernamePassword(loginParam.username, loginParam.namePassHash);
        bool cancelled = AuthenticateNetClientComm(&auth, NULL);

        if (IS_NET_ERROR(auth) || cancelled) {
            doIntroDialogs = true;

            loginParam.authError = auth;

            if (cancelled)
            {
                NetCommDisconnect();
            }
        }
    }

    if (doIntroDialogs) {
        needExit = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_MAIN ), NULL, UruLoginDialogProc, (LPARAM)&loginParam ) <= 0;
    }

    if (doIntroDialogs && !needExit) {
        HINSTANCE hRichEdDll = LoadLibrary("RICHED20.DLL");
        INT_PTR val = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_EULA ), NULL, UruTOSDialogProc, (LPARAM)hInst);
        FreeLibrary(hRichEdDll);
        if (val <= 0) {
            DWORD error = GetLastError();
            needExit = true;
        }
    }

    curl_global_cleanup();

    if (needExit) {
        DeInitNetClientComm();
        return PARABLE_NORMAL_EXIT;
    }

    NetCliAuthAutoReconnectEnable(true);

    // VERY VERY FIRST--throw up our splash screen
    HWND splashDialog = ::CreateDialog( hInst, MAKEINTRESOURCE( IDD_LOADING ), NULL, SplashDialogProc );

    // Install our unhandled exception filter for trapping all those nasty crashes in release build
#ifndef HS_DEBUGGING
    LPTOP_LEVEL_EXCEPTION_FILTER oldFilter;
    oldFilter = SetUnhandledExceptionFilter( plCustomUnhandledExceptionFilter );
#endif

    //
    // Set up to log errors by using hsDebugMessage
    //
    DebugInit();
    DebugMsgF("Plasma 2.0.%i.%i - %s", PLASMA2_MAJOR_VERSION, PLASMA2_MINOR_VERSION, plProduct::ProductString().c_str());

    for (;;) {
        // Create Window
        if (!WinInit(hInst, nCmdShow) || gClient->GetDone())
            break;

        // Done with our splash now
        ::DestroyWindow( splashDialog );

        if (!gClient)
            break;

        // Show the main window
        ShowWindow(gClient->GetWindowHandle(), SW_SHOW);

        // Be really REALLY forceful about being in the front
        BringWindowToTop( gClient->GetWindowHandle() );

        // Update the window
        UpdateWindow(gClient->GetWindowHandle());

        //
        // Init Application here
        //
        if( !gClient->StartInit() )
            break;

        // I want it on top! I mean it!
        BringWindowToTop( gClient->GetWindowHandle() );

        // initialize dinput here:
        if (gClient && gClient->GetInputManager())
            gClient->GetInputManager()->InitDInput(hInst, (HWND)gClient->GetWindowHandle());

        // Seriously!
        BringWindowToTop( gClient->GetWindowHandle() );

        //
        // Main loop
        //
        MSG msg;
        do
        {
            gClient->MainLoop();

            if( gClient->GetDone() )
                break;

            // Look for a message
            while (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
            {
                // Handle the message
                TranslateMessage( &msg );
                DispatchMessage( &msg );
            }
        } while (WM_QUIT != msg.message);

        break;
    }

    //
    // Cleanup
    //
    if (gClient)
    {
        gClient->Shutdown(); // shuts down PhysX for us
        gClient = nil;
    }
    hsAssert(hsgResMgr::ResMgr()->RefCnt()==1, "resMgr has too many refs, expect mem leaks");
    hsgResMgr::Shutdown();  // deletes fResMgr
    DeInitNetClientComm();

    // Uninstall our unhandled exception filter, if we installed one
#ifndef HS_DEBUGGING
    SetUnhandledExceptionFilter( oldFilter );
#endif

    // Exit WinMain and terminate the app....
    return PARABLE_NORMAL_EXIT;
}
Example #20
0
CurlDownloadManager::~CurlDownloadManager()
{
    stopThread();
    curl_multi_cleanup(m_curlMultiHandle);
    curl_global_cleanup();
}
Example #21
0
/* test function */
int test(char *URL)
{
    int res;
    CURLSHcode scode;
    char *url;
    struct Tdata tdata;
    CURL *curl;
    CURLSH *share;
    struct curl_slist *headers;
    int i;
    struct userdata user;

    user.text = (char *)"Pigs in space";
    user.counter = 0;

    printf( "GLOBAL_INIT\n" );
    curl_global_init( CURL_GLOBAL_ALL );

    /* prepare share */
    printf( "SHARE_INIT\n" );
    share = curl_share_init();
    curl_share_setopt( share, CURLSHOPT_LOCKFUNC,   lock);
    curl_share_setopt( share, CURLSHOPT_UNLOCKFUNC, unlock);
    curl_share_setopt( share, CURLSHOPT_USERDATA,   &user);
    printf( "CURL_LOCK_DATA_COOKIE\n" );
    curl_share_setopt( share, CURLSHOPT_SHARE,      CURL_LOCK_DATA_COOKIE);
    printf( "CURL_LOCK_DATA_DNS\n" );
    curl_share_setopt( share, CURLSHOPT_SHARE,      CURL_LOCK_DATA_DNS);

    res = 0;

    /* start treads */
    for (i=1; i<=THREADS; i++ )
    {

        /* set thread data */
        tdata.url   = suburl( URL, i ); /* must be freed */
        tdata.share = share;

        /* simulate thread, direct call of "thread" function */
        printf( "*** run %d\n",i );
        fire( &tdata );

        free( tdata.url );

    }


    /* fetch a another one and save cookies */
    printf( "*** run %d\n", i );
    curl = curl_easy_init();

    url = suburl( URL, i );
    headers = sethost( NULL );
    curl_easy_setopt( curl, CURLOPT_HTTPHEADER, (void*)headers );
    curl_easy_setopt( curl, CURLOPT_URL,        url );
    printf( "CURLOPT_SHARE\n" );
    curl_easy_setopt( curl, CURLOPT_SHARE,      share );
    printf( "CURLOPT_COOKIEJAR\n" );
    curl_easy_setopt( curl, CURLOPT_COOKIEJAR,  JAR );

    printf( "PERFORM\n" );
    curl_easy_perform( curl );

    /* try to free share, expect to fail because share is in use*/
    printf( "try SHARE_CLEANUP...\n" );
    scode = curl_share_cleanup( share );
    if ( scode==CURLSHE_OK )
    {
        fprintf(stderr, "curl_share_cleanup succeed but error expected\n");
        share = NULL;
    }
    else
    {
        printf( "SHARE_CLEANUP failed, correct\n" );
    }

    /* clean up last handle */
    printf( "CLEANUP\n" );
    curl_easy_cleanup( curl );
    curl_slist_free_all( headers );
    free(url);


    /* free share */
    printf( "SHARE_CLEANUP\n" );
    scode = curl_share_cleanup( share );
    if ( scode!=CURLSHE_OK )
    {
        fprintf(stderr, "curl_share_cleanup failed, code errno %d\n", scode);
    }

    printf( "GLOBAL_CLEANUP\n" );
    curl_global_cleanup();

    return res;
}
Example #22
0
int free_internet() {
	if (curlHnd != NULL) curl_easy_cleanup(curlHnd);
	curl_global_cleanup();
	return 0;
}
Example #23
0
void moloch_http_exit()
{
    curl_global_cleanup();
}
Example #24
0
ConsulRestClient::~ConsulRestClient() {
    curl_global_cleanup();
}
Example #25
0
	~CurlInit() { curl_global_cleanup(); }
Example #26
0
/* test function */
int test(char *URL)
{
  int res;
  CURLSHcode scode = CURLSHE_OK;
  char *url = NULL;
  struct Tdata tdata;
  CURL *curl;
  CURLSH *share;
  struct curl_slist *headers = NULL;
  int i;
  struct userdata user;

  user.text = (char *)"Pigs in space";
  user.counter = 0;

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

  /* prepare share */
  printf( "SHARE_INIT\n" );
  if ((share = curl_share_init()) == NULL) {
    fprintf(stderr, "curl_share_init() failed\n");
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_LOCKFUNC\n" );
    scode = curl_share_setopt( share, CURLSHOPT_LOCKFUNC, my_lock);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_UNLOCKFUNC\n" );
    scode = curl_share_setopt( share, CURLSHOPT_UNLOCKFUNC, my_unlock);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_USERDATA\n" );
    scode = curl_share_setopt( share, CURLSHOPT_USERDATA, &user);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURL_LOCK_DATA_COOKIE\n" );
    scode = curl_share_setopt( share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURL_LOCK_DATA_DNS\n" );
    scode = curl_share_setopt( share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
  }

  if ( CURLSHE_OK != scode ) {
    fprintf(stderr, "curl_share_setopt() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  /* initial cookie manipulation */
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }
  printf( "CURLOPT_SHARE\n" );
  test_setopt( curl, CURLOPT_SHARE,      share );
  printf( "CURLOPT_COOKIELIST injected_and_clobbered\n" );
  test_setopt( curl, CURLOPT_COOKIELIST,
               "Set-Cookie: injected_and_clobbered=yes; "
               "domain=host.foo.com; expires=Sat Feb 2 11:56:27 GMT 2030" );
  printf( "CURLOPT_COOKIELIST ALL\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "ALL" );
  printf( "CURLOPT_COOKIELIST session\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "Set-Cookie: session=elephants" );
  printf( "CURLOPT_COOKIELIST injected\n" );
  test_setopt( curl, CURLOPT_COOKIELIST,
               "Set-Cookie: injected=yes; domain=host.foo.com; "
               "expires=Sat Feb 2 11:56:27 GMT 2030" );
  printf( "CURLOPT_COOKIELIST SESS\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "SESS" );
  printf( "CLEANUP\n" );
  curl_easy_cleanup( curl );


  res = 0;

  /* start treads */
  for (i=1; i<=THREADS; i++ ) {

    /* set thread data */
    tdata.url   = suburl( URL, i ); /* must be curl_free()d */
    tdata.share = share;

    /* simulate thread, direct call of "thread" function */
    printf( "*** run %d\n",i );
    fire( &tdata );

    curl_free( tdata.url );

  }


  /* fetch a another one and save cookies */
  printf( "*** run %d\n", i );
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  url = suburl( URL, i );
  headers = sethost( NULL );
  test_setopt( curl, CURLOPT_HTTPHEADER, headers );
  test_setopt( curl, CURLOPT_URL,        url );
  printf( "CURLOPT_SHARE\n" );
  test_setopt( curl, CURLOPT_SHARE,      share );
  printf( "CURLOPT_COOKIEJAR\n" );
  test_setopt( curl, CURLOPT_COOKIEJAR,  JAR );
  printf( "CURLOPT_COOKIELIST FLUSH\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "FLUSH" );

  printf( "PERFORM\n" );
  curl_easy_perform( curl );

  /* try to free share, expect to fail because share is in use*/
  printf( "try SHARE_CLEANUP...\n" );
  scode = curl_share_cleanup( share );
  if ( scode==CURLSHE_OK )
  {
    fprintf(stderr, "curl_share_cleanup succeed but error expected\n");
    share = NULL;
  } else {
    printf( "SHARE_CLEANUP failed, correct\n" );
  }

test_cleanup:

  /* clean up last handle */
  printf( "CLEANUP\n" );
  curl_easy_cleanup( curl );

  if ( headers )
    curl_slist_free_all( headers );

  if ( url )
    curl_free(url);

  /* free share */
  printf( "SHARE_CLEANUP\n" );
  scode = curl_share_cleanup( share );
  if ( scode!=CURLSHE_OK )
    fprintf(stderr, "curl_share_cleanup failed, code errno %d\n",
            (int)scode);

  printf( "GLOBAL_CLEANUP\n" );
  curl_global_cleanup();

  return res;
}
Example #27
0
void CommandDispatcher (int32_t pProcNum, sLONG_PTR *pResult, PackagePtr pParams)
{
	switch(pProcNum)
	{
		case kInitPlugin :
			curl_global_init(CURL_GLOBAL_ALL);
			break;
			
		case kDeinitPlugin :
			curl_global_cleanup();
			break;			
            // --- PKCS
            
		case 1 :
			PEM_From_P12(pResult, pParams);
			break;
            
            // --- MISC
            
		case 2 :
			PICTURE_GET_RAW_DATA(pResult, pParams);
			break;
            
		case 3 :
			STACK_Get_available_size(pResult, pParams);
			break;
            
		case 4 :
			PROCESS_GET_LIST(pResult, pParams);
			break;
            
		case 5 :
			PROCESS_Get_id(pResult, pParams);
			break;
            
		case 6 :
			SYSTEM_Get_timestamp(pResult, pParams);
			break;
            
		case 7 :
			SYSTEM_Get_timestring(pResult, pParams);
			break;
            
		case 8 :
			SYSTEM_Generate_UUID(pResult, pParams);
			break;
            
		case 9 :
			SYSTEM_Get_unixtime(pResult, pParams);
			break;
            
		case 10 :
			STRUCTURE_Import_definition(pResult, pParams);
			break;
            
		case 11 :
			VOLUME_Is_remote(pResult, pParams);
			break;
            
		case 12 :
			VOLUME_Is_ejectable(pResult, pParams);
			break;
            
		case 13 :
			PATH_Get_known_folder(pResult, pParams);
			break;
            
		case 14 :
			PATH_From_user_selection(pResult, pParams);
			break;
            
            // --- JSON
            
		case 15 :
			JSON_Strip_white_space(pResult, pParams);
			break;
            
		case 16 :
			JSON_Parse_text(pResult, pParams);
			break;
            
		case 17 :
			JSON_Export_to_text(pResult, pParams);
			break;
            
		case 18 :
			JSON_CLOSE(pResult, pParams);
			break;
            
		case 19 :
			JSON_New(pResult, pParams);
			break;
            
		case 20 :
			JSON_GET_BOOL_ARRAY(pResult, pParams);
			break;
            
		case 21 :
			JSON_GET_CHILD_NODES(pResult, pParams);
			break;
            
		case 22 :
			JSON_GET_LONG_ARRAY(pResult, pParams);
			break;
            
		case 23 :
			JSON_Get_child_by_name(pResult, pParams);
			break;
            
		case 24 :
			JSON_Get_child_by_position(pResult, pParams);
			break;
            
		case 25 :
			JSON_Get_comment(pResult, pParams);
			break;
            
		case 26 :
			JSON_GET_TEXT_ARRAY(pResult, pParams);
			break;
            
		case 27 :
			JSON_GET_REAL_ARRAY(pResult, pParams);
			break;
            
		case 28 :
			JSON_Get_bool(pResult, pParams);
			break;
            
		case 29 :
			JSON_Get_real(pResult, pParams);
			break;
            
		case 30 :
			JSON_Get_long(pResult, pParams);
			break;
            
		case 31 :
			JSON_Get_type(pResult, pParams);
			break;
            
		case 32 :
			JSON_Get_name(pResult, pParams);
			break;
            
		case 33 :
			JSON_Get_text(pResult, pParams);
			break;
            
		case 34 :
			JSON_DELETE_ITEM_BY_NAME(pResult, pParams);
			break;
            
		case 35 :
			JSON_DELETE_ITEM_BY_POSITION(pResult, pParams);
			break;
            
		case 36 :
			JSON_SET_TYPE(pResult, pParams);
			break;
            
		case 37 :
			JSON_SET_NULL(pResult, pParams);
			break;
            
		case 38 :
			JSON_SET_COMMENT(pResult, pParams);
			break;
            
		case 39 :
			JSON_SET_NAME(pResult, pParams);
			break;
            
		case 40 :
			JSON_SET_TEXT(pResult, pParams);
			break;
            
		case 41 :
			JSON_SET_LONG(pResult, pParams);
			break;
            
		case 42 :
			JSON_SET_REAL(pResult, pParams);
			break;
            
		case 43 :
			JSON_Append_bool_array(pResult, pParams);
			break;
            
		case 44 :
			JSON_Append_real_array(pResult, pParams);
			break;
            
		case 45 :
			JSON_Append_long_array(pResult, pParams);
			break;
            
		case 46 :
			JSON_Append_text_array(pResult, pParams);
			break;
            
		case 47 :
			JSON_Append_text(pResult, pParams);
			break;
            
		case 48 :
			JSON_Append_long(pResult, pParams);
			break;
            
		case 49 :
			JSON_Append_real(pResult, pParams);
			break;
            
		case 50 :
			JSON_Append_bool(pResult, pParams);
			break;
            
		case 51 :
			JSON_Append_node(pResult, pParams);
			break;
            
		case 52 :
			JSON_SET_BOOL(pResult, pParams);
			break;
            
		case 53 :
			JSON_CLEAR(pResult, pParams);
			break;
            
            // --- ZIP
            
		case 54 :
			Unzip(pResult, pParams);
			break;
            
		case 55 :
			Zip(pResult, pParams);
			break;
            
            // --- Common Crypto
            
		case 56 :
			RSASHA256(pResult, pParams);
			break;
            
		case 57 :
			HMACMD5(pResult, pParams);
			break;
            
		case 58 :
			HMACSHA1(pResult, pParams);
			break;
            
		case 59 :
			HMACSHA256(pResult, pParams);
			break;
            
		case 60 :
			HMACSHA384(pResult, pParams);
			break;
            
		case 61 :
			HMACSHA512(pResult, pParams);
			break;
            
		case 62 :
			SHA384(pResult, pParams);
			break;
            
		case 63 :
			SHA512(pResult, pParams);
			break;
            
		case 64 :
			MD5(pResult, pParams);
			break;
            
		case 65 :
			SHA1(pResult, pParams);
			break;
            
		case 66 :
			SHA256(pResult, pParams);
			break;
            
            // --- cURL
            
		case 67 :
			_cURL(pResult, pParams);
			break;
            
		case 68 :
			cURL_Escape_url(pResult, pParams);
			break;
            
		case 69 :
			cURL_Unescape_url(pResult, pParams);
			break;
            
		case 70 :
			cURL_Get_version(pResult, pParams);
			break;
            
		case 71 :
			cURL_Get_date(pResult, pParams);
			break;
			
	}
}
Example #28
0
int test(char *URL)
{
  int res = 0;
  CURL *curl[NUM_HANDLES];
  int running;
  char done=FALSE;
  CURLM *m;
  int i, j;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;
  char target_url[256];

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

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

  /* get NUM_HANDLES easy handles */
  for(i=0; i < NUM_HANDLES; i++) {
    curl[i] = curl_easy_init();
    if(!curl[i]) {
      fprintf(stderr, "curl_easy_init() failed "
              "on handle #%d\n", i);
      for (j=i-1; j >= 0; j--) {
        curl_multi_remove_handle(m, curl[j]);
        curl_easy_cleanup(curl[j]);
      }
      curl_multi_cleanup(m);
      curl_global_cleanup();
      return TEST_ERR_MAJOR_BAD + i;
    }
    sprintf(target_url, "%s%04i", URL, i + 1);
    target_url[sizeof(target_url) - 1] = '\0';

    res = curl_easy_setopt(curl[i], CURLOPT_URL, target_url);
    if(res) {
      fprintf(stderr, "curl_easy_setopt() failed "
              "on handle #%d\n", i);
      for (j=i; j >= 0; j--) {
        curl_multi_remove_handle(m, curl[j]);
        curl_easy_cleanup(curl[j]);
      }
      curl_multi_cleanup(m);
      curl_global_cleanup();
      return TEST_ERR_MAJOR_BAD + i;
    }

    /* go verbose */
    res = curl_easy_setopt(curl[i], CURLOPT_VERBOSE, 1L);
    if(res) {
      fprintf(stderr, "curl_easy_setopt() failed "
              "on handle #%d\n", i);
      for (j=i; j >= 0; j--) {
        curl_multi_remove_handle(m, curl[j]);
        curl_easy_cleanup(curl[j]);
      }
      curl_multi_cleanup(m);
      curl_global_cleanup();
      return TEST_ERR_MAJOR_BAD + i;
    }

    /* include headers */
    res = curl_easy_setopt(curl[i], CURLOPT_HEADER, 1L);
    if(res) {
      fprintf(stderr, "curl_easy_setopt() failed "
              "on handle #%d\n", i);
      for (j=i; j >= 0; j--) {
        curl_multi_remove_handle(m, curl[j]);
        curl_easy_cleanup(curl[j]);
      }
      curl_multi_cleanup(m);
      curl_global_cleanup();
      return TEST_ERR_MAJOR_BAD + i;
    }

    /* add handle to multi */
    if ((res = (int)curl_multi_add_handle(m, curl[i])) != CURLM_OK) {
      fprintf(stderr, "curl_multi_add_handle() failed, "
              "on handle #%d with code %d\n", i, res);
      curl_easy_cleanup(curl[i]);
      for (j=i-1; j >= 0; j--) {
        curl_multi_remove_handle(m, curl[j]);
        curl_easy_cleanup(curl[j]);
      }
      curl_multi_cleanup(m);
      curl_global_cleanup();
      return TEST_ERR_MAJOR_BAD + i;
    }
  }

  curl_multi_setopt(m, CURLMOPT_PIPELINING, 1L);

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  fprintf(stderr, "Start at URL 0\n");

  while (!done) {
    fd_set rd, wr, exc;
    int max_fd;
    struct timeval interval;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }
    mp_timedout = FALSE;
    mp_start = tutil_tvnow();

    while (res == CURLM_CALL_MULTI_PERFORM) {
      res = (int)curl_multi_perform(m, &running);
      if (tutil_tvdiff(tutil_tvnow(), mp_start) >
          MULTI_PERFORM_HANG_TIMEOUT) {
        mp_timedout = TRUE;
        break;
      }
      if (running <= 0) {
        done = TRUE; /* bail out */
        break;
      }
    }
    if (mp_timedout || done)
      break;

    if (res != CURLM_OK) {
      fprintf(stderr, "not okay???\n");
      break;
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);
    max_fd = 0;

    if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
      fprintf(stderr, "unexpected failured of fdset.\n");
      res = 189;
      break;
    }

    if (select_test(max_fd+1, &rd, &wr, &exc, &interval) == -1) {
      fprintf(stderr, "bad select??\n");
      res = 195;
      break;
    }

    res = CURLM_CALL_MULTI_PERFORM;
  }

  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

/* test_cleanup: */

  /* cleanup NUM_HANDLES easy handles */
  for(i=0; i < NUM_HANDLES; i++) {
    curl_multi_remove_handle(m, curl[i]);
    curl_easy_cleanup(curl[i]);
  }

  curl_multi_cleanup(m);
  curl_global_cleanup();

  return res;
}
Example #29
0
void QBox_Global_Cleanup()
{
	curl_global_cleanup();
}
Example #30
0
void CWebTV::processPlaylistUrl(const char *url, const char *name, const char * description) 
{
	dprintf(DEBUG_DEBUG, "CWebTV::processPlaylistUrl\n");
	
	CURL *curl_handle;
	struct MemoryStruct chunk;
	
	chunk.memory = NULL; 	/* we expect realloc(NULL, size) to work */
	chunk.size = 0;    	/* no data at this point */

	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, WriteMemoryCallback);

	/* we pass our 'chunk' struct to the callback function */
	curl_easy_setopt(curl_handle, 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_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

	/* don't use signal for timeout */
	curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, (long)1);

	/* set timeout to 10 seconds */
	curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 10);
	
	if(strcmp(g_settings.softupdate_proxyserver, "")!=0)
	{
		curl_easy_setopt(curl_handle, CURLOPT_PROXY, g_settings.softupdate_proxyserver);
		
		if(strcmp(g_settings.softupdate_proxyusername, "") != 0)
		{
			char tmp[200];
			strcpy(tmp, g_settings.softupdate_proxyusername);
			strcat(tmp, ":");
			strcat(tmp, g_settings.softupdate_proxypassword);
			curl_easy_setopt(curl_handle, CURLOPT_PROXYUSERPWD, tmp);
		}
	}

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

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

	/*
	* Now, our chunk.memory points to a memory block that is chunk.size
	* bytes big and contains the remote file.
	*
	* Do something nice with it!
	*
	* You should be aware of the fact that at this point we might have an
	* allocated data block, and nothing has yet deallocated that data. So when
	* you're done with it, you should free() it as a nice application.
	*/

	long res_code;
	if (curl_easy_getinfo(curl_handle, CURLINFO_HTTP_CODE, &res_code ) ==  CURLE_OK) 
	{
		if (200 == res_code) 
		{
			//printf("\nchunk = %s\n", chunk.memory);
			std::istringstream iss;
			iss.str (std::string(chunk.memory, chunk.size));
			char line[512];
			char *ptr;
			
			while (iss.rdstate() == std::ifstream::goodbit) 
			{
				iss.getline(line, 512);
				if (line[0] != '#') 
				{
					//printf("chunk: line = %s\n", line);
					ptr = strstr(line, "http://");
					if (ptr != NULL) 
					{
						char *tmp;
						// strip \n and \r characters from url
						tmp = strchr(line, '\r');
						if (tmp != NULL)
							*tmp = '\0';
						tmp = strchr(line, '\n');
						if (tmp != NULL)
							*tmp = '\0';
						
						addUrl2Playlist(ptr, name, description);
					}
				}
			}
		}
	}

	if(chunk.memory)
		free(chunk.memory);
 
	/* we're done with libcurl, so clean it up */
	curl_global_cleanup();
}