// Recursive Function void _ftpEntry::removeFolderChildren( size_t folderID ) { Connection *sqlConnect = dbConnect(); bool isDone = false; Query serverQuery = sqlConnect->query(); StoreQueryResult serverResults; StoreQueryResult::iterator storeQueryIT; size_t ID; // Find all folders that parent us serverQuery << "select * from ServerFolders where parentID = " << quote << folderID; serverQuery.execute(); // for(storeQueryIT = serverResults.begin(); storeQueryIT != serverResults.end(); storeQueryIT++ ) { // Remove all children from this parent ID = (size_t) (*storeQueryIT)["folderID"]; removeFolderChildren( ID ); // Now remove the parent serverQuery.str(""); serverQuery << "delete from ServerFolders where folderID = " << quote << ID; serverQuery.execute(); } delete sqlConnect; }
// Find users with <ip> vector<size_t> ipFind( database *database, string IP_ ) { socketTCP socket("0.0.0.0"); string domain, ip, ipTmp; vector<size_t> members; size_t pos; // Resolve domain/ip ip = socket.hostnameLookup( IP_ ); domain = socket.ipLookup( IP_ ); if(!ip.size()) { // Remove after * size_t pos = IP_.find("*"); if(pos != string::npos) { IP_ = IP_.substr(0, pos); } ip = IP_; } // Get a list of similar ips StoreQueryResult IPs = database->ipFind( ip ); StoreQueryResult::iterator ipIT; Row IPRow; if( !IPs.size() ) IPs = database->ipFind( domain ); if(IPs.size() ) { // Add each matching member to the vector for( ipIT = IPs.begin(); ipIT != IPs.end(); ipIT++ ) { IPRow = *ipIT; members.push_back( (size_t) IPRow["memberID"] ); } return members; } // Now get all IPs, resolve them all and try and match IPs = database->ipsRead(0); for( ipIT = IPs.begin(); ipIT != IPs.end(); ipIT++ ) { IPRow = *ipIT; ipTmp = (string) IPRow["ip"]; if( (pos = ipTmp.find("*")) != string::npos) { ipTmp = ipTmp.substr(0, pos-1); if( ip.find( ipTmp) != string::npos ) members.push_back( (size_t) IPRow["memberID"] ); } ipTmp = socket.hostnameLookup( ipTmp ); if( ip == ipTmp ) members.push_back( (size_t) IPRow["memberID"] ); } return members; }
int run() { c.connect("crowdify", "localhost", "root", "root"); create_test_data(); stringstream qs; qs.clear(); qs.str(string()); qs << "SELECT * FROM clients;"; Query q = c.query(qs.str()); StoreQueryResult r = q.store(); StoreQueryResult::iterator it; struct sockaddr_in sin; char *username, *password; for (it = r.begin(); it != r.end(); it++) { Row r = *it; run_client(r[0]); } print_query("select * from blocks;"); print_query("select * from files;"); print_query("select * from clients;"); print_query("select * from filestoblocks;"); print_query("select * from directoriestofiles;"); print_query("select * from clientstodirectories;"); return 0; }
bool ipValidate( database *database, string IP, size_t memberID ) { socketTCP socket("0.0.0.0"); string domain; // Resolve domain/ip IP = socket.hostnameLookup(IP); // Current Connect Client IP domain = socket.ipLookup( IP ); // Resolve the clients IP // Get any IP/Host matches for this member's ID / Connected IP/Domain StoreQueryResult IPs = database->ipsRead( memberID, IP ); StoreQueryResult Domains = database->ipsRead( memberID, domain ); // Did we find any? if(!IPs.empty()) return true; if(!Domains.empty()) return true; if(!IP.size()) return false; // Nope, so we need to get all IPs/Domains for this user from the database // Remove all wildcards and check the domain for matches Domains = database->ipsRead( memberID ); StoreQueryResult::iterator addressIT; string testName; string resolvedIP; string::iterator sIT; Row row; for( addressIT = Domains.begin(); addressIT != Domains.end(); addressIT++ ) { row = *addressIT; // Get an address to test testName = (string) row["ip"]; // Resolve the name from the database, and try it against the connected IP resolvedIP = socket.hostnameLookup( testName ); if( ! IP.compare( resolvedIP ) ) return true; // Remove wildcards sIT = remove( testName.begin(), testName.end(), '*' ); if(sIT != testName.end()) testName.erase(sIT); // Check against the connected IP if( IP.find( testName ) != string::npos ) return true; // Check against the connected domain name if( domain.find( testName ) != string::npos ) return true; } return false; }
void IRCBot::actionMIA( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { size_t count = 1; size_t lastOnline; bool active, showAll = false; if( pParameters == "all" ) showAll = true; StoreQueryResult members = _db->membersReadSeen( true ); StoreQueryResult::iterator memberIT; Row member; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { stringstream irc; member = *memberIT; active = (bool) member["active"]; if( !showAll && !active ) continue; if( _smokingman->thepipeGet()->userOnline( ((size_t) member["memberID"] ) ) != userOFFLINE ) continue; lastOnline = (size_t) member["lastOnline"]; irc << count << ". " << ((string) member["nameUser"]) << " : " << timeCalc( time(0) - lastOnline ); speak( "LastOn", irc, pChannel ); ++count; } }
/** @brief Return the list of all orders of a given user @param[in] pp An instance of User @return A vector of Order */ vector<Order *> & Order::ordersForUser(User & pp) { vector<Order *> *orders = new vector<Order *>; // get an instance of the database Database& db = Database::instance(); try { // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(); q << "SELECT * FROM orders WHERE uid = " << pp.uniqueID() << " ORDER BY oid, date"; StoreQueryResult res = q.store(); if (!res.empty()) { orders->reserve(res.num_rows()); StoreQueryResult::const_iterator it; for (it = res.begin(); it != res.end(); it++){ Row row = *it; orders->push_back(new Order(row)); } } } catch (std::exception &e) { cerr << "an error occurred: " << e.what() << endl; } return *orders; }
/** @brief Returns the list of products (and requested quantity) of an order @return A std::map where the key is product ID and the value the quantity */ map<int, int>& Order::products() { map<int, int> *prd = NULL; // get an instance of the database Database& db = Database::instance(); try { // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(); q << "SELECT * FROM order_details WHERE oid = " << valueForKey(KEY_ORD_OID); StoreQueryResult res = q.store(); if (!res.empty()) { prd = new map<int, int>; StoreQueryResult::const_iterator it; for (it = res.begin(); it != res.end(); it++){ Row row = *it; int key = atoi(row["pid"]); int qty = atoi(row["qty"]); (*prd)[key] = qty; } } } catch (std::exception &e) { cerr << "an error occurred: " << e.what() << endl; } return *prd; }
void _ftpEntry::checkDBFolders() { bool isDone = false; Query serverQuery = _sqlConnection->query(); StoreQueryResult serverResults; StoreQueryResult::iterator storeQueryIT; vector<_ftpEntry*>::iterator entryIT; // Nothing to do here... if( directorys.empty() ) return; // Get a list of all the directorys that we parent serverQuery << "select * from ServerFolders where serverID = " << quote << _serverID; serverQuery << " AND parentID = " << quote << _folderID; // Do the query serverResults = serverQuery.store(); // None? if( !serverResults.size() ) return; // We now have to check each DB result, against the results in directorys vector for(storeQueryIT = serverResults.begin(); storeQueryIT != serverResults.end(); storeQueryIT++ , isDone = false) { for( entryIT = directorys.begin(); entryIT != directorys.end(); entryIT++) { // Does this directory still exist? if((*entryIT)->getName() == (string) (*storeQueryIT)["name"]) { isDone = true; // Yes it exists break; } // parentID check } // entryIT // Deleted? if(!isDone) { // Yes, remove the entry from the DB removeFolderChildren( (size_t) (*storeQueryIT)["folderID"] ); serverQuery.str(""); serverQuery << "delete from ServerFolders where folderID = " << quote << (*storeQueryIT)["folderID"]; // bye bye :) serverQuery.execute(); } // !isDone } // storeQueryIT } // checkDBFolders
bool IRCBot::testPrepare() { StoreQueryResult ircBots = _db->ircBotReadAll(); StoreQueryResult::iterator ircIT; stringstream ircs; size_t sleepTime = 500, count = 0; Row irc, ircBot; _ircMii *botMii; if(ircBots.empty()) return false; // loop through and start each server test for( ircIT = ircBots.begin(); ircIT != ircBots.end(); ++ircIT, ++count ) { ircBot = *ircIT; irc = _db->ircRead( (size_t) ircBot["ircID"] ); if(irc.empty()) return false; botMii = _Miis->ircMiiLoad( (string) irc["nick"] ); if(botMii) { botMii->ircBotRowLoad(); botMii->silentSet(); botTestAdd( botMii, 0 ); } else { stringstream ircs; ircs << "Bot " << ( (string) irc["nick"] ) << " is not online."; speak("Test", ircs, _testChannel); } Sleep(sleepTime); // Every 4, sleep triple time if(count == 4) { Sleep(sleepTime*2); count=0; } } // Nothing to do? if(_testMiis.empty()) { stringstream ircs; ircs << "No bots to test."; speak("Test", ircs, _testChannel); return false; } return true; }
int print_query(const char *q) { Query q2 = c.query(q); StoreQueryResult r = q2.store(); StoreQueryResult::iterator it; for (it = r.begin(); it != r.end(); it++) { Row r = *it; cout << " " << r[0] << endl; } cout << endl; return 0; }
void IRCBot::actionTotalTime( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { size_t count = 1; time_t timeOnline; bool active, showAll = false; if( pParameters == "all" ) showAll = true; StoreQueryResult members = _db->memberTimeOnGet( false ); StoreQueryResult::iterator memberIT; Row member; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { member = *memberIT; active = (bool) member["active"]; if( !showAll && !active ) continue; timeOnline = (time_t) member["timeOnline"]; /* if( _smokingman->thepipeGet()->userOnline( ((size_t) member["memberID"] ) ) != userOFFLINE ) { client *user = _smokingman->thepipeGet()->userClient(((size_t) member["memberID"] ) ); time_t addTime = time(0) - user->connectedTimeGet(); timeOnline += addTime; }*/ if(timeOnline > 0) { stringstream irc; irc << count << ". " << ((string) member["nameUser"]) << " : " << timeCalc( timeOnline ); speak( "TotalTime", irc, pChannel ); ++count; } } }
static vector<Item> handle_get_inventory(const StoreQueryResult& result) { typedef mysqlpp::StoreQueryResult::const_iterator ResultIt; vector<Item> items(16); for(ResultIt i = result.begin(), end = result.end(); i != end; ++i) { const Row& row = *i; Item item; item.cid = row["id"]; item.itemid = row["itemid"]; if(row["rental"]) { // TODO(Jacob): Handle item.RentHour } items.push_back(item); } return items; }
void IRCBot::actionOnline( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { vector<size_t> doneMembers; vector<time_t> times; vector<time_t>::iterator timesIT; stringstream irc; StoreQueryResult members = _db->membersRead(0); StoreQueryResult::iterator memberIT; Row member; time_t timeOnline; client *userClient = 0; size_t memberID = 0; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { member = *memberIT; memberID = (size_t) member["memberID"]; // Get the client userClient = _smokingman->thepipeGet()->userClient( memberID ); if(!userClient) continue; // Calc the time online timeOnline = userClient->connectedTimeGet(); times.push_back( timeOnline ); userClient = 0; } // Sort the times sort( times.begin(), times.end() ); size_t count = 1; // Output the result for(timesIT = times.begin(); timesIT != times.end(); timesIT++ ) { timeOnline = *timesIT; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { member = *memberIT; memberID = (size_t) member["memberID"]; userClient = _smokingman->thepipeGet()->userClient( memberID ); if(!userClient) continue; if( find( doneMembers.begin(), doneMembers.end(), memberID ) != doneMembers.end() ) continue; if( timeOnline == userClient->connectedTimeGet() ) { doneMembers.push_back( memberID ); irc << count << ". " << userClient->moduleGet<moduleAuth>(modAUTH)->memberUserNameGet() << " : " << timeCalc( time(0) - timeOnline ); speak( "Online", irc, pChannel ); irc.str(""); ++count; break; } } } }
void IRCBot::actionSearch( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { StoreQueryResult serverResults; StoreQueryResult::iterator resultIT; bool modeFiles = false; stringstream irc; string serverShort; if(readServerName(pParameters.substr(0, pParameters.find(" "))) != 0) serverShort = parameterGet(pParameters); string searchTerm = parameterGet(pParameters); string resultName, next; Row server, search, folder; size_t searchServerID; size_t serverID = readServerName( serverShort ); size_t folderID = 0, count = 0, parentID = 0; searchServerID = serverID; if(!searchTerm.size()) { speak("search", "syntax wrong, usage", pChannel); speak("search", "folder: !search <term>", pChannel); speak("search", "files: !search <term> file", pChannel); speak("search", "serverSpecific: !search <server shortname> <term>", pChannel); return; } while(pParameters.size()) { next = parameterGet(pParameters); if(next[0] == 'f' && pParameters.size() == 0) { modeFiles = true; } else { searchTerm.append(" "); searchTerm.append(next); } } if(modeFiles) { serverResults = _db->searchFiles( searchTerm ); } else serverResults = _db->searchFolders( searchTerm, readServerName(serverShort.c_str()) ); if(!serverResults.size()) { irc << "No results for query '" << searchTerm << "'"; speak("search", irc, pChannel); return; } // Have results to parse for( resultIT = serverResults.begin(); resultIT != serverResults.end(); resultIT++ ) { irc.str(""); search = *resultIT; if(count > 10) break; if(modeFiles) { folderID = (size_t) search["folderID"]; folder = _db->folderRead( folderID ); serverID = (size_t) folder["serverID"]; if(searchServerID && serverID != searchServerID) continue; server = _db->serverRead( serverID ); serverShort = (string) server["nameShort"]; resultName = (string) search["name"]; irc << "[" << serverShort << "]: " << resultName << " in "; parentID = (size_t) folder["parentID"]; } else { serverID = (size_t) search["serverID"]; server = _db->serverRead( serverID ); serverShort = (string) server["nameShort"]; resultName = (string) search["name"]; parentID = (size_t) search["parentID"]; folder = search; irc << "[" << serverShort << "]: " << resultName << " in "; } if(parentID) { search = _db->folderRead( parentID ); if(!search.empty()) if((string) search["name"] != "/") irc << ((string) search["name"]); } if(modeFiles) irc << "/" << ((string) folder["name"]); speak("search", irc, pChannel); count++; } }
int run_client(int cid) { stringstream qs; struct sockaddr_in sin; char *username, *password; StoreQueryResult r; StoreQueryResult::iterator it; try { qs << "SELECT * FROM clients WHERE cid=" << cid << ";"; Query q = c.query(qs.str()); r = q.store(); for (it = r.begin(); it != r.end(); it++) { Row r = *it; cout << " " << r[0] << " " << r[1] << " " << r[2] << " " << r[3] << endl; sin.sin_addr.s_addr = r[1]; username = strdup(r[2]); password = strdup(r[3]); } } catch (const mysqlpp::BadQuery& er) { cerr << "no clients found: " << er.what() << endl; return 1; } libssh2_init(0); int sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { cerr << "failed to connect" << endl; return 1; } ssh_session = libssh2_session_init(); libssh2_session_set_blocking(ssh_session, 1); if (libssh2_session_handshake(ssh_session, sock)) { cerr << "handshake failed" << endl; return 1; } if (libssh2_userauth_password(ssh_session, username, password)) { cerr << "couldn't authenticate user" << endl; return 1; } Query q = c.query("CREATE TABLE IF NOT EXISTS directories (did INT AUTO_INCREMENT PRIMARY KEY NOT NULL, path VARCHAR(4096), uid SMALLINT, gid SMALLINT, perm SMALLINT);"); q.execute(); q = c.query("CREATE TABLE IF NOT EXISTS clientstodirectories (cid INT, did INT);"); q.execute(); try { qs.clear(); qs.str(string()); qs << "SELECT * FROM clientstodirectories WHERE cid=" << cid << ";"; cerr << qs.str() << endl; q = c.query(qs.str()); r = q.store(); for (it = r.begin(); it != r.end(); it++) { Row r = *it; ssh_ftw(r[1]); } } catch (const mysqlpp::BadQuery& er) { cerr << "no clients found: " << er.what() << endl; return 1; } libssh2_session_disconnect(ssh_session, "bye"); libssh2_session_free(ssh_session); libssh2_exit(); return 0; }
int ssh_ftw(int did) { stringstream qs; qs.clear(); qs.str(string()); qs << "SELECT * FROM directories WHERE did=" << did << ";"; Query q = c.query(qs.str()); cerr << qs.str() << endl; StoreQueryResult r; StoreQueryResult::iterator it; r = q.store(); char *dirpath; cerr << "Opening: " << dirpath << endl; for (it = r.begin(); it != r.end(); it++) { Row r = *it; dirpath = strdup(r[1]); } sftp_session = libssh2_sftp_init(ssh_session); if (sftp_session == NULL) { cerr << "couldn't init sftp" << endl; return 1; } LIBSSH2_SFTP_HANDLE *sftp_dir = libssh2_sftp_opendir(sftp_session, dirpath); if (sftp_dir == NULL) { cerr << "couldn't open dir" << endl; return 1; } LIBSSH2_SFTP_ATTRIBUTES sftp_attr; char *name = new char[512]; char *mem = new char[512]; q = c.query("CREATE TABLE IF NOT EXISTS directoriestofiles (did INT, fid INT);"); q.execute(); int rc = 0; while ((rc = libssh2_sftp_readdir_ex(sftp_dir, mem, 512, name, 512, &sftp_attr)) > 0) { cerr << name << ": " << hex << sftp_attr.permissions << endl; if ((sftp_attr.permissions & 0100000L) != 0) { cout << name << endl; Query q = c.query("CREATE TABLE IF NOT EXISTS files (fid INT AUTO_INCREMENT PRIMARY KEY NOT NULL, name VARCHAR(256), ch BIGINT, uid SMALLINT, gid SMALLINT, perm SMALLINT, size BIGINT)"); q.execute(); std::stringstream fs; fs << "INSERT INTO files VALUES(NULL,\"" << mem << "\"," << 1 << "," << (short int) sftp_attr.uid << "," << (short int) sftp_attr.gid << "," << (short int) sftp_attr.permissions << "," << (long int) sftp_attr.filesize << ");"; cerr << "query: " << fs.str() << endl; q = c.query(fs.str()); int fid = q.execute().insert_id(); stringstream qs; qs << "INSERT INTO directoriestofiles VALUES(" << did << "," << fid << ");"; cerr << qs.str() << endl; q.execute(qs.str()); stringstream full_name; full_name << dirpath << "/" << mem; insert_blocks(fid, full_name.str().c_str()); } } libssh2_sftp_closedir(sftp_dir); libssh2_sftp_shutdown(sftp_session); return 0; }
int CViewMng::init(Connection *conn) { CoCycle *cycle = g_cycle; if(conn == NULL) return -1; mDBConn = conn; StoreQueryResult::const_iterator it; Row row ; Query query = mDBConn->query(); query << "select id, ltrim(rtrim(name)), ltrim(rtrim(remark)), " << "interruptable, type from t_view_set"; StoreQueryResult res = query.store(); if(res.empty()) return -2; static char buf[2048]; CodeConverter cc = CodeConverter("utf-8","gb2312"); for (it = res.begin(); it != res.end(); ++it) { row = *it; ViewSet *viewSet = cycle->mPool->newObj<ViewSet>(); assert(viewSet != NULL); viewSet->id = row[0]; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[1].c_str(), row[1].length(), buf, sizeof(buf)); viewSet->name = buf; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[2].c_str(), row[2].length(), buf, sizeof(buf)); viewSet->remark = buf; int interruptable = row[3]; if(interruptable == 0) viewSet->interruptable = true; else viewSet->interruptable = false; viewSet->type = row[4]; insertViewSet(viewSet); } query << "select a.id, ltrim(rtrim(a.name)), ltrim(rtrim(a.content)), " << " ltrim(rtrim(b.name)) from t_view as a " << "left join t_view_set as b on a.view_set_id = b.id"; res = query.store(); if(res.empty()) return -3; for (it = res.begin(); it != res.end(); ++it) { row = *it; View *view = cycle->mPool->newObj<View>(); assert(view != NULL); view->id = row[0]; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[1].c_str(), row[1].length(), buf, sizeof(buf)); view->name = buf; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[2].c_str(), row[2].length(), buf, sizeof(buf)); view->content = buf; insertView(row[3].c_str(), view); } query << "select a.id, ltrim(rtrim(a.name)), ltrim(rtrim(a.title)), " << " ltrim(rtrim(a.action)), a.type, ltrim(rtrim(b.name)) " <<"from t_click_action as a left join t_view_set as b " << "on a.view_set_id = b.id"; res = query.store(); if(res.empty()) return -4; for (it = res.begin(); it != res.end(); ++it) { row = *it; ClickAction *clickAction = cycle->mPool->newObj<ClickAction>(); assert(clickAction != NULL); clickAction->id = row[0]; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[1].c_str(), row[1].length(), buf, sizeof(buf)); clickAction->name = buf; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[2].c_str(), row[2].length(), buf, sizeof(buf)); clickAction->title = buf; memset(buf, 0, sizeof(buf)); cc.convert((char *)row[3].c_str(), row[3].length(), buf, sizeof(buf)); clickAction->action = buf; clickAction->type = row[4]; insertClickAction(row[5].c_str(), clickAction); } return 0; }