Beispiel #1
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;
}
Beispiel #2
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;
			
	}
}
Beispiel #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;
}
Beispiel #4
0
Datei: http.c Projekt: hkjels/git
void http_init(struct remote *remote, const char *url, int proactive_auth)
{
	char *low_speed_limit;
	char *low_speed_time;

	http_is_verbose = 0;

	git_config(http_options, NULL);

	curl_global_init(CURL_GLOBAL_ALL);

	http_proactive_auth = proactive_auth;

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

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

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

	curlm = curl_multi_init();
	if (curlm == NULL) {
		fprintf(stderr, "Error creating curl multi handle.\n");
		exit(1);
	}
#endif

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

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

	set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");

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

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

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

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

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

#ifndef NO_CURL_EASY_DUPHANDLE
	curl_default = get_curl_handle();
#endif
}
Beispiel #5
0
void saldl(saldl_params *params_ptr) {
  /* Definitions */
  info_s info = DEF_INFO_S;
  info.params = params_ptr;

  /* Handle signals */
  info_global = &info;
  saldl_handle_signals();

  /* Need to be set as early as possible */
  set_color(&params_ptr->no_color);
  set_verbosity(&params_ptr->verbosity, &params_ptr->libcurl_verbosity);

  /* Check if loaded libcurl is recent enough */
  info.curl_info = curl_version_info(CURLVERSION_NOW);
  check_libcurl(info.curl_info);

  /* Library initializations, should run only once */
  SALDL_ASSERT(!curl_global_init(CURL_GLOBAL_ALL));
  SALDL_ASSERT(!evthread_use_pthreads());

  /* get/set initial info */
  main_msg("URL", "%s", params_ptr->start_url);
  check_url(params_ptr->start_url);
  get_info(&info);
  set_info(&info);
  check_remote_file_size(&info);

  /* initialize chunks early for extra_resume() */
  chunks_init(&info);

  if (params_ptr->resume) {
    check_resume(&info);
  }

  print_chunk_info(&info);
  global_progress_init(&info);

  /* exit here if dry_run was set */
  if ( params_ptr->dry_run  ) {
    saldl_free_all(&info);
    finish_msg_and_exit("Dry-run done.");
  }

  check_files_and_dirs(&info);

  /* Check if download was interrupted after all data was merged */
  if (info.already_finished) {
    goto saldl_all_data_merged;
  }

  /* threads, needed by set_modes() */
  info.threads = saldl_calloc(params_ptr->num_connections, sizeof(thread_s));
  set_modes(&info);

  /* 1st iteration */
  for (size_t counter = 0; counter < params_ptr->num_connections; counter++) {
    queue_next_chunk(&info, counter, 1);
  }

  /* Create event pthreads */
  saldl_pthread_create(&info.trigger_events_pth, NULL, events_trigger_thread, &info);

  if (!params_ptr->read_only && !params_ptr->to_stdout) {
    saldl_pthread_create(&info.sync_ctrl_pth, NULL, sync_ctrl, &info);
  }

  if (info.chunk_count != 1) {
    saldl_pthread_create(&info.status_display_pth, NULL, status_display, &info);
    saldl_pthread_create(&info.queue_next_pth, NULL, queue_next_thread, &info);
    saldl_pthread_create(&info.merger_pth, NULL, merger_thread, &info);
  }

  /* Now that everything is initialized */
  info.session_status = SESSION_IN_PROGRESS;

  /* Avoid race in joining event threads if the session was interrupted, or finishing without downloading if single_mode */
  do {
    usleep(100000);
  } while (params_ptr->single_mode ? info.chunks[0].progress != PRG_FINISHED : info.global_progress.complete_size != info.file_size);

  /* Join event pthreads */
  if (!params_ptr->read_only && !params_ptr->to_stdout) {
    join_event_pth(&info.ev_ctrl ,&info.sync_ctrl_pth);
  }

  if (info.chunk_count !=1) {
    join_event_pth(&info.ev_status, &info.status_display_pth);
    join_event_pth(&info.ev_queue, &info.queue_next_pth);
    join_event_pth(&info.ev_merge, &info.merger_pth);
  }

  info.events_queue_done = true;
  event_queue(&info.ev_trigger, NULL);
  join_event_pth(&info.ev_trigger ,&info.trigger_events_pth);

saldl_all_data_merged:

  /* Remove tmp_dirname */
  if (!params_ptr->read_only && !params_ptr->mem_bufs && !params_ptr->single_mode) {
    if ( rmdir(info.tmp_dirname) ) {
      err_msg(FN, "Failed to delete %s: %s", info.tmp_dirname, strerror(errno) );
    }
  }

  /*** Final Steps ***/

  /* One last check  */
  if (info.file_size && !params_ptr->no_remote_info &&
      !params_ptr->read_only && !params_ptr->to_stdout &&
      (!info.remote_info.content_encoded || params_ptr->no_decompress)) {
    off_t saved_file_size = saldl_fsizeo(info.part_filename, info.file);
    if (saved_file_size != info.file_size) {
      pre_fatal(FN, "Unexpected saved file size (%"SAL_JU"!=%"SAL_JU").", saved_file_size, info.file_size);
      pre_fatal(FN, "This could happen if you're downloading from a dynamic site.");
      pre_fatal(FN, "If that's the case and the download is small, retry with --no-remote-info");
      fatal(FN, "If you think that's a bug in saldl, report it: https://github.com/saldl/saldl/issues");
    }
  }
  else {
    debug_msg(FN, "Strict check for finished file size skipped.");
  }

  if (!params_ptr->read_only && !params_ptr->to_stdout) {
    saldl_fclose(info.part_filename, info.file);
    if (rename(info.part_filename, params_ptr->filename) ) {
      err_msg(FN, "Failed to rename now-complete %s to %s: %s", info.part_filename, params_ptr->filename, strerror(errno));
    }

    saldl_fclose(info.ctrl_filename, info.ctrl_file);
    if ( remove(info.ctrl_filename) ) {
      err_msg(FN, "Failed to remove %s: %s", info.ctrl_filename, strerror(errno));
    }
  }

  /* cleanups */
  curl_cleanup(&info);
  saldl_free_all(&info);

  finish_msg_and_exit("Download Finished.");
}
Beispiel #6
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;
}
	CurlInit() { curl_global_init(CURL_GLOBAL_ALL);	}
static char * rest_get( const char * url, int * code ) {
    CURL * curl = nullptr;
    CURLcode status;
    struct curl_slist * headers = nullptr;
    char * data = nullptr;


    curl = curl_easy_init();
    if( !curl ) {
        curl_clean( data, curl, headers );
        return nullptr;
    }

    data = ( char * ) malloc( BUFFER_SIZE );
    if( !data ) {
        curl_clean( data, curl, headers );
        return nullptr;
    }

    struct curl_payload result = {
            .data = data,
            .size = 0
    };

    curl_easy_setopt( curl, CURLOPT_URL, url );
    curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_callback );
    curl_easy_setopt( curl, CURLOPT_WRITEDATA, &result );

    status = curl_easy_perform( curl );
    if( status != 0 ) {
        LOG( ERROR ) << "Error: unable to request data from " << url ;
        LOG( ERROR ) << "curl_easy_perform() fail: " << curl_easy_strerror( status );
        curl_clean( data, curl, headers );
        *code = 500;
        return nullptr;
    }

    curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, code );
    if( *code != 200 ) {
        LOG( ERROR ) << "Error: server responded with code " << *code;
        curl_clean( data, curl, headers );
        return nullptr;
    }

    LOG( INFO ) << "curl_easy_getinfo() successfully.";

    curl_clean( nullptr, curl, headers );
    data[result.size] = '\0';

    return data;
}

static int rest_put( const char * url, struct curl_payload * payload ) {
    CURL * curl = nullptr;
    CURLcode status;

    curl_global_init( CURL_GLOBAL_ALL );

    curl = curl_easy_init();
    if( !curl ) {
        curl_clean( nullptr, curl, nullptr );
        return 500;
    }

    curl_easy_setopt( curl, CURLOPT_READFUNCTION, read_callback );
    curl_easy_setopt( curl, CURLOPT_UPLOAD, 1L );
    curl_easy_setopt( curl, CURLOPT_PUT, 1L );
    curl_easy_setopt( curl, CURLOPT_URL, url );
    curl_easy_setopt( curl, CURLOPT_READDATA, payload );

    status = curl_easy_perform( curl );

    if( status != CURLE_OK ) {
        LOG( ERROR ) << "curl_easy_perform() failed: " << curl_easy_strerror( status );
        curl_clean( nullptr, curl, nullptr );
        return 500;
    }

    LOG( INFO ) << "curl_easy_perform() put successfully.";

    curl_clean( nullptr, curl, nullptr );
    return 0;
}
Beispiel #9
0
int main(int argc, char *argv[]) {
    
    hashset_t set = hashset_create();
    hashset_add(set,"leer");
    curl_global_init(CURL_GLOBAL_ALL);
    CURL * myHandle = curl_easy_init();
    char md5Password [32];
    struct string s;
    struct string g;
    init_string(&s);
    init_string(&g);
    int i;
    /*
      char password[BUFSIZ];
      char name[BUFSIZ];
      printf("Enter Username: \n");
      fgets(name, BUFSIZ, stdin);
      printf("Enter Password: \n");
      fgets(password,BUFSIZ,stdin);
      cleaner(name);
      cleaner(password);
     */

    //temp
    char password [] = "569dgBAh#6Kv2^e9z^ALFiOq";
    char name [] = "Foxi";

    //temp

    hashPassword(password, md5Password);
    doLogin(name, md5Password, myHandle);

    sleep(3);
    getSecretToken(myHandle,&s);
    sleep(3);

    char* tokenarray = (char*) malloc((s.len + 3) * sizeof (char));

    strcpy(tokenarray, s.ptr);
    findSecretToken(tokenarray, s.len);
    
    //Hier muss die URL hin auf welche Danke gesagt wird!
    char danke [] = "http://usenet-4all.info/forum/showthread.php?t=637647";
    doTanks(danke,&g, myHandle);

    char* pidarray = (char*) malloc((g.len + 3) * sizeof (char));
    strcpy(pidarray, g.ptr);
    findPid(pidarray, g.len, set);
    //Ab hier habe ich alle PIDS!
    pushthanks(tokenarray,danke,set,myHandle);
    
    
    print_cookies(myHandle);
    curl_easy_cleanup(myHandle);

    free(s.ptr);

    free(tokenarray);
    free(pidarray);

    free(g.ptr);


    return 0;
}
Beispiel #10
0
static void curl_once_routine(){
	if(curl_global_init(CURL_GLOBAL_ALL)){
		fprintf(stderr, "Could not init cURL\n");		
		abort();
	}
}
ConsulRestClient::ConsulRestClient() {
    curl_global_init( CURL_GLOBAL_ALL );
}
Beispiel #12
0
static int curl_open(BlockDriverState *bs, QDict *options, int flags,
                     Error **errp)
{
    BDRVCURLState *s = bs->opaque;
    CURLState *state = NULL;
    QemuOpts *opts;
    Error *local_err = NULL;
    const char *file;
    double d;

    static int inited = 0;

    if (flags & BDRV_O_RDWR) {
        error_setg(errp, "curl block device does not support writes");
        return -EROFS;
    }

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out_noclean;
    }

    s->readahead_size = qemu_opt_get_size(opts, "readahead", READ_AHEAD_SIZE);
    if ((s->readahead_size & 0x1ff) != 0) {
        error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
                   s->readahead_size);
        goto out_noclean;
    }

    file = qemu_opt_get(opts, "url");
    if (file == NULL) {
        error_setg(errp, "curl block driver requires an 'url' option");
        goto out_noclean;
    }

    if (!inited) {
        curl_global_init(CURL_GLOBAL_ALL);
        inited = 1;
    }

    DPRINTF("CURL: Opening %s\n", file);
    s->url = g_strdup(file);
    state = curl_init_state(s);
    if (!state)
        goto out_noclean;

    // Get file size

    s->accept_range = false;
    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
    curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
                     curl_header_cb);
    curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
    if (curl_easy_perform(state->curl))
        goto out;
    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);
    if (d)
        s->len = (size_t)d;
    else if(!s->len)
        goto out;
    if ((!strncasecmp(s->url, "http://", strlen("http://"))
        || !strncasecmp(s->url, "https://", strlen("https://")))
        && !s->accept_range) {
        pstrcpy(state->errmsg, CURL_ERROR_SIZE,
                "Server does not support 'range' (byte ranges).");
        goto out;
    }
    DPRINTF("CURL: Size = %zd\n", s->len);

    curl_clean_state(state);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;

    aio_timer_init(bdrv_get_aio_context(bs), &s->timer,
                   QEMU_CLOCK_REALTIME, SCALE_NS,
                   curl_multi_timeout_do, s);

    // Now we know the file exists and its size, so let's
    // initialize the multi interface!

    s->multi = curl_multi_init();
    curl_multi_setopt(s->multi, CURLMOPT_SOCKETDATA, s);
    curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
#ifdef NEED_CURL_TIMER_CALLBACK
    curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
    curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
#endif
    curl_multi_do(s);

    qemu_opts_del(opts);
    return 0;

out:
    fprintf(stderr, "CURL: Error opening file: %s\n", state->errmsg);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;
out_noclean:
    g_free(s->url);
    qemu_opts_del(opts);
    return -EINVAL;
}
Beispiel #13
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;
}
Beispiel #14
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;
}
Beispiel #15
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;
}
Beispiel #16
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;
}
Beispiel #17
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;
}
Beispiel #18
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;
}
Beispiel #19
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
}
/**
* Uploads the save file to CloudyWeb.
*
* @param Filename               Filename of the save game file.
* @param PlayerControllerId     PlayerControllerId of the player who is saving the game.
*
* @return Returns true if the file upload was successful. Else, returns false.
*
*/
bool CloudyWebConnectorImpl::UploadFile(FString Filename, int32 PlayerControllerId)
{
    bool RequestSuccess = false;

    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    
    FString Url = BaseUrl + SaveDataUrl;
    std::string UrlCString(TCHAR_TO_UTF8(*Url));
    
    // Filepath of .sav file
    FString Filepath = FPaths::GameDir();
    Filepath += "Saved/SaveGames/" + Filename + ".sav";
    std::string filePath(TCHAR_TO_UTF8(*Filepath));
    
    // Get game name
    FString GameName = FApp::GetGameName();
    std::string gameName(TCHAR_TO_UTF8(*GameName));

    // Get game ID
    FString GameID = FString::FromInt(GetGameId());
    std::string GameIDCString(TCHAR_TO_UTF8(*GameID));

    // Get username
    FString Username = GetUsername(PlayerControllerId);
    std::string UsernameCString(TCHAR_TO_UTF8(*Username));
    
    // Convert PlayerControllerId
    FString playerControllerIdFString = FString::FromInt(PlayerControllerId);
    std::string playerControllerId(TCHAR_TO_UTF8(*playerControllerIdFString));

    if (GetGameId() == -1 || Username.Equals("") || PlayerControllerId < 0)
    {
        UE_LOG(CloudyWebConnectorLog, Error, TEXT("The game ID, username, or player controller ID is invalid"));
        return false;
    }
    
    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    struct curl_slist *headerlist = NULL;
    FString AuthHeader = "Authorization: Token " + Token;
    std::string AuthHeaderCString(TCHAR_TO_UTF8(*AuthHeader));
    
    curl_global_init(CURL_GLOBAL_ALL);
    
    /* Fill in the file upload field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "saved_file",
        CURLFORM_FILE, filePath.c_str(),
        CURLFORM_END);
    
    /* Fill in the player controller ID field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "user",
        CURLFORM_COPYCONTENTS, UsernameCString.c_str(),
        CURLFORM_END);
    
    /* Fill in the game name field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "game",
        CURLFORM_COPYCONTENTS, GameIDCString.c_str(),
        CURLFORM_END);
    
    curl = curl_easy_init();
    /* initialize custom header list (stating that Expect: 100-continue is not
    wanted */
    headerlist = curl_slist_append(headerlist, AuthHeaderCString.c_str());
    if (curl) {
        /* what URL that receives this POST */
        curl_easy_setopt(curl, CURLOPT_URL, UrlCString.c_str());

        /* only disable 100-continue header if explicitly requested */
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

        /* What form to send */
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
    
        /* Set up string to write response into */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check if the request was successful */
        if (res == CURLE_OK)
        {
            RequestSuccess = true;
        }
    
        /* always cleanup */
        curl_easy_cleanup(curl);
    
        /* then cleanup the formpost chain */
        curl_formfree(formpost);
        /* free slist */
        curl_slist_free_all(headerlist);
    
        UE_LOG(CloudyWebConnectorLog, Warning, TEXT("Response data: %s"), UTF8_TO_TCHAR(readBuffer.c_str()));
        ReadAndStoreSaveFileURL(readBuffer.c_str(), PlayerControllerId);
    }

    return RequestSuccess;
}
Beispiel #21
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;
}
Beispiel #22
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 */
}
Beispiel #23
0
/* This should to be called from main() to make sure thread safe */
void curl_download_init()
{
  curl_global_init(CURL_GLOBAL_ALL);
  get_cookie_file(TRUE);
  curl_download_user_agent = g_strdup_printf ("%s/%s %s", PACKAGE, VERSION, curl_version());
}
Beispiel #24
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;
}
int main (int argc, char* argv[]) {
  if (argc < 3) {
    std::cout << "Need HOST and PORT as command line arguments." << std::endl;
    return 1;
  }
  if (argc >= 4) {
    N = atoi(argv[3]);
  }
  std::string resulturl;
  if (argc >= 5) {
    resulturl = argv[4];
  }

  std::cout << "ArangoDB latency test, calling " << N 
            << " times GET /_api/document/c/mykey" << std::endl;

  std::vector<uint64_t> timings;
  timings.reserve(N);

  std::string url = std::string("http://") + argv[1] + ":" + argv[2];
  std::string urlcomplete;

  curl_global_init(CURL_GLOBAL_DEFAULT);
  CURL* h = curl_easy_init();

  // Delete the collection c:
  std::cout << "Dropping collection c..." << std::endl;
  curl_easy_setopt(h, CURLOPT_CUSTOMREQUEST, "DELETE");
  urlcomplete = url + "/_api/collection/c";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  curl_easy_perform(h);
  curl_easy_setopt(h, CURLOPT_CUSTOMREQUEST, NULL);
  std::cout << "\ndone." << std::endl;

  std::cout << "Creating collection c..." << std::endl;
  strcpy(buffer, "{\"name\": \"c\", \"numberOfShards\":13}");
  urlcomplete = url + "/_api/collection";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  struct curl_slist *headers=NULL;
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(h, CURLOPT_POSTFIELDS, buffer);
  curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE, strlen(buffer));
  curl_easy_perform(h);
  curl_slist_free_all(headers);
  headers = NULL;
  std::cout << "\ndone." << std::endl;

  std::cout << "Creating one document..." << std::endl;
  strcpy(buffer, "{\"_key\":\"mykey\", \"name\":\"Neunhöffer\", \"firstName\":\"Max\"}");
  urlcomplete = url + "/_api/document?collection=c";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(h, CURLOPT_POSTFIELDS, buffer);
  curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE, strlen(buffer));
  curl_easy_perform(h);
  curl_slist_free_all(headers);
  std::cout << "\ndone." << std::endl;

  curl_easy_setopt(h, CURLOPT_HTTPGET, 1);
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, NULL);
  curl_easy_setopt(h, CURLOPT_TCP_NODELAY, 1);

  std::cout << "Now racing..." << std::endl;
  timePointType t = timeNow();
  urlcomplete = url + "/_api/document/c/mykey";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
  timePointType t3, t4;
  for (int i = 0; i < N; i++) {
    pos = 0;
    t3 = timeNow();
    int success = curl_easy_perform(h);
    t4 = timeNow();
    timings.push_back(timeDiff(t3,t4));
    buffer[pos] = 0;
  }
  curl_easy_cleanup(h);
  timePointType t2 = timeNow();
  uint64_t d = timeDiff(t,t2);
  std::cout << "Total time: " << d << " ns" << std::endl;
  analyzeTimings("arangoTestDocument" + std::to_string(getpid()) 
                 + ".times", timings, N);
  dumpTimings("arangoTestDocument" + std::to_string(getpid()) 
              + ".times", timings);
  if (! resulturl.empty()) {
    submitTimings(resulturl, "readDocument", timings, N-1);
  }
  return 0;
}
Beispiel #26
0
int main(int argc, char *argv[]) {

	char *ally = "ally.txt", *play = "tribe.txt", *village = "village.txt", *oda = "kill_att.txt", *odd = "kill_def.txt", *ods = "kill_sup.txt", *odaT = "kill_att_tribe.txt", *oddT = "kill_def_tribe.txt", *conquer = "conquer.txt";
	char buffer[256];

	unsigned int topTribeRanks[15] = { 0 }, topPlayerRanks[15] = { 0 }, topODARanks[15] = { 0 }, topODDRanks[15] = { 0 }, topODSRanks[15] = { 0 }, topODATRanks[15] = { 0 }, topODDTRanks[15] = { 0 }, topPlayerConqRanks[15] = { 0 }, topPlayerLossRanks[15] = { 0 }, topTribeConqRanks[15] = { 0 }, topTribeLossRanks[15] = { 0 };

	URL_FILE *handle;
	std::string urlBase, urlFinish;
	const char *url;
	CURL *cURL;

	curl_global_init(CURL_GLOBAL_DEFAULT);
	cURL = curl_easy_init();

	std::string data, filePath;
	std::vector<std::string> servers, serverNames, serverEnds;
	std::ifstream serverFile;

	//read in server list
	int bytes = GetModuleFileName(NULL, buffer, 256);
	if (bytes == 0)
		return EXIT_FAILURE;
	else
		filePath = buffer;

	data = filePath.substr(0, filePath.find_last_of('\\'));

	data += "\\Servers\\servers.txt";
	serverFile.open(data);

	if (serverFile.is_open()) {

		while (std::getline(serverFile, data)) {//27 total

			unsigned int fstPos = 0, secPos = 0;

			if (data[0] == ';')
				continue;

			secPos = data.find(' ');
			servers.push_back(data.substr(fstPos, secPos- fstPos));

			fstPos = secPos + 1;
			secPos = data.find(' ', fstPos);
			serverNames.push_back(data.substr(fstPos, secPos - fstPos).c_str());
			serverEnds.push_back(data.substr(secPos + 1, data.length() - (secPos + 1)));

		}

	}
	else
		return EXIT_FAILURE;

	serverFile.close();

	//Read in colors to file
	std::ifstream inFile;
	inFile.open("colors.txt");

	unsigned int colors[45] = { 0 };

	for (int count = 0; std::getline(inFile, data); count++) {

		unsigned int fstPos = 0, secPos = 0;

		secPos = data.find(' ');
		colors[count * 3] = atoi(data.substr(fstPos, secPos - fstPos).c_str());

		fstPos = secPos + 1;
		secPos = data.find(' ', fstPos);
		colors[count * 3 + 1] = atoi(data.substr(fstPos, secPos - fstPos).c_str());

		colors[count * 3 + 2] = atoi(data.substr(secPos + 1, data.length() - (secPos + 1)).c_str());

	}

	inFile.close();
	time_t timer;

	while (true) {

		timer = std::time(NULL);

		if (timer % 86400 == 23250) {

			unsigned int ServerCount = 0;

			int bytes = GetModuleFileName(NULL, buffer, 256);
			if (bytes == 0)
				return EXIT_FAILURE;
			else
				filePath = buffer;

			std::string worldFileName = filePath.substr(0, filePath.find_last_of('\\')); 
			worldFileName += "\\Servers\\Worlds\\" + servers.at(ServerCount) + "worlds.txt";
			std::ifstream worldFile;
			worldFile.open(worldFileName);

			if (worldFile.is_open()) {

				while (std::getline(worldFile, data)) {

					if (data[0] == ';')
						continue;

					std::string world = servers.at(ServerCount) + data;

					urlBase = "https://";
					urlBase += world;
					//urlBase += ".tribalwars.net/map/";
					urlBase += '.' + serverNames.at(ServerCount) + '.' + serverEnds.at(ServerCount) + "/map/";

					urlFinish = urlBase + ally;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					For handling data, first the tribe data must be stored, then the player data, to be able to link players to tribes.
					Afterwards, everything can be handled at the same time - 3+ threads.
					*/

					std::vector<tribe> tribes;

					//Read in Tribe data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						size_t comFstPos = 0, comSecPos = 0;

						tribes.push_back(tribe());

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL) return EXIT_FAILURE;
						bufferString = buffer;

						comSecPos = bufferString.find(',');

						tribes.at(count).setID(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setName(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setTag(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setMemb(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setVills(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setTopPoints(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setPoints(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribes.at(count).setRank(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()) <= 15)
							topTribeRanks[atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()) - 1] = tribes.size() - 1;

						comFstPos = 0;
						comSecPos = 0;

					}

					url_fclose(handle);

					urlFinish = urlBase + play;
					url = urlFinish.c_str();
					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					std::vector<player> players;

					//Read in player data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						size_t comFstPos = 0, comSecPos = 0;
						unsigned int tribeIDCheck = 0, chkID = 0;

						players.push_back(player());

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL) return EXIT_FAILURE;
						bufferString = buffer;

						comSecPos = bufferString.find(',');

						players.at(count).setID(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						players.at(count).setName(bufferString.substr(comFstPos, comSecPos - comFstPos));

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribeIDCheck = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (tribeIDCheck != 0)
							tribeIDCheck = tbinarySearch(tribeIDCheck, 0, tribes.size(), tribes);

						if (tribeIDCheck != NULL) {

							players.at(count).setTribeID(tribeIDCheck);
							tribes.at(tribeIDCheck).addMember(players.size() - 1);

						}

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						players.at(count).setVill(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						players.at(count).setPoints(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						players.at(count).setRank(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()) <= 15)
							topPlayerRanks[atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()) - 1] = players.size() - 1;

						comFstPos = 0;
						comSecPos = 0;

					}

					url_fclose(handle);

					urlFinish = urlBase + village;
					url = urlFinish.c_str();

					unsigned int zoom = 500;

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					std::vector<villages> allVills;

					//Read village data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0;
						unsigned int playerIDCheck = 0;
						unsigned int x = 0, y = 0;
						unsigned int points = 0;

						allVills.push_back(villages());

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');

						allVills.at(count).setID(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						x = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (x < zoom)
							zoom = x;

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						y = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						playerIDCheck = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						points = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (playerIDCheck)
							playerIDCheck = pbinarySearch(playerIDCheck, 0, players.size(), players);
						if (playerIDCheck != NULL) {

							players.at(playerIDCheck).addVillage(x, y);

							allVills.at(count).setPlayerID(playerIDCheck);
							allVills.at(count).setX(x);
							allVills.at(count).setY(y);
							allVills.at(count).setPoints(points);

						}
					}

					if (zoom > 400)
						zoom = 5;
					else if (zoom > 300)
						zoom = 2;
					else
						zoom = 1;

					urlFinish = urlBase + oda;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					//read ODA data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0, rank = 0, player = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');
						rank = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						player = pbinarySearch(atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()), 0, players.size(), players);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (player)
							players.at(player).setODA(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (rank <= 15)
							topODARanks[rank - 1] = player;

					}

					urlFinish = urlBase + odd;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					//read ODD data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0, rank = 0, player = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');
						rank = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						player = pbinarySearch(atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()), 0, players.size(), players);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (player)
							players.at(player).setODD(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (rank <= 15)
							topODDRanks[rank - 1] = player;

					}

					urlFinish = urlBase + ods;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					//read ODS data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0, rank = 0, player = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');
						rank = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						player = pbinarySearch(atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()), 0, players.size(), players);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (player)
							players.at(player).setODS(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (rank <= 15)
							topODSRanks[rank - 1] = player;

					}

					urlFinish = urlBase + odaT;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					//read Tribe ODA data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0, rank = 0, tribe = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');
						rank = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribe = tbinarySearch(atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()), 0, tribes.size(), tribes);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (tribe)
							tribes.at(tribe).setODA(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (rank <= 15)
							topODATRanks[rank - 1] = tribe;

					}

					urlFinish = urlBase + oddT;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					//Read Tribe ODD Data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;
						unsigned int comFstPos = 0, comSecPos = 0, rank = 0, tribe = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');
						rank = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						tribe = tbinarySearch(atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()), 0, tribes.size(), tribes);

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (tribe)
							tribes.at(tribe).setODA(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

						if (rank <= 15)
							topODDTRanks[rank - 1] = tribe;

					}

					urlFinish = urlBase + conquer;
					url = urlFinish.c_str();

					handle = url_fopen(url, "r");
					if (!handle) {

						system("PAUSE");
						return EXIT_FAILURE;

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					std::time_t currTime = time(nullptr);
					std::time_t passTime = time(nullptr) - 86400;//604800 seconds = 7 days

					//read conquer data
					for (unsigned int count = 0; !url_feof(handle); count++) {

						std::string bufferString;

						unsigned int comFstPos = 0, comSecPos = 0, vill = 0, play = 0;

						if (url_fgets(buffer, sizeof(buffer), handle) == NULL)
							return EXIT_FAILURE;

						bufferString = buffer;

						comSecPos = bufferString.find(',');

						comFstPos = comSecPos + 1;
						comSecPos = bufferString.find(',', comFstPos);

						if (atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str()) >= passTime) {

							vill = vbinarySearch(atoi(bufferString.substr(0, comFstPos).c_str()), 0, allVills.size(), allVills);

							comFstPos = comSecPos + 1;
							comSecPos = bufferString.find(',', comFstPos);

							play = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

							if (vill) {

								unsigned int playerTribeID = players.at(pbinarySearch(play, 0, players.size(), players)).getTribeID();

								players.at(pbinarySearch(play, 0, players.size(), players)).setConq(allVills.at(vill).getPoints(), allVills.at(vill).getX(), allVills.at(vill).getY());

								if (playerTribeID != 0)
									tribes.at(playerTribeID).setConq(allVills.at(vill).getPoints(), allVills.at(vill).getX(), allVills.at(vill).getY());

								comFstPos = comSecPos + 1;
								comSecPos = bufferString.find(',', comFstPos);

								play = atoi(bufferString.substr(comFstPos, comSecPos - comFstPos).c_str());

								if (play) {

									players.at(pbinarySearch(play, 0, players.size(), players)).setLoss(allVills.at(vill).getPoints(), allVills.at(vill).getX(), allVills.at(vill).getY());

									playerTribeID = players.at(pbinarySearch(play, 0, players.size(), players)).getTribeID();

									if (playerTribeID != 0)
										tribes.at(playerTribeID).setLoss(allVills.at(vill).getPoints(), allVills.at(vill).getX(), allVills.at(vill).getY());

								}

							}

						}

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					for (unsigned int count = 0; count < players.size(); count++) {

						for (unsigned int counter = 0; counter < 15; counter++) {

							if (players.at(count).getConqPoints() > players.at(topPlayerConqRanks[counter]).getConqPoints()) {

								for (unsigned int counting = 14; counting > counter; counting--) {

									topPlayerConqRanks[counting] = topPlayerConqRanks[counting - 1];

								}

								topPlayerConqRanks[counter] = count;
								break;

							}

						}

					}

					for (unsigned int count = 0; count < players.size(); count++) {

						for (unsigned int counter = 0; counter < 15; counter++) {

							if (players.at(count).getLossPoints() > players.at(topPlayerLossRanks[counter]).getLossPoints()) {

								for (unsigned int counting = 14; counting > counter; counting--) {

									topPlayerLossRanks[counting] = topPlayerLossRanks[counting - 1];

								}

								topPlayerLossRanks[counter] = count;
								break;

							}

						}

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					for (unsigned int count = 0; count < tribes.size(); count++) {

						for (unsigned int counter = 0; counter < 15; counter++) {

							if (tribes.at(count).getConqPoints() > tribes.at(topTribeConqRanks[counter]).getConqPoints()) {

								for (unsigned int counting = 14; counting > counter; counting--) {

									topTribeConqRanks[counting] = topTribeConqRanks[counting - 1];

								}

								topTribeConqRanks[counter] = count;
								break;

							}

						}

					}

					for (unsigned int count = 0; count < tribes.size(); count++) {

						for (unsigned int counter = 0; counter < 15; counter++) {

							if (tribes.at(count).getLossPoints() > tribes.at(topTribeLossRanks[counter]).getLossPoints()) {

								for (unsigned int counting = 14; counting > counter; counting--) {

									topTribeLossRanks[counting] = topTribeLossRanks[counting - 1];

								}

								topTribeLossRanks[counter] = count;
								break;

							}

						}

					}

					/*
					***************************************************************************************************
					***************************************************************************************************
					*/

					std::vector<std::thread> threads;

					threads.push_back(std::thread(topTribes, world, colors, zoom, tribes, players, topTribeRanks));
					threads.push_back(std::thread(topODATribe, world, colors, zoom, tribes, players, topODATRanks));
					threads.push_back(std::thread(topODDTribe, world, colors, zoom, tribes, players, topODDTRanks));

					for (auto& th : threads)
						th.join();

					threads.clear();

					threads.push_back(std::thread(topPlayers, world, colors, zoom, players, topPlayerRanks));
					threads.push_back(std::thread(topODAPlay, world, colors, zoom, players, topODARanks));
					threads.push_back(std::thread(topODDPlay, world, colors, zoom, players, topODDRanks));
					threads.push_back(std::thread(topODSPlay, world, colors, zoom, players, topODSRanks));

					for (auto& th : threads)
						th.join();

					threads.clear();

					threads.push_back(std::thread(topConqTribes, world, colors, zoom, tribes, players, topTribeRanks, topTribeConqRanks));
					threads.push_back(std::thread(topLossTribes, world, colors, zoom, tribes, players, topTribeRanks, topTribeLossRanks));

					threads.push_back(std::thread(topConqPlayers, world, colors, zoom, players, topPlayerRanks, topPlayerConqRanks));
					threads.push_back(std::thread(topLossPlayers, world, colors, zoom, players, topPlayerRanks, topPlayerLossRanks));

					for (auto& th : threads)
						th.join();

					threads.clear();

				}

			}

			ServerCount++;

			worldFile.close();

		}

	}

	curl_easy_cleanup(cURL);

	system("PAUSE");
	return EXIT_SUCCESS;

}
Beispiel #27
0
void janus_turnrest_init(void) {
    /* Initialize libcurl, needed for contacting the TURN REST API backend */
    curl_global_init(CURL_GLOBAL_ALL);
    janus_mutex_init(&api_mutex);
}
Beispiel #28
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;
}
Beispiel #29
0
void QBox_Global_Init(long flags)
{
	curl_global_init(CURL_GLOBAL_ALL);
}
Beispiel #30
0
int main(int argc, char **argv) {

	if (argc != 4) {
		usage();
	}

	url = argv[1];
	char *username = argv[2];
	char *password = argv[3];

	xmlInitParser();
	xmlKeepBlanksDefault(0);
	xen_init();
	curl_global_init(CURL_GLOBAL_ALL);

#define CLEANUP                                 \
    do {                                        \
        xen_session_logout(session);            \
        curl_global_cleanup();                  \
        xen_fini();                             \
        xmlCleanupParser();                     \
    } while(0)                                  \


	xen_session *session = xen_session_login_with_password(call_func, NULL,
			username, password, xen_api_latest_version);

	/* ---------------------------------------------------------------------
	 Read host, capabilities and API vsn
	 --------------------------------------------------------------------- */
	testConsoles(session);
	testCrashdumps(session);
	testHosts(session);
	testHostCpus(session);
	testHostCrashdumps(session);
	testHostMetricss(session);
	testHostPatchs(session);
	testNetworks(session);
	testPBDs(session);
	testPIFs(session);
	testPIFMetricss(session);
	testPools(session);
	testSMs(session);
	testSRs(session);
	testTasks(session);
	testVBDs(session);
	testVBDMetricss(session);
	testVDIs(session);
	testVIFs(session);
	testVIFMetricss(session);
	testVMs(session);
	testVMGuestMetricss(session);
	testVMMetricss(session);

	if (session->api_version == xen_api_version_1_1) {
		printf(
				"Rio connection detected; skipping getting records on Bonds, Patches, and VLANs\n\n");
	} else {
		testBonds(session);
		testPoolPatchs(session);
		testVLANs(session);
	}

	printf("\n\n");

	CLEANUP;

	return 0;
}