bool Client::SaveToDB() { typedef Poco::Tuple<string, string, string, string, int32_t, string, int32_t, string, string, int32_t, int16_t, int32_t, double, double, double, bool, int8_t, string, int64_t> ClientSave; ClientSave savedata(DBBuffs(), DBResearch(), DBItems(), DBMisc(), m_status, m_ipaddress, m_sex, m_flag, m_faceurl, m_allianceid, m_alliancerank, m_cents, m_prestige, m_honor, m_lastlogin, m_changedface, m_icon, m_allianceapply, m_allianceapplytime); try { Session ses(m_main->serverpool->get()); ses << "UPDATE `accounts` SET buffs=?,`research`=?,items=?,misc=?,`status`=?,ipaddress=?,sex=?,flag=?,faceurl=?,allianceid=?,alliancerank=?,cents=?,prestige=?,honor=?,lastlogin=?,changedface=?,icon=?,allianceapply=?,allianceapplytime=? WHERE accountid=?;", use(savedata), use(m_accountid), now; return true; } catch (Poco::Data::MySQL::ConnectionException& e)\ { m_main->consoleLogger->error(Poco::format("ConnectionException: %s", e.displayText())); } catch (Poco::Data::MySQL::StatementException& e) { m_main->consoleLogger->error(Poco::format("StatementException: %s", e.displayText())); } catch (Poco::Data::MySQL::MySQLException& e) { m_main->consoleLogger->error(Poco::format("MySQLException: %s", e.displayText())); } catch (Poco::InvalidArgumentException& e) { m_main->consoleLogger->error(Poco::format("InvalidArgumentException: %s", e.displayText())); } return false; }
bool PlayerCity::SaveToDB() { typedef Poco::Tuple<string, int8_t, bool, string, int32_t, string, string, string, string, string, string, bool, bool, double, double, double, double, double> CitySave; CitySave savedata(DBMisc(), m_status, m_allowalliance, m_logurl, m_tileid, DBTransingtrades(), DBTroops(), m_cityname, DBBuildings(), DBFortifications(), DBTrades(), m_gooutforbattle, m_hasenemy, m_resources.gold, m_resources.food, m_resources.wood, m_resources.iron, m_resources.stone); try { Session ses(m_client->m_main->serverpool->get()); ses << "UPDATE `cities` SET misc=?,status=?,allowalliance=?,logurl=?,fieldid=?,transingtrades=?,troop=?,name=?,buildings=?,fortification=?,trades=?,gooutforbattle=?,hasenemy=?,gold=?,food=?,wood=?,iron=?,stone=? WHERE id=?;", use(savedata), use(this->m_castleinternalid), now; return true; } catch (Poco::Data::MySQL::ConnectionException& e)\ { m_client->m_main->consoleLogger->error(Poco::format("ConnectionException: %s", e.displayText())); } catch (Poco::Data::MySQL::StatementException& e) { m_client->m_main->consoleLogger->error(Poco::format("StatementException: %s", e.displayText())); } catch (Poco::Data::MySQL::MySQLException& e) { m_client->m_main->consoleLogger->error(Poco::format("MySQLException: %s", e.displayText())); } catch (Poco::InvalidArgumentException& e) { m_client->m_main->consoleLogger->error(Poco::format("InvalidArgumentException: %s", e.displayText())); } return false; }
TestResults* myersDiffbyLineNoWhite ( const std::string & student_file, const std::string & expected_file) { vectorOfWords text_a = stringToWords( student_file ); vectorOfWords text_b = stringToWords( expected_file ); Difference* diff = ses( &text_a, &text_b, false ); diff->type = ByLineByWord; return diff; }
TestResults* myersDiffbyLinebyChar ( const std::string & student_file, const std::string & expected_file) { vectorOfLines text_a = stringToLines( student_file ); vectorOfLines text_b = stringToLines( expected_file ); Difference* diff = ses( &text_a, &text_b, true ); diff->type = ByLineByChar; return diff; }
TestResults* myersDiffbyLinebyCharExtraStudentOutputOk ( const std::string & student_file, const std::string & expected_file) { #if 0 //from nowhite vectorOfWords text_a = stringToWords( student_file ); vectorOfWords text_b = stringToWords( expected_file ); Difference* diff = ses( &text_a, &text_b, true, extraStudentOutputOk ); diff->type = ByLineByWord; return diff; #else std::cout << "MYERS DIFF EXTRA STUDENT OUTPUT" << std::endl; vectorOfLines text_a = stringToLines( student_file ); vectorOfLines text_b = stringToLines( expected_file ); bool extraStudentOutputOk = true; Difference* diff = ses( &text_a, &text_b, true, extraStudentOutputOk ); diff->type = ByLineByChar; std::cout << "end of MYERS DIFF EXTRA STUDENT OUTPUT" << std::endl; return diff; #endif }
session::pointer factory_impl::create_session(std::string const & username , std::string const & password , std::string const & address) { session::pointer ses( new generic_session(id_counter_++ , target::pointer(new target(username, password, address))) ); sessions_.insert(ses->id(), ses); logger::info() << name() << " Session with id = " << ses->id() << " created"; return ses; }
void HttpProtocolData::makeSession(HttpTask *task, size_t begin, size_t len) { LOG(0, "make task %p session from %lu, len %lu\n", task->info, begin, len); char logBuffer[64] = {0}; snprintf(logBuffer, 63, "make new session from %lu, len %lu", begin, len); task->info->taskLog(task->info, logBuffer); std::auto_ptr<HttpSession> ses( new HttpSession(task) ); ses->pos = begin; size_t end = begin + len; if (task->info->totalSize < end) end = task->info->totalSize; ses->length = end - begin; ses->handle = curl_easy_init(); if (ses->handle == NULL) throw DOWNLOADEXCEPTION(CURL_BAD_ALLOC, "CURL", strerror(CURL_BAD_ALLOC)); CURLcode rete = curl_easy_setopt(ses->handle, CURLOPT_URL, task->info->uri.c_str()); rete = curl_easy_setopt(ses->handle, CURLOPT_WRITEFUNCTION, writeCallback); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_WRITEDATA, ses.get()); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_PRIVATE, ses.get()); CHECK_CURLE(rete); char range[128] = {0}; sprintf(range, "%lu-%lu", begin, end - 1); rete = curl_easy_setopt(ses->handle, CURLOPT_RANGE, range); CHECK_CURLE(rete); CURLMcode retm = curl_multi_add_handle(this->handle, ses->handle); if (retm != CURLM_OK) { throw DOWNLOADEXCEPTION(retm, "CURL", curl_multi_strerror(retm)); } ++task->info->validSource; ++task->info->totalSource; ++running; // TODO: maybe need short sessions by pos. task->sessions.push_back(ses.get()); ses.release(); }
void HttpProtocol::addTask(TaskInfo *info) { LOG(0, "enter addTask, info = %p\n", info); if (info == NULL) throw DOWNLOADEXCEPTION(NULL_INFO, "HTTP", strerror(NULL_INFO)); Tasks::iterator it = d->tasks.find(info); if (it != d->tasks.end()) { LOG(0, "task %p has exist\n", info); throw DOWNLOADEXCEPTION(TASK_EXIST, "HTTP", strerror(TASK_EXIST)); } std::auto_ptr<HttpTask> task( new HttpTask(d.get()) ); task->state = HT_PREPARE; task->info = info; info->protocol = this; info->downloadSize = 0; info->totalSource = info->validSource = 0; std::auto_ptr<HttpSession> ses( new HttpSession(task.get()) ); ses->handle = curl_easy_init(); if (ses->handle == NULL) throw DOWNLOADEXCEPTION(CURL_BAD_ALLOC, "CURL", strerror(CURL_BAD_ALLOC)); CURLcode rete = curl_easy_setopt(ses->handle, CURLOPT_URL, task->info->uri.c_str()); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_FILETIME, 1); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_WRITEFUNCTION, writeCallback); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_WRITEDATA, ses.get()); CHECK_CURLE(rete); rete = curl_easy_setopt(ses->handle, CURLOPT_PRIVATE, ses.get()); CHECK_CURLE(rete); if (info->processData.length() != 0) { info->taskLog(task->info, "Resume task, initialize"); d->loadTask(task.get(), info->processData); if (task->info->totalSize > 0) { unsigned int begin = info->downloadMap.find(false, 0) * task->info->downloadMap.bytesPerBit(); unsigned int end = info->downloadMap.find(true, begin) * task->info->downloadMap.bytesPerBit(); ses->pos = begin; ses->length = end - begin; char range[64]; sprintf(range, "%u-%u", begin, end); LOG(0, "resume task at %s\n", range); rete = curl_easy_setopt(ses->handle, CURLOPT_RANGE, range); CHECK_CURLE(rete); } } else { info->taskLog(task->info, "Add new task, initialize"); } if (info->options.length() > 0) { d->loadTask(task.get(), info->options); } if (task->conf.referer.length() > 0) { rete = curl_easy_setopt(ses->handle, CURLOPT_REFERER, task->conf.referer.c_str()); CHECK_CURLE(rete); } if (task->conf.userAgent.length() > 0) { rete = curl_easy_setopt(ses->handle, CURLOPT_USERAGENT, task->conf.userAgent.c_str()); CHECK_CURLE(rete); } CURLMcode retm = curl_multi_add_handle(d->handle, ses->handle); if (retm != CURLM_OK) { throw DOWNLOADEXCEPTION(retm, "CURL", curl_multi_strerror(retm)); } ++d->running; d->tasks.insert(Tasks::value_type(info, task.get())); task->sessions.push_back(ses.get()); ses.release(); task.release(); }
int main(int argc, char const* argv[]) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " <magnet-url>" << std::endl; return 1; } lt::settings_pack pack; pack.set_int(lt::settings_pack::alert_mask , lt::alert::error_notification | lt::alert::storage_notification | lt::alert::status_notification); lt::session ses(pack); clk::time_point last_save_resume = clk::now(); // load resume data from disk and pass it in as we add the magnet link std::ifstream ifs(".resume_file", std::ios_base::binary); ifs.unsetf(std::ios_base::skipws); std::vector<char> buf{std::istream_iterator<char>(ifs) , std::istream_iterator<char>()}; lt::error_code ec; lt::add_torrent_params atp = lt::read_resume_data(&buf[0], int(buf.size()), ec); atp.url = argv[1]; atp.save_path = "."; // save in current dir ses.async_add_torrent(atp); // this is the handle we'll set once we get the notification of it being // added lt::torrent_handle h; for (;;) { std::vector<lt::alert*> alerts; ses.pop_alerts(&alerts); for (lt::alert const* a : alerts) { if (auto at = lt::alert_cast<lt::add_torrent_alert>(a)) { h = at->handle; } // if we receive the finished alert or an error, we're done if (lt::alert_cast<lt::torrent_finished_alert>(a)) { h.save_resume_data(); goto done; } if (lt::alert_cast<lt::torrent_error_alert>(a)) { std::cout << a->message() << std::endl; goto done; } // when resume data is ready, save it if (auto rd = lt::alert_cast<lt::save_resume_data_alert>(a)) { std::ofstream of(".resume_file", std::ios_base::binary); of.unsetf(std::ios_base::skipws); lt::bencode(std::ostream_iterator<char>(of) , *rd->resume_data); } if (auto st = lt::alert_cast<lt::state_update_alert>(a)) { if (st->status.empty()) continue; // we only have a single torrent, so we know which one // the status is for lt::torrent_status const& s = st->status[0]; std::cout << "\r" << state(s.state) << " " << (s.download_payload_rate / 1000) << " kB/s " << (s.total_done / 1000) << " kB (" << (s.progress_ppm / 10000) << "%) downloaded\x1b[K"; std::cout.flush(); } } std::this_thread::sleep_for(std::chrono::milliseconds(200)); // ask the session to post a state_update_alert, to update our // state output for the torrent ses.post_torrent_updates(); // save resume data once every 30 seconds if (clk::now() - last_save_resume > std::chrono::seconds(30)) { h.save_resume_data(); } } // TODO: ideally we should save resume data here done: std::cout << "\ndone, shutting down" << std::endl; }
void plogin::process() { obj2["data"] = amf3object(); amf3object & data2 = obj2["data"]; //errors: //-5 = captcha //-99 = general error //-100 = holiday string username = data["user"]; string password = data["pwd"]; if (gserver->maxplayers <= gserver->currentplayersonline + 1) { gserver->SendObject(req.conn, gserver->CreateError("server.LoginResponse", -99, "Servers are currently overloaded. Please try again later.")); return; } string newuser; string newpass; newuser = makesafe(username); newpass = makesafe(password); { Session ses(gserver->accountpool->get()); Statement select(ses); select << "SELECT COUNT(*) AS a FROM `account` WHERE `email`=?;", use(newuser); select.execute(); RecordSet rs(select); if (rs.value("a").convert<int32_t>() == 0) { //account does not exist - insert new row try { Statement insert(ses); insert << "INSERT INTO `account` (`name`, `email`, `ip`, `lastlogin`, `creation`, `password`, `status`, `reason`) VALUES ('null', ?, '', ?, ?, ?, 0, '');", use(newuser), use(unixtime()), use(unixtime()), use(newpass), now; } catch (Poco::Data::MySQL::StatementException * e) { gserver->consoleLogger->error(Poco::format("Account Create Exception: %s", e->displayText())); return; } } } { Session ses(gserver->accountpool->get()); Statement select(ses); select << "SELECT * FROM `account` WHERE `email`=? AND `password`=?;", use(newuser), use(newpass); select.execute(); RecordSet rs(select); if (rs.rowCount() == 0) { //account doesn't exist or password is wrong gserver->SendObject(req.conn, gserver->CreateError("server.LoginResponse", -2, "Incorrect account or password.")); return; } else { int32_t masteraccountid = rs.value("id").convert<int32_t>(); client = gserver->GetClientByParent(masteraccountid); bool banned = false; { //are they banned? if so, globally or for this server? Session ses2(gserver->serverpool->get()); Statement select2(ses2); select2 << "SELECT * FROM `accounts` WHERE `parentid`=?;", use(masteraccountid); select2.execute(); RecordSet rs2(select2); if (rs.value("status").convert<int32_t>() == -99) banned = true; if (rs2.rowCount() > 0 && rs2.value("status").convert<int32_t>() == -99) banned = true; if (banned) { string errormsg = "You are banned. Reason: "; errormsg += rs.value("reason").convert<string>().length() > 0 ? rs.value("reason").convert<string>() : rs2.value("reason").convert<string>(); gserver->SendObject(req.conn, gserver->CreateError("server.LoginResponse", -99, errormsg)); return; } } //client = gserver->GetClientByParent(parentid); if (client == 0) { client = gserver->NewClient(); client->masteraccountid = masteraccountid; client->m_socknum = req.conn->uid; client->socket = req.conn; req.conn->client_ = client; client->m_connected = true; } else { if (client->m_connected) { //player already logged on gserver->CloseClient(client, 3, "");//multiple people logging into the same account } //Login is valid client->m_connected = true; double logintime = unixtime(); if (logintime - client->m_lastlogin < 1000 * 5) { gserver->SendObject(req.conn, gserver->CreateError("server.LoginResponse", 6, "You have tried logging in too frequently. Please try again later.")); req.conn->stop(); return; } client->m_lastlogin = logintime; if (client->socket) gserver->CloseClient(client, 3, ""); client->socket = req.conn; client->m_socknum = req.conn->uid; client->m_ipaddress = req.conn->address; req.conn->client_ = client; gserver->consoleLogger->information(Poco::format("Already established client found # %?d", (uint32_t)client->m_clientnumber)); if (client->m_email == "Daisy") { client->m_bdenyotherplayer = true; client->m_icon = 7; } } if (client == 0) { //error creating client object gserver->consoleLogger->information(Poco::format("Error creating client object @ %s:%?d", (string)__FILE__, __LINE__)); gserver->SendObject(client, gserver->CreateError("server.LoginResponse", -99, "Error with connecting. Please contact support.")); return; } //account exists Session ses2(gserver->serverpool->get()); Statement select2(ses2); select2 << "SELECT * FROM `accounts` WHERE `parentid`=?;", use(masteraccountid); select2.execute(); RecordSet rs2(select2); if (rs2.rowCount() == 0) { //does not have an account on server gserver->SendObject(client, gserver->CreateError("server.LoginResponse", -4, "need create player")); client->m_loggedin = true; return; } else { int accountid = rs2.value("accountid").convert<int32_t>(); client->m_accountid = accountid; //has an account, what about cities? Session ses3(gserver->serverpool->get()); Statement select3(ses3); select3 << "SELECT * FROM `cities` WHERE `accountid`=?;", use(accountid); select3.execute(); RecordSet rs3(select3); if (rs3.rowCount() == 0) { //does not have any cities on server but did have an account - this only happens if you try to "restart" your account. it saves the account info while deleting your cities gserver->SendObject(client, gserver->CreateError("server.LoginResponse", -4, "need create player")); client->m_loggedin = true; return; } else { //has an account and cities. process the list and send account info amf3object obj; obj["cmd"] = "server.LoginResponse"; obj["data"] = amf3object(); amf3object & data = obj["data"]; data["packageId"] = 0.0f; double tslag = unixtime(); if (client->GetItemCount("consume.1.a") < 10000) client->SetItem("consume.1.a", 10000); client->m_cents = 5000; data["player"] = client->ToObject(); //UNLOCK(M_CLIENTLIST); if (client->m_city.size() == 0) { //problem gserver->consoleLogger->error(Poco::format("Error client has no cities @ %s:%?d", (string)__FILE__, __LINE__)); gserver->SendObject(client, gserver->CreateError("server.LoginResponse", -99, "Error with connecting. Please contact support.")); return; } client->m_currentcityid = ((PlayerCity*)client->m_city.at(0))->m_castleid; client->m_currentcityindex = 0; client->m_accountexists = true; //check for holiday status stBuff * holiday = client->GetBuff("FurloughBuff"); if (holiday && holiday->endtime > tslag) { //is in holiday - send holiday info too string s; { int32_t hours; int32_t mins; int32_t secs = (holiday->endtime - tslag) / 1000; hours = secs / 60 / 60; mins = secs / 60 - hours * 60; secs = secs - mins * 60 - hours * 60 * 60; std::stringstream ss; ss << hours << "," << mins << "," << secs; s = ss.str(); } data["ok"] = -100; data["msg"] = s; data["errorMsg"] = s; } else { data["ok"] = 1; data["msg"] = "success"; } gserver->SendObject(client, obj); //SendObject(*req.connection, obj); client->m_lag = unixtime() - tslag; client->m_loggedin = true; gserver->currentplayersonline++; client->SaveToDB(); return; } } } } return; }