void JabberProtocol::ProcessPresence(XMLEntity *entity) { int num_matches = 0; // verify we have a username if (entity->Attribute("from")) { // circumvent groupchat presences string room, server, user; if (entity->Child("x", "xmlns", "http://jabber.org/protocol/muc#user")) { UserID from = UserID(string(entity->Attribute("from"))); room = from.JabberUsername(); server = from.JabberServer(); user = from.JabberResource(); fprintf(stderr, "Group Presence in room %s from user %s.\n", from.JabberHandle().c_str(), user.c_str()); BMessage *msg = new BMessage(JAB_GROUP_CHATTER_ONLINE); msg->AddString("room", (room + '@' + server).c_str()); msg->AddString("server", server.c_str()); msg->AddString("username", user.c_str()); if (!entity->Attribute("type") || !strcasecmp(entity->Attribute("type"), "available")) { if (entity->Child("show") && entity->Child("show")->Data()) { msg->AddString("show", entity->Child("show")->Data()); } else msg->AddString("show", "online"); if (entity->Child("status") && entity->Child("status")->Data()) { msg->AddString("status", entity->Child("status")->Data()); } else msg->AddString("status", ""); if (entity->Child("x")->Child("item") && entity->Child("x")->Child("item")->Attribute("role")) msg->AddString("role", entity->Child("x")->Child("item")->Attribute("role")); else msg->AddString("role", "admin"); if (entity->Child("x")->Child("item") && entity->Child("x")->Child("item")->Attribute("affiliation")) msg->AddString("affiliation", entity->Child("x")->Child("item")->Attribute("affiliation")); else msg->AddString("affiliation", "none"); msg->what = JAB_GROUP_CHATTER_ONLINE; } else if (!strcasecmp(entity->Attribute("type"), "unavailable")) { msg->what = JAB_GROUP_CHATTER_OFFLINE; } TalkManager::Instance()->Lock(); ChatWindow *window = TalkManager::Instance()->FindWindow(from.JabberHandle()); if (window != NULL) { fprintf(stderr, "Process group presence %s.\n", window->GetUserID()->JabberHandle().c_str()); window->PostMessage(msg); } else { fprintf(stderr, "There is no window group presence route to.\n"); } TalkManager::Instance()->Unlock(); return; } JRoster *roster = JRoster::Instance(); roster->Lock(); for (JRoster::ConstRosterIter i = roster->BeginIterator(); i != roster->EndIterator(); ++i) { UserID *user = NULL; if (!strcasecmp(UserID(entity->Attribute("from")).JabberHandle().c_str(), (*i)->JabberHandle().c_str())) { ++num_matches; user = *i; ProcessUserPresence(user, entity); fprintf(stderr, "Process roster presence %s.\n", user->JabberHandle().c_str()); } } if (num_matches == 0) { UserID user(string(entity->Attribute("from"))); fprintf(stderr, "Process not in roster presence %s.\n", user.JabberHandle().c_str()); ProcessUserPresence(&user, entity); } roster->Unlock(); mainWindow->PostMessage(BLAB_UPDATE_ROSTER); } }
nsresult PromptDlg::PromptUsernameAndPassword(HWND hwndParent, const PRUnichar *dialogTitle, const PRUnichar *text, PRUnichar **username, PRUnichar **password, const PRUnichar *checkMsg, PRBool *checkValue, PRBool *_retval) { NS_ENSURE_ARG_POINTER(text); NS_ENSURE_ARG_POINTER(_retval); HINSTANCE hInstResource = _Module.m_hInstResource; USES_CONVERSION; // Duplicate all strings, turning them into TCHARs if (dialogTitle) mTitle = _tcsdup(W2T(dialogTitle)); mMessage = _tcsdup(W2T(text)); if (checkMsg) { NS_ENSURE_ARG_POINTER(checkValue); mCheckMessage = _tcsdup(W2T(checkMsg)); mCheckValue = *checkValue ? TRUE : FALSE; } if (username) { mUsername = _tcsdup(W2T(*username)); } if (password) { mPassword = _tcsdup(W2T(*password)); } mPromptMode = PROMPT_USERPASS; INT result = DialogBoxParam(hInstResource, MAKEINTRESOURCE(IDD_PROMPTUSERPASS), hwndParent, PromptProc, (LPARAM) this); if (result == IDOK) { if (username) { if (*username) nsMemory::Free(*username); nsAutoString user(T2W(mUsername)); *username = ToNewUnicode(user); } if (password) { if (*password) nsMemory::Free(*password); nsAutoString pass(T2W(mPassword)); *password = ToNewUnicode(pass); } if (checkValue) *checkValue = mCheckValue; *_retval = TRUE; } else { *_retval = FALSE; } return NS_OK; }
Address Peer::address() const { return Address(user(), group(), id()); }
void TestPreferences::testPreferences() { auto pref = SettingsObjectWrapper::instance(); pref->load(); auto cloud = pref->cloud_storage; cloud->setBackgroundSync(true); TEST(cloud->backgroundSync(), true); cloud->setBackgroundSync(false); TEST(cloud->backgroundSync(), false); cloud->setBaseUrl("test_one"); TEST(cloud->baseUrl(), QStringLiteral("test_one")); cloud->setBaseUrl("test_two"); TEST(cloud->baseUrl(), QStringLiteral("test_two")); cloud->setEmail("*****@*****.**"); TEST(cloud->email(), QStringLiteral("*****@*****.**")); cloud->setEmail("*****@*****.**"); TEST(cloud->email(), QStringLiteral("*****@*****.**")); cloud->setGitLocalOnly(true); TEST(cloud->gitLocalOnly(), true); cloud->setGitLocalOnly(false); TEST(cloud->gitLocalOnly(), false); // Why there's new password and password on the prefs? cloud->setNewPassword("ABCD"); TEST(cloud->newPassword(), QStringLiteral("ABCD")); cloud->setNewPassword("ABCDE"); TEST(cloud->newPassword(), QStringLiteral("ABCDE")); cloud->setPassword("ABCDE"); TEST(cloud->password(), QStringLiteral("ABCDE")); cloud->setPassword("ABCABC"); TEST(cloud->password(), QStringLiteral("ABCABC")); cloud->setSavePasswordLocal(true); TEST(cloud->savePasswordLocal(), true); cloud->setSavePasswordLocal(false); TEST(cloud->savePasswordLocal(), false); // Why this is short and not bool? cloud->setSaveUserIdLocal(1); TEST(cloud->saveUserIdLocal(), (short)1); cloud->setSaveUserIdLocal(0); TEST(cloud->saveUserIdLocal(), (short)0); cloud->setUserId("Tomaz"); TEST(cloud->userId(), QStringLiteral("Tomaz")); cloud->setUserId("Zamot"); TEST(cloud->userId(), QStringLiteral("Zamot")); cloud->setVerificationStatus(0); TEST(cloud->verificationStatus(), (short)0); cloud->setVerificationStatus(1); TEST(cloud->verificationStatus(), (short)1); auto tecDetails = pref->techDetails; tecDetails->setModp02(0.2); TEST(tecDetails->modp02(), 0.2); tecDetails->setModp02(1.0); TEST(tecDetails->modp02(), 1.0); tecDetails->setGflow(2); TEST(tecDetails->gflow(), 2); tecDetails->setGflow(3); TEST(tecDetails->gflow(), 3); tecDetails->setGfhigh(4); TEST(tecDetails->gfhigh(), 4); tecDetails->setGfhigh(5); TEST(tecDetails->gfhigh(), 5); tecDetails->setVpmbConservatism(5); TEST(tecDetails->vpmbConservatism(), (short)5); tecDetails->setVpmbConservatism(6); TEST(tecDetails->vpmbConservatism(), (short)6); tecDetails->setEad(true); TEST(tecDetails->ead(), true); tecDetails->setMod(true); TEST(tecDetails->mod(), true); tecDetails->setDCceiling(true); TEST(tecDetails->dcceiling(), true); tecDetails->setRedceiling(true); TEST(tecDetails->redceiling(), true); tecDetails->setCalcceiling(true); TEST(tecDetails->calcceiling(), true); tecDetails->setCalcceiling3m(true); TEST(tecDetails->calcceiling3m(), true); tecDetails->setCalcalltissues(true); TEST(tecDetails->calcalltissues(), true); tecDetails->setCalcndltts(true); TEST(tecDetails->calcndltts(), true); tecDetails->setBuehlmann(true); TEST(tecDetails->buehlmann(), true); tecDetails->setHRgraph(true); TEST(tecDetails->hrgraph(), true); tecDetails->setTankBar(true); TEST(tecDetails->tankBar(), true); tecDetails->setPercentageGraph(true); TEST(tecDetails->percentageGraph(), true); tecDetails->setRulerGraph(true); TEST(tecDetails->rulerGraph(), true); tecDetails->setShowCCRSetpoint(true); TEST(tecDetails->showCCRSetpoint(), true); tecDetails->setShowCCRSensors(true); TEST(tecDetails->showCCRSensors(), true); tecDetails->setZoomedPlot(true); TEST(tecDetails->zoomedPlot(), true); tecDetails->setShowSac(true); TEST(tecDetails->showSac(), true); tecDetails->setGfLowAtMaxDepth(true); TEST(tecDetails->gfLowAtMaxDepth(), true); tecDetails->setDisplayUnusedTanks(true); TEST(tecDetails->displayUnusedTanks(), true); tecDetails->setShowAverageDepth(true); TEST(tecDetails->showAverageDepth(), true); tecDetails->setShowPicturesInProfile(true); TEST(tecDetails->showPicturesInProfile(), true); tecDetails->setEad(false); TEST(tecDetails->ead(), false); tecDetails->setMod(false); TEST(tecDetails->mod(), false); tecDetails->setDCceiling(false); TEST(tecDetails->dcceiling(), false); tecDetails->setRedceiling(false); TEST(tecDetails->redceiling(), false); tecDetails->setCalcceiling(false); TEST(tecDetails->calcceiling(), false); tecDetails->setCalcceiling3m(false); TEST(tecDetails->calcceiling3m(), false); tecDetails->setCalcalltissues(false); TEST(tecDetails->calcalltissues(), false); tecDetails->setCalcndltts(false); TEST(tecDetails->calcndltts(), false); tecDetails->setBuehlmann(false); TEST(tecDetails->buehlmann(), false); tecDetails->setHRgraph(false); TEST(tecDetails->hrgraph(), false); tecDetails->setTankBar(false); TEST(tecDetails->tankBar(), false); tecDetails->setPercentageGraph(false); TEST(tecDetails->percentageGraph(), false); tecDetails->setRulerGraph(false); TEST(tecDetails->rulerGraph(), false); tecDetails->setShowCCRSetpoint(false); TEST(tecDetails->showCCRSetpoint(), false); tecDetails->setShowCCRSensors(false); TEST(tecDetails->showCCRSensors(), false); tecDetails->setZoomedPlot(false); TEST(tecDetails->zoomedPlot(), false); tecDetails->setShowSac(false); TEST(tecDetails->showSac(), false); tecDetails->setGfLowAtMaxDepth(false); TEST(tecDetails->gfLowAtMaxDepth(), false); tecDetails->setDisplayUnusedTanks(false); TEST(tecDetails->displayUnusedTanks(), false); tecDetails->setShowAverageDepth(false); TEST(tecDetails->showAverageDepth(), false); tecDetails->setShowPicturesInProfile(false); TEST(tecDetails->showPicturesInProfile(), false); auto pp = pref->pp_gas; pp->setShowPn2(false); pp->setShowPhe(false); pp->setShowPo2(false); pp->setPo2Threshold(1.0); pp->setPn2Threshold(2.0); pp->setPheThreshold(3.0); TEST(pp->showPn2(), (short) false); TEST(pp->showPhe(), (short) false); TEST(pp->showPo2(), (short) false); TEST(pp->pn2Threshold(), 2.0); TEST(pp->pheThreshold(), 3.0); TEST(pp->po2Threshold(), 1.0); pp->setShowPn2(true); pp->setShowPhe(true); pp->setShowPo2(true); pp->setPo2Threshold(4.0); pp->setPn2Threshold(5.0); pp->setPheThreshold(6.0); TEST(pp->showPn2(), (short) true); TEST(pp->showPhe(), (short) true); TEST(pp->showPo2(), (short) true); TEST(pp->pn2Threshold(), 5.0); TEST(pp->pheThreshold(), 6.0); TEST(pp->po2Threshold(), 4.0); auto fb = pref->facebook; fb->setAccessToken("rand-access-token"); fb->setUserId("tomaz-user-id"); fb->setAlbumId("album-id"); TEST(fb->accessToken(),QStringLiteral("rand-access-token")); TEST(fb->userId(), QStringLiteral("tomaz-user-id")); TEST(fb->albumId(), QStringLiteral("album-id")); fb->setAccessToken("rand-access-token-2"); fb->setUserId("tomaz-user-id-2"); fb->setAlbumId("album-id-2"); TEST(fb->accessToken(),QStringLiteral("rand-access-token-2")); TEST(fb->userId(), QStringLiteral("tomaz-user-id-2")); TEST(fb->albumId(), QStringLiteral("album-id-2")); auto geo = pref->geocoding; geo->setEnableGeocoding(true); geo->setParseDiveWithoutGps(true); geo->setTagExistingDives(true); TEST(geo->enableGeocoding(),true); TEST(geo->parseDiveWithoutGps(),true); TEST(geo->tagExistingDives(),true); geo->setFirstTaxonomyCategory(TC_NONE); geo->setSecondTaxonomyCategory(TC_OCEAN); geo->setThirdTaxonomyCategory(TC_COUNTRY); TEST(geo->firstTaxonomyCategory(), TC_NONE); TEST(geo->secondTaxonomyCategory(), TC_OCEAN); TEST(geo->thirdTaxonomyCategory(), TC_COUNTRY); geo->setEnableGeocoding(false); geo->setParseDiveWithoutGps(false); geo->setTagExistingDives(false); TEST(geo->enableGeocoding(),false); TEST(geo->parseDiveWithoutGps(),false); TEST(geo->tagExistingDives(),false); geo->setFirstTaxonomyCategory(TC_OCEAN); geo->setSecondTaxonomyCategory(TC_COUNTRY); geo->setThirdTaxonomyCategory(TC_NONE); TEST(geo->firstTaxonomyCategory(), TC_OCEAN); TEST(geo->secondTaxonomyCategory(), TC_COUNTRY); TEST(geo->thirdTaxonomyCategory(), TC_NONE); auto proxy = pref->proxy; proxy->setType(2); proxy->setPort(80); proxy->setAuth(true); proxy->setHost("localhost"); proxy->setUser("unknown"); proxy->setPass("secret"); TEST(proxy->type(),2); TEST(proxy->port(),80); TEST(proxy->auth(),true); TEST(proxy->host(),QStringLiteral("localhost")); TEST(proxy->user(),QStringLiteral("unknown")); TEST(proxy->pass(),QStringLiteral("secret")); proxy->setType(3); proxy->setPort(8080); proxy->setAuth(false); proxy->setHost("127.0.0.1"); proxy->setUser("unknown_1"); proxy->setPass("secret_1"); TEST(proxy->type(),3); TEST(proxy->port(),8080); TEST(proxy->auth(),false); TEST(proxy->host(),QStringLiteral("127.0.0.1")); TEST(proxy->user(),QStringLiteral("unknown_1")); TEST(proxy->pass(),QStringLiteral("secret_1")); auto planner = pref->planner_settings; planner->setLastStop(true); planner->setVerbatimPlan(true); planner->setDisplayRuntime(true); planner->setDisplayDuration(true); planner->setDisplayTransitions(true); planner->setDoo2breaks(true); planner->setDropStoneMode(true); planner->setSafetyStop(true); planner->setSwitchAtRequiredStop(true); planner->setAscrate75(1); planner->setAscrate50(2); planner->setAscratestops(3); planner->setAscratelast6m(4); planner->setDescrate(5); planner->setBottompo2(6); planner->setDecopo2(7); planner->setBestmixend(8); planner->setReserveGas(9); planner->setMinSwitchDuration(10); planner->setBottomSac(11); planner->setDecoSac(12); planner->setDecoMode(BUEHLMANN); TEST(planner->lastStop(),true); TEST(planner->verbatimPlan(),true); TEST(planner->displayRuntime(),true); TEST(planner->displayDuration(),true); TEST(planner->displayTransitions(),true); TEST(planner->doo2breaks(),true); TEST(planner->dropStoneMode(),true); TEST(planner->safetyStop(),true); TEST(planner->switchAtRequiredStop(),true); TEST(planner->ascrate75(),1); TEST(planner->ascrate50(),2); TEST(planner->ascratestops(),3); TEST(planner->ascratelast6m(),4); TEST(planner->descrate(),5); TEST(planner->bottompo2(),6); TEST(planner->decopo2(),7); TEST(planner->bestmixend(),8); TEST(planner->reserveGas(),9); TEST(planner->minSwitchDuration(),10); TEST(planner->bottomSac(),11); TEST(planner->decoSac(),12); TEST(planner->decoMode(),BUEHLMANN); planner->setLastStop(false); planner->setVerbatimPlan(false); planner->setDisplayRuntime(false); planner->setDisplayDuration(false); planner->setDisplayTransitions(false); planner->setDoo2breaks(false); planner->setDropStoneMode(false); planner->setSafetyStop(false); planner->setSwitchAtRequiredStop(false); planner->setAscrate75(11); planner->setAscrate50(12); planner->setAscratestops(13); planner->setAscratelast6m(14); planner->setDescrate(15); planner->setBottompo2(16); planner->setDecopo2(17); planner->setBestmixend(18); planner->setReserveGas(19); planner->setMinSwitchDuration(110); planner->setBottomSac(111); planner->setDecoSac(112); planner->setDecoMode(RECREATIONAL); TEST(planner->lastStop(),false); TEST(planner->verbatimPlan(),false); TEST(planner->displayRuntime(),false); TEST(planner->displayDuration(),false); TEST(planner->displayTransitions(),false); TEST(planner->doo2breaks(),false); TEST(planner->dropStoneMode(),false); TEST(planner->safetyStop(),false); TEST(planner->switchAtRequiredStop(),false); TEST(planner->ascrate75(),11); TEST(planner->ascrate50(),12); TEST(planner->ascratestops(),13); TEST(planner->ascratelast6m(),14); TEST(planner->descrate(),15); TEST(planner->bottompo2(),16); TEST(planner->decopo2(),17); TEST(planner->bestmixend(),18); TEST(planner->reserveGas(),19); TEST(planner->minSwitchDuration(),110); TEST(planner->bottomSac(),111); TEST(planner->decoSac(),112); TEST(planner->decoMode(),RECREATIONAL); auto units = pref->unit_settings; units->setLength(0); units->setPressure(0); units->setVolume(0); units->setTemperature(0); units->setWeight(0); units->setVerticalSpeedTime(0); units->setUnitSystem(QStringLiteral("metric")); units->setCoordinatesTraditional(false); TEST(units->length(),0); TEST(units->pressure(),0); TEST(units->volume(),0); TEST(units->temperature(),0); TEST(units->weight(),0); TEST(units->verticalSpeedTime(),0); TEST(units->unitSystem(),QStringLiteral("metric")); TEST(units->coordinatesTraditional(),false); units->setLength(1); units->setPressure(1); units->setVolume(1); units->setTemperature(1); units->setWeight(1); units->setVerticalSpeedTime(1); units->setUnitSystem(QStringLiteral("fake-metric-system")); units->setCoordinatesTraditional(true); TEST(units->length(),1); TEST(units->pressure(),1); TEST(units->volume(),1); TEST(units->temperature(),1); TEST(units->weight(),1); TEST(units->verticalSpeedTime(),1); TEST(units->unitSystem(),QStringLiteral("personalized")); TEST(units->coordinatesTraditional(),true); auto general = pref->general_settings; general->setDefaultFilename ("filename"); general->setDefaultCylinder ("cylinder_2"); //TODOl: Change this to a enum. // This is 'undefined', it will need to figure out later between no_file or use_deault file. general->setDefaultFileBehavior (0); general->setDefaultSetPoint (0); general->setO2Consumption (0); general->setPscrRatio (0); general->setUseDefaultFile (true); TEST(general->defaultFilename(), QStringLiteral("filename")); TEST(general->defaultCylinder(), QStringLiteral("cylinder_2")); TEST(general->defaultFileBehavior(), (short) LOCAL_DEFAULT_FILE); // since we have a default file, here it returns TEST(general->defaultSetPoint(), 0); TEST(general->o2Consumption(), 0); TEST(general->pscrRatio(), 0); TEST(general->useDefaultFile(), true); general->setDefaultFilename ("no_file_name"); general->setDefaultCylinder ("cylinder_1"); //TODOl: Change this to a enum. general->setDefaultFileBehavior (CLOUD_DEFAULT_FILE); general->setDefaultSetPoint (1); general->setO2Consumption (1); general->setPscrRatio (1); general->setUseDefaultFile (false); TEST(general->defaultFilename(), QStringLiteral("no_file_name")); TEST(general->defaultCylinder(), QStringLiteral("cylinder_1")); TEST(general->defaultFileBehavior(), (short) CLOUD_DEFAULT_FILE); TEST(general->defaultSetPoint(), 1); TEST(general->o2Consumption(), 1); TEST(general->pscrRatio(), 1); TEST(general->useDefaultFile(), false); auto display = pref->display_settings; display->setDivelistFont("comic"); display->setFontSize(10.0); display->setDisplayInvalidDives(true); TEST(display->divelistFont(),QStringLiteral("comic")); TEST(display->fontSize(), 10.0); TEST(display->displayInvalidDives(),(short) true); //TODO: this is true / false. display->setDivelistFont("helvetica"); display->setFontSize(14.0); display->setDisplayInvalidDives(false); TEST(display->divelistFont(),QStringLiteral("helvetica")); TEST(display->fontSize(), 14.0); TEST(display->displayInvalidDives(),(short) false); auto language = pref->language_settings; language->setLangLocale ("en_US"); language->setLanguage ("en"); language->setTimeFormat ("hh:mm"); language->setDateFormat ("dd/mm/yy"); language->setDateFormatShort ("dd/mm"); language->setTimeFormatOverride (false); language->setDateFormatOverride (false); language->setUseSystemLanguage (false); TEST(language->langLocale(), QStringLiteral("en_US")); TEST(language->language(), QStringLiteral("en")); TEST(language->timeFormat(), QStringLiteral("hh:mm")); TEST(language->dateFormat(), QStringLiteral("dd/mm/yy")); TEST(language->dateFormatShort(), QStringLiteral("dd/mm")); TEST(language->timeFormatOverride(), false); TEST(language->dateFormatOverride(), false); TEST(language->useSystemLanguage(), false); language->setLangLocale ("en_EN"); language->setLanguage ("br"); language->setTimeFormat ("mm:hh"); language->setDateFormat ("yy/mm/dd"); language->setDateFormatShort ("dd/yy"); language->setTimeFormatOverride (true); language->setDateFormatOverride (true); language->setUseSystemLanguage (true); TEST(language->langLocale(), QStringLiteral("en_EN")); TEST(language->language(), QStringLiteral("br")); TEST(language->timeFormat(), QStringLiteral("mm:hh")); TEST(language->dateFormat(), QStringLiteral("yy/mm/dd")); TEST(language->dateFormatShort(), QStringLiteral("dd/yy")); TEST(language->timeFormatOverride(),true); TEST(language->dateFormatOverride(),true); TEST(language->useSystemLanguage(), true); pref->animation_settings->setAnimationSpeed(20); TEST(pref->animation_settings->animationSpeed(), 20); pref->animation_settings->setAnimationSpeed(30); TEST(pref->animation_settings->animationSpeed(), 30); auto location = pref->location_settings; location->setTimeThreshold(10); location->setDistanceThreshold(20); TEST(location->timeThreshold(), 10); TEST(location->distanceThreshold(), 20); location->setTimeThreshold(30); location->setDistanceThreshold(40); TEST(location->timeThreshold(), 30); TEST(location->distanceThreshold(), 40); auto update = pref->update_manager_settings; QDate date = QDate::currentDate(); update->setDontCheckForUpdates(true); update->setLastVersionUsed("tomaz-1"); update->setNextCheck(date); TEST(update->dontCheckForUpdates(), true); TEST(update->lastVersionUsed(), QStringLiteral("tomaz-1")); TEST(update->nextCheck(), date); date.addDays(3); update->setDontCheckForUpdates(false); update->setLastVersionUsed("tomaz-2"); update->setNextCheck(date); TEST(update->dontCheckForUpdates(), false); TEST(update->lastVersionUsed(), QStringLiteral("tomaz-2")); TEST(update->nextCheck(), date); auto dc = pref->dive_computer_settings; dc->setDevice("TomazComputer"); TEST(dc->dc_device(), QStringLiteral("TomazComputer")); dc->setDevice("Deepwater"); TEST(dc->dc_device(), QStringLiteral("Deepwater")); dc->setDownloadMode(0); TEST(dc->downloadMode(), 0); dc->setDownloadMode(1); TEST(dc->downloadMode(), 1); dc->setProduct("Thingy1"); TEST(dc->dc_product(), QStringLiteral("Thingy1")); dc->setProduct("Thingy2"); TEST(dc->dc_product(), QStringLiteral("Thingy2")); dc->setVendor("Sharewater"); TEST(dc->dc_vendor(), QStringLiteral("Sharewater")); dc->setVendor("OSTS"); TEST(dc->dc_vendor(), QStringLiteral("OSTS")); }
int main (int argc, char *argv[]) { /* Scan the argument vector and strip off all parameters known to * GTK+. */ Gtk::Main kit(argc, argv); /*prepare global MIDI definitions*/ for ( int i=0; i<c_maxBuses; i++ ) { for ( int j=0; j<16; j++ ) global_user_midi_bus_definitions[i].instrument[j] = -1; } for ( int i=0; i<c_max_instruments; i++ ) { for ( int j=0; j<128; j++ ) global_user_instrument_definitions[i].controllers_active[j] = false; } /* Init the lash driver (strip lash specific command line * arguments and connect to daemon) */ #ifdef LASH_SUPPORT lash_driver = new lash(&argc, &argv); #endif /* the main performance object */ /* lash must be initialized here because mastermidibus uses the global * lash_driver variable*/ perform p; /* read user preferences files */ if ( getenv( HOME ) != NULL ) { Glib::ustring home( getenv( HOME )); last_used_dir = home; Glib::ustring total_file = home + SLASH + config_filename; if (Glib::file_test(total_file, Glib::FILE_TEST_EXISTS)) { printf( "Reading [%s]\n", total_file.c_str()); optionsfile options( total_file ); if ( !options.parse( &p ) ) { printf( "Error Reading [%s]\n", total_file.c_str()); } } total_file = home + SLASH + user_filename; if (Glib::file_test(total_file, Glib::FILE_TEST_EXISTS)) { printf( "Reading [%s]\n", total_file.c_str()); userfile user( total_file ); if ( !user.parse( &p ) ) { printf( "Error Reading [%s]\n", total_file.c_str()); } } } else printf( "Error calling getenv( \"%s\" )\n", HOME ); /* parse parameters */ int c; while (true) { /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "Chi:jJkmM:pPsSU:vx:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case '?': case 'h': printf( " -h, --help: show this message\n" ); printf( " -v, --version: show program version information\n" ); printf( " -m, --manual_alsa_ports: seq42 won't attach alsa ports\n" ); printf( " -s, --showmidi: dumps incoming midi events to screen\n" ); printf( " -p, --priority: runs higher priority with FIFO scheduler (must be root)\n" ); printf( " -P, --pass_sysex: passes any incoming sysex messages to all outputs \n" ); printf( " -i, --ignore <number>: ignore ALSA device\n" ); printf( " -k, --show_keys: prints pressed key value\n" ); printf( " -x, --interaction_method <number>: see .seq42rc for methods to use\n" ); printf( " -j, --jack_transport: seq42 will sync to jack transport\n" ); printf( " -J, --jack_master: seq42 will try to be jack master\n" ); printf( " -C, --jack_master_cond: jack master will fail if there is already a master\n" ); printf( " -M, --song_start_mode <mode>: The following play\n" ); printf( " modes are available (0 = live mode)\n"); printf( " (1 = song mode) (default)\n" ); printf( " -S, --stats: show statistics\n" ); printf( " -U, --jack_session_uuid <uuid>: set uuid for jack session\n" ); printf( "\n\n\n" ); return EXIT_SUCCESS; break; case 'S': global_stats = true; break; case 's': global_showmidi = true; break; case 'p': global_priority = true; break; case 'P': global_pass_sysex = true; break; case 'k': global_print_keys = true; break; case 'j': global_with_jack_transport = true; break; case 'J': global_with_jack_master = true; break; case 'C': global_with_jack_master_cond = true; break; case 'M': if (atoi( optarg ) > 0) { global_song_start_mode = true; } else { global_song_start_mode = false; } break; case 'm': global_manual_alsa_ports = true; break; case 'i': /* ignore alsa device */ global_device_ignore = true; global_device_ignore_num = atoi( optarg ); break; case 'v': printf("%s", versiontext); return EXIT_SUCCESS; break; case 'U': global_jack_session_uuid = Glib::ustring(optarg); break; case 'x': global_interactionmethod = (interaction_method_e)atoi( optarg ); break; default: break; } } /* end while */ p.init(); p.launch_input_thread(); p.launch_output_thread(); p.init_jack(); p_font_renderer = new font(); mainwnd seq42_window( &p ); if (optind < argc) { if (Glib::file_test(argv[optind], Glib::FILE_TEST_EXISTS)) seq42_window.open_file(argv[optind]); else printf("File not found: %s\n", argv[optind]); } /* connect to lash daemon and poll events*/ #ifdef LASH_SUPPORT lash_driver->start( &p ); #endif kit.run(seq42_window); p.deinit_jack(); if ( getenv( HOME ) != NULL ) { string home( getenv( HOME )); Glib::ustring total_file = home + SLASH + config_filename; printf( "Writing [%s]\n", total_file.c_str()); optionsfile options( total_file ); if ( !options.write( &p ) ) { printf( "Error writing [%s]\n", total_file.c_str()); } } else { printf( "Error calling getenv( \"%s\" )\n", HOME ); } #ifdef LASH_SUPPORT delete lash_driver; #endif return 0; }
/* * Handles commands received from the slave process. It will not return * except in one situation: After successful authentication it will * return as the user-privileged slave process. */ void handle_cmds(void) { enum monitor_command cmd; enum auth_ret auth; int err, s, slavequit, serrno, domain; pid_t preauth_slave_pid; size_t len; union sockunion sa; socklen_t salen; char *name, *pw; for (;;) { recv_data(fd_slave, &cmd, sizeof(cmd)); switch (cmd) { case CMD_USER: debugmsg("CMD_USER received"); recv_data(fd_slave, &len, sizeof(len)); if (len == SIZE_T_MAX) fatalx("monitor received invalid user length"); if ((name = malloc(len + 1)) == NULL) fatalx("malloc: %m"); if (len > 0) recv_data(fd_slave, name, len); name[len] = '\0'; user(name); free(name); break; case CMD_PASS: debugmsg("CMD_PASS received"); recv_data(fd_slave, &len, sizeof(len)); if (len == SIZE_T_MAX) fatalx("monitor received invalid pass length"); if ((pw = malloc(len + 1)) == NULL) fatalx("malloc: %m"); if (len > 0) recv_data(fd_slave, pw, len); pw[len] = '\0'; preauth_slave_pid = slave_pid; auth = pass(pw); bzero(pw, len); free(pw); switch (auth) { case AUTH_FAILED: /* Authentication failure */ debugmsg("authentication failed"); slavequit = 0; send_data(fd_slave, &slavequit, sizeof(slavequit)); break; case AUTH_SLAVE: /* User-privileged slave */ debugmsg("user-privileged slave started"); return; /* NOTREACHED */ case AUTH_MONITOR: /* Post-auth monitor */ debugmsg("monitor went into post-auth phase"); state = POSTAUTH; #ifdef HASSETPROCTITLE setproctitle("%s: [priv post-auth]", remotehost); #endif slavequit = 1; send_data(fd_slave, &slavequit, sizeof(slavequit)); while (waitpid(preauth_slave_pid, NULL, 0) < 0 && errno == EINTR) ; break; default: fatalx("bad return value from pass()"); /* NOTREACHED */ } break; case CMD_SOCKET: debugmsg("CMD_SOCKET received"); if (state != POSTAUTH) fatalx("CMD_SOCKET received in invalid state"); recv_data(fd_slave, &domain, sizeof(domain)); if (domain != AF_INET && domain != AF_INET6) fatalx("monitor received invalid addr family"); s = socket(domain, SOCK_STREAM, 0); serrno = errno; send_fd(fd_slave, s); if (s == -1) send_data(fd_slave, &serrno, sizeof(serrno)); else close(s); break; case CMD_BIND: debugmsg("CMD_BIND received"); if (state != POSTAUTH) fatalx("CMD_BIND received in invalid state"); s = recv_fd(fd_slave); recv_data(fd_slave, &salen, sizeof(salen)); if (salen == 0 || salen > sizeof(sa)) fatalx("monitor received invalid sockaddr len"); bzero(&sa, sizeof(sa)); recv_data(fd_slave, &sa, salen); if (sa.su_si.si_len != salen) fatalx("monitor received invalid sockaddr len"); if (sa.su_si.si_family != AF_INET && sa.su_si.si_family != AF_INET6) fatalx("monitor received invalid addr family"); err = bind(s, (struct sockaddr *)&sa, salen); serrno = errno; if (s >= 0) close(s); send_data(fd_slave, &err, sizeof(err)); if (err == -1) send_data(fd_slave, &serrno, sizeof(serrno)); break; default: fatalx("monitor received unknown command %d", cmd); /* NOTREACHED */ } } }
//// HOST_SAY // String comes in as // say blah blah blah // or as // blah blah blah // void Host_Say( edict_t *pEdict, const CCommand &args, bool teamonly ) { CBasePlayer *client; int j; char *p; char text[256]; char szTemp[256]; const char *cpSay = "say"; const char *cpSayTeam = "say_team"; const char *pcmd = args[0]; bool bSenderDead = false; // We can get a raw string now, without the "say " prepended if ( args.ArgC() == 0 ) return; if ( !stricmp( pcmd, cpSay) || !stricmp( pcmd, cpSayTeam ) ) { if ( args.ArgC() >= 2 ) { p = (char *)args.ArgS(); } else { // say with a blank message, nothing to do return; } } else // Raw text, need to prepend argv[0] { if ( args.ArgC() >= 2 ) { Q_snprintf( szTemp,sizeof(szTemp), "%s %s", ( char * )pcmd, (char *)args.ArgS() ); } else { // Just a one word command, use the first word...sigh Q_snprintf( szTemp,sizeof(szTemp), "%s", ( char * )pcmd ); } p = szTemp; } CBasePlayer *pPlayer = NULL; if ( pEdict ) { pPlayer = ((CBasePlayer *)CBaseEntity::Instance( pEdict )); Assert( pPlayer ); // make sure the text has valid content p = CheckChatText( pPlayer, p ); } if ( !p ) return; if ( pEdict ) { if ( !pPlayer->CanSpeak() ) return; // See if the player wants to modify of check the text pPlayer->CheckChatText( p, 127 ); // though the buffer szTemp that p points to is 256, // chat text is capped to 127 in CheckChatText above Assert( strlen( pPlayer->GetPlayerName() ) > 0 ); bSenderDead = ( pPlayer->m_lifeState != LIFE_ALIVE ); } else { bSenderDead = false; } const char *pszFormat = NULL; const char *pszPrefix = NULL; const char *pszLocation = NULL; if ( g_pGameRules ) { pszFormat = g_pGameRules->GetChatFormat( teamonly, pPlayer ); pszPrefix = g_pGameRules->GetChatPrefix( teamonly, pPlayer ); pszLocation = g_pGameRules->GetChatLocation( teamonly, pPlayer ); } const char *pszPlayerName = pPlayer ? pPlayer->GetPlayerName():"Console"; if ( pszPrefix && strlen( pszPrefix ) > 0 ) { if ( pszLocation && strlen( pszLocation ) ) { Q_snprintf( text, sizeof(text), "%s %s @ %s: ", pszPrefix, pszPlayerName, pszLocation ); } else { Q_snprintf( text, sizeof(text), "%s %s: ", pszPrefix, pszPlayerName ); } } else { Q_snprintf( text, sizeof(text), "%s: ", pszPlayerName ); } j = sizeof(text) - 2 - strlen(text); // -2 for /n and null terminator if ( (int)strlen(p) > j ) p[j] = 0; Q_strncat( text, p, sizeof( text ), COPY_ALL_CHARACTERS ); Q_strncat( text, "\n", sizeof( text ), COPY_ALL_CHARACTERS ); // loop through all players // Start with the first player. // This may return the world in single player if the client types something between levels or during spawn // so check it, or it will infinite loop client = NULL; for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { client = ToBaseMultiplayerPlayer( UTIL_PlayerByIndex( i ) ); if ( !client || !client->edict() ) continue; if ( client->edict() == pEdict ) continue; if ( !(client->IsNetClient()) ) // Not a client ? (should never be true) continue; if ( teamonly && g_pGameRules->PlayerCanHearChat( client, pPlayer ) != GR_TEAMMATE ) continue; if ( pPlayer && !client->CanHearAndReadChatFrom( pPlayer ) ) continue; if ( pPlayer && GetVoiceGameMgr() && GetVoiceGameMgr()->IsPlayerIgnoringPlayer( pPlayer->entindex(), i ) ) continue; CSingleUserRecipientFilter user( client ); user.MakeReliable(); if ( pszFormat ) { UTIL_SayText2Filter( user, pPlayer, true, pszFormat, pszPlayerName, p, pszLocation ); } else { UTIL_SayTextFilter( user, text, pPlayer, true ); } } if ( pPlayer ) { // print to the sending client CSingleUserRecipientFilter user( pPlayer ); user.MakeReliable(); if ( pszFormat ) { UTIL_SayText2Filter( user, pPlayer, true, pszFormat, pszPlayerName, p, pszLocation ); } else { UTIL_SayTextFilter( user, text, pPlayer, true ); } } // echo to server console // Adrian: Only do this if we're running a dedicated server since we already print to console on the client. if ( engine->IsDedicatedServer() ) Msg( "%s", text ); Assert( p ); int userid = 0; const char *networkID = "Console"; const char *playerName = "Console"; const char *playerTeam = "Console"; if ( pPlayer ) { userid = pPlayer->GetUserID(); networkID = pPlayer->GetNetworkIDString(); playerName = pPlayer->GetPlayerName(); CTeam *team = pPlayer->GetTeam(); if ( team ) { playerTeam = team->GetName(); } } if ( teamonly ) UTIL_LogPrintf( "\"%s<%i><%s><%s>\" say_team \"%s\"\n", playerName, userid, networkID, playerTeam, p ); else UTIL_LogPrintf( "\"%s<%i><%s><%s>\" say \"%s\"\n", playerName, userid, networkID, playerTeam, p ); IGameEvent * event = gameeventmanager->CreateEvent( "player_say" ); if ( event ) // will be null if there are no listeners! { event->SetInt("userid", userid ); event->SetString("text", p ); event->SetInt("priority", 1 ); // HLTV event priority, not transmitted gameeventmanager->FireEvent( event ); } }
int main() { static Class instance = { probe }; funUser([](auto... p) { user(instance, p...); }); }
int main( int argc, char* argv[] ) { std::string user( "lenss_lab" ); std::string pass( "Lenss123" ); twitCurl twitterObj; std::string tmpStr; std::string replyMsg; char tmpBuf[1024]; int tmpVar = 0; /* Set twitter username and password */ twitterObj.setTwitterUsername( user ); twitterObj.setTwitterPassword( pass ); /* OAuth flow begins */ /* Step 0: Set OAuth related params. These are got by registering your app at twitter.com */ twitterObj.getOAuth().setConsumerKey( std::string( "PYfkFFlcdqJEyiarhOtug" ) ); twitterObj.getOAuth().setConsumerSecret( std::string( "mM7WWBAbSXfqOlXrVqKjt3Gna7SrG7X8u0EAhEwi8" ) ); /* Step 1: Check if we alredy have OAuth access token from a previous run */ std::string myOAuthAccessTokenKey( "266263893-P9g5kdxLrpkazhrRHug2ks16XvypSr4LjXY7mYKe" ); std::string myOAuthAccessTokenSecret( "KWiGEqGldGUbLBNZ72zZavCSNZK0iXgF0f7gwA3Ms" ); std::ifstream oAuthTokenKeyIn; std::ifstream oAuthTokenSecretIn; /* oAuthTokenKeyIn.open( "twitterClient_token_key.txt" ); oAuthTokenSecretIn.open( "twitterClient_token_secret.txt" ); memset( tmpBuf, 0, 1024 ); oAuthTokenKeyIn >> tmpBuf; myOAuthAccessTokenKey = tmpBuf; memset( tmpBuf, 0, 1024 ); oAuthTokenSecretIn >> tmpBuf; myOAuthAccessTokenSecret = tmpBuf; oAuthTokenKeyIn.close(); oAuthTokenSecretIn.close();*/ if( myOAuthAccessTokenKey.size() && myOAuthAccessTokenSecret.size() ) { /* If we already have these keys, then no need to go through auth again */ printf( "\nUsing:\nKey: %s\nSecret: %s\n\n", myOAuthAccessTokenKey.c_str(), myOAuthAccessTokenSecret.c_str() ); twitterObj.getOAuth().setOAuthTokenKey( myOAuthAccessTokenKey ); twitterObj.getOAuth().setOAuthTokenSecret( myOAuthAccessTokenSecret ); } else { /* Step 2: Get request token key and secret */ twitterObj.oAuthRequestToken( tmpStr ); /* Step 3: Get PIN */ memset( tmpBuf, 0, 1024 ); printf( "\nDo you want to visit twitter.com for PIN (0 for no; 1 for yes): " ); gets( tmpBuf ); tmpVar = atoi( tmpBuf ); if( tmpVar > 0 ) { /* Ask user to visit twitter.com page and get PIN */ memset( tmpBuf, 0, 1024 ); printf( "\nPlease visit this link in web browser and authorize this application:\n%s", tmpStr.c_str() ); printf( "\nEnter the PIN provided by twitter: " ); gets( tmpBuf ); tmpStr = tmpBuf; twitterObj.getOAuth().setOAuthPin( tmpStr ); } else { /* Else, get it via twitcurl PIN handling */ twitterObj.oAuthHandlePIN( tmpStr ); } /* Step 4: Exchange request token with access token */ twitterObj.oAuthAccessToken(); /* Step 5: Now, save this access token key and secret for future use without PIN */ twitterObj.getOAuth().getOAuthTokenKey( myOAuthAccessTokenKey ); twitterObj.getOAuth().getOAuthTokenSecret( myOAuthAccessTokenSecret ); /* Step 6: Save these keys in a file or wherever */ std::ofstream oAuthTokenKeyOut; std::ofstream oAuthTokenSecretOut; oAuthTokenKeyOut.open( "twitterClient_token_key.txt" ); oAuthTokenSecretOut.open( "twitterClient_token_secret.txt" ); oAuthTokenKeyOut.clear(); oAuthTokenSecretOut.clear(); oAuthTokenKeyOut << myOAuthAccessTokenKey.c_str(); oAuthTokenSecretOut << myOAuthAccessTokenSecret.c_str(); oAuthTokenKeyOut.close(); oAuthTokenSecretOut.close(); } /* OAuth flow ends */ /* Post a new status message */ char statusMsg[1024]; memset( statusMsg, 0, 1024 ); printf( "\nEnter a new status message: " ); gets( statusMsg ); tmpStr = statusMsg; replyMsg = ""; if( twitterObj.statusUpdate( tmpStr ) ) { twitterObj.getLastWebResponse( replyMsg ); printf( "\ntwitterClient:: twitCurl::statusUpdate web response:\n%s\n", replyMsg.c_str() ); } else { twitterObj.getLastCurlError( replyMsg ); printf( "\ntwitterClient:: twitCurl::statusUpdate error:\n%s\n", replyMsg.c_str() ); } return 0; }
StatusWith<std::tuple<bool, std::string>> SaslSCRAMServerMechanism<Policy>::_firstStep( OperationContext* opCtx, StringData inputData) { const auto badCount = [](int got) { return Status(ErrorCodes::BadValue, str::stream() << "Incorrect number of arguments for first SCRAM client message, got " << got << " expected at least 3"); }; /** * gs2-cbind-flag := ("p=" cb-name) / 'y' / 'n' * gs2-header := gs2-cbind-flag ',' [ authzid ] ',' * reserved-mext := "m=" 1*(value-char) * client-first-message-bare := [reserved-mext ','] username ',' nonce [',' extensions] * client-first-message := gs2-header client-first-message-bare */ const auto gs2_cbind_comma = inputData.find(','); if (gs2_cbind_comma == std::string::npos) { return badCount(1); } const auto gs2_cbind_flag = inputData.substr(0, gs2_cbind_comma); if (gs2_cbind_flag.startsWith("p=")) { return Status(ErrorCodes::BadValue, "Server does not support channel binding"); } if ((gs2_cbind_flag != "y") && (gs2_cbind_flag != "n")) { return Status(ErrorCodes::BadValue, str::stream() << "Incorrect SCRAM client message prefix: " << gs2_cbind_flag); } const auto gs2_header_comma = inputData.find(',', gs2_cbind_comma + 1); if (gs2_header_comma == std::string::npos) { return badCount(2); } auto authzId = inputData.substr(gs2_cbind_comma + 1, gs2_header_comma - (gs2_cbind_comma + 1)); if (authzId.size()) { if (authzId.startsWith("a=")) { authzId = authzId.substr(2); } else { return Status(ErrorCodes::BadValue, str::stream() << "Incorrect SCRAM authzid: " << authzId); } } const auto client_first_message_bare = inputData.substr(gs2_header_comma + 1); if (client_first_message_bare.startsWith("m=")) { return Status(ErrorCodes::BadValue, "SCRAM mandatory extensions are not supported"); } /* StringSplitter::split() will ignore consecutive delimiters. * e.g. "foo,,bar" => {"foo","bar"} * This makes our implementation of SCRAM *slightly* more generous * in what it will accept than the standard calls for. * * This does not impact _authMessage, as it's composed from the raw * string input, rather than the output of the split operation. */ const auto input = StringSplitter::split(client_first_message_bare.toString(), ","); if (input.size() < 2) { // gs2-header is not included in this count, so add it back in. return badCount(input.size() + 2); } if (!str::startsWith(input[0], "n=") || input[0].size() < 3) { return Status(ErrorCodes::BadValue, str::stream() << "Invalid SCRAM user name: " << input[0]); } ServerMechanismBase::_principalName = input[0].substr(2); decodeSCRAMUsername(ServerMechanismBase::_principalName); if (!authzId.empty() && ServerMechanismBase::_principalName != authzId) { return Status(ErrorCodes::BadValue, str::stream() << "SCRAM user name " << ServerMechanismBase::_principalName << " does not match authzid " << authzId); } if (!str::startsWith(input[1], "r=") || input[1].size() < 6) { return Status(ErrorCodes::BadValue, str::stream() << "Invalid SCRAM client nonce: " << input[1]); } const auto clientNonce = input[1].substr(2); // SERVER-16534, SCRAM-SHA-1 must be enabled for authenticating the internal user, so that // cluster members may communicate with each other. Hence ignore disabled auth mechanism // for the internal user. UserName user(ServerMechanismBase::ServerMechanismBase::_principalName, ServerMechanismBase::getAuthenticationDatabase()); if (!sequenceContains(saslGlobalParams.authenticationMechanisms, "SCRAM-SHA-1") && user != internalSecurity.user->getName()) { return Status(ErrorCodes::BadValue, "SCRAM-SHA-1 authentication is disabled"); } // The authentication database is also the source database for the user. User* userObj; auto authManager = AuthorizationManager::get(opCtx->getServiceContext()); Status status = authManager->acquireUser(opCtx, user, &userObj); if (!status.isOK()) { return status; } User::CredentialData credentials = userObj->getCredentials(); UserName userName = userObj->getName(); authManager->releaseUser(userObj); _scramCredentials = credentials.scram<HashBlock>(); if (!_scramCredentials.isValid()) { // Check for authentication attempts of the __system user on // systems started without a keyfile. if (userName == internalSecurity.user->getName()) { return Status(ErrorCodes::AuthenticationFailed, "It is not possible to authenticate as the __system user " "on servers started without a --keyFile parameter"); } else { return Status(ErrorCodes::AuthenticationFailed, "Unable to perform SCRAM authentication for a user with missing " "or invalid SCRAM credentials"); } } _secrets = scram::Secrets<HashBlock>("", base64::decode(_scramCredentials.storedKey), base64::decode(_scramCredentials.serverKey)); // Generate server-first-message // Create text-based nonce as base64 encoding of a binary blob of length multiple of 3 const int nonceLenQWords = 3; uint64_t binaryNonce[nonceLenQWords]; std::unique_ptr<SecureRandom> sr(SecureRandom::create()); binaryNonce[0] = sr->nextInt64(); binaryNonce[1] = sr->nextInt64(); binaryNonce[2] = sr->nextInt64(); _nonce = clientNonce + base64::encode(reinterpret_cast<char*>(binaryNonce), sizeof(binaryNonce)); StringBuilder sb; sb << "r=" << _nonce << ",s=" << _scramCredentials.salt << ",i=" << _scramCredentials.iterationCount; std::string outputData = sb.str(); // add client-first-message-bare and server-first-message to _authMessage _authMessage = client_first_message_bare.toString() + "," + outputData; return std::make_tuple(false, std::move(outputData)); }
//----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponSpawner::MyTouch(CBasePlayer *pPlayer) { bool bSuccess = false; CTFPlayer *pTFPlayer = dynamic_cast<CTFPlayer *>(pPlayer); if ( ValidTouch( pTFPlayer ) && pTFPlayer->IsPlayerClass( TF_CLASS_MERCENARY ) ) { #ifndef DM_WEAPON_BUCKET int iSlot = m_Item.GetStaticData()->GetLoadoutSlot( TF_CLASS_MERCENARY ); CTFWeaponBase *pWeapon = (CTFWeaponBase *)pTFPlayer->GetEntityForLoadoutSlot( iSlot ); const char *pszWeaponName = m_Item.GetEntityName(); int iAmmoType = m_pWeaponInfo->iAmmoType; if ( pWeapon ) { if ( pTFPlayer->ItemsMatch( pWeapon->GetItem(), &m_Item, pWeapon ) ) { if ( pTFPlayer->GiveAmmo( pWeapon->GetInitialAmmo(), iAmmoType, true, TF_AMMO_SOURCE_AMMOPACK ) ) bSuccess = true; } else if ( !(pTFPlayer->m_nButtons & IN_ATTACK) && (pTFPlayer->m_nButtons & IN_USE || pWeapon->GetWeaponID() == TF_WEAPON_PISTOL) ) { // Drop a usable weapon pTFPlayer->DropWeapon( pWeapon ); // Check Use button, always replace pistol if ( pWeapon == pTFPlayer->GetActiveTFWeapon() ) { pWeapon->Holster(); } pTFPlayer->Weapon_Detach( pWeapon ); UTIL_Remove( pWeapon ); pWeapon = NULL; } else { pTFPlayer->m_Shared.SetDesiredWeaponIndex( m_nItemID ); } } #else CTFWeaponBase *pWeapon = pTFPlayer->Weapon_OwnsThisID( m_nWeaponID ); const char *pszWeaponName = WeaponIdToClassname( m_nWeaponID ); if ( pWeapon ) { if ( pPlayer->GiveAmmo(999, m_pWeaponInfo->iAmmoType) ) bSuccess = true; } #endif if ( !pWeapon ) { CTFWeaponBase *pNewWeapon = (CTFWeaponBase *)pTFPlayer->GiveNamedItem( pszWeaponName, 0, &m_Item ); if ( pNewWeapon ) { pPlayer->SetAmmoCount( pNewWeapon->GetInitialAmmo(), iAmmoType ); pNewWeapon->DefaultTouch( pPlayer ); pTFPlayer->m_Shared.SetDesiredWeaponIndex( -1 ); bSuccess = true; } } if ( bSuccess ) { CSingleUserRecipientFilter user( pPlayer ); user.MakeReliable(); UserMessageBegin( user, "ItemPickup" ); WRITE_STRING( GetClassname() ); MessageEnd(); pPlayer->EmitSound( "BaseCombatCharacter.AmmoPickup" ); } } return bSuccess; }
void POP::setState( State s ) { if ( s == d->state ) return; switch ( s ) { case Authorization: log( "Switching to Authorization state" ); break; case Transaction: log( "Switching to Transaction state" ); break; case Update: log( "Switching to Update state" ); break; } if ( s == Update && user() && !d->toBeDeleted.isEmpty() ) { log( "Deleting " + fn( d->toBeDeleted.count() ) + " messages" ); class PopDeleter : public EventHandler { private: User * user; Mailbox * mailbox; IntegerSet s; ::Transaction * t; Query * nms; RetentionSelector * r; Query * iq; int64 ms; public: PopDeleter( User * u, Mailbox * m, const IntegerSet & ms ) : user( u ), mailbox( m ), s( ms ), t( 0 ), nms( 0 ), r( 0 ), iq( 0 ), ms( 0 ) {} void execute() { if ( !r ) { r = new RetentionSelector( mailbox, this ); r->execute(); } if ( !t ) { t = new ::Transaction( this ); nms = new Query( "select nextmodseq from mailboxes " "where id=$1 for update", this ); nms->bind( 1, mailbox->id() ); t->enqueue( nms ); t->execute(); } if ( nms ) { if ( !r->done() ) return; if ( !nms->done() ) return; ms = nms->nextRow()->getBigint( "nextmodseq" ); nms = 0; Selector * s = new Selector; if ( r->retains() ) { Selector * n = new Selector( Selector::Not ); s->add( n ); n->add( r->retains() ); } s->add( new Selector( this->s ) ); s->simplify(); EStringList wanted; wanted.append( "mailbox" ); wanted.append( "uid" ); wanted.append( "message" ); iq = s->query( 0, mailbox, 0, this, false, &wanted, false ); int i = iq->string().find( " from " ); uint msb = s->placeHolder(); uint ub = s->placeHolder(); uint rb = s->placeHolder(); iq->setString( "insert into deleted_messages " "(mailbox,uid,message,modseq,deleted_by,reason) " + iq->string().mid( 0, i ) + ", $" + fn( msb ) +", $" + fn( ub ) + ", $" + fn( rb ) + iq->string().mid( i ) ); iq->bind( msb, ms ); iq->bind( ub, user->id() ); iq->bind( rb, "POP delete " + Scope::current()->log()->id() ); t->enqueue( iq ); t->execute(); } if ( iq ) { if ( !iq->done() ) return; if ( iq->rows() ) { // at least one message was deleted Query * q = new Query( "update mailboxes set " "nextmodseq=$1 where id=$2", this ); q->bind( 1, ms+1 ); q->bind( 2, mailbox->id() ); t->enqueue( q ); Mailbox::refreshMailboxes( t ); } iq = 0; t->commit(); } if ( !t->done() ) return; if ( t->failed() ) log( "Error deleting messages: " + t->error() ); } }; PopDeleter * pd = new PopDeleter( user(), d->session->mailbox(), d->toBeDeleted ); pd->execute(); } d->state = s; }
int main(int argc, char **argv) { struct group *gr; struct passwd *pw; int Gflag, Pflag, ch, gflag, id, nflag, pflag, rflag, uflag; const char *myname; Gflag = Pflag = gflag = nflag = pflag = rflag = uflag = 0; myname = strrchr(argv[0], '/'); myname = (myname != NULL) ? myname + 1 : argv[0]; if (strcmp(myname, "groups") == 0) { isgroups = 1; Gflag = nflag = 1; } else if (strcmp(myname, "whoami") == 0) { iswhoami = 1; uflag = nflag = 1; } while ((ch = getopt(argc, argv, (isgroups || iswhoami) ? "" : "PGgnpru")) != -1) switch(ch) { case 'G': Gflag = 1; break; case 'P': Pflag = 1; break; case 'g': gflag = 1; break; case 'n': nflag = 1; break; case 'p': pflag = 1; break; case 'r': rflag = 1; break; case 'u': uflag = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; if (iswhoami && argc > 0) usage(); switch(Gflag + Pflag + gflag + pflag + uflag) { case 1: break; case 0: if (!nflag && !rflag) break; /* FALLTHROUGH */ default: usage(); } pw = *argv ? who(*argv) : NULL; if (gflag) { id = pw ? pw->pw_gid : rflag ? getgid() : getegid(); if (nflag && (gr = getgrgid(id))) printf("%s\n", gr->gr_name); else printf("%u\n", id); exit(0); } if (uflag) { id = pw ? pw->pw_uid : rflag ? getuid() : geteuid(); if (nflag && (pw = getpwuid(id))) printf("%s\n", pw->pw_name); else printf("%u\n", id); exit(0); } if (Gflag) { group(pw, nflag); exit(0); } if (Pflag) { pline(pw); exit(0); } if (pflag) { pretty(pw); exit(0); } if (pw) user(pw); else current(); exit(0); }
HANDLE WINAPI EXP_NAME(OpenPlugin)(int OpenFrom, INT_PTR Item) { // Options.Read(); AutoUTF cline; if (OpenFrom == OPEN_PLUGINSMENU) { FarPnl pi(PANEL_ACTIVE); if (pi.IsOK()) { AutoUTF buf(MAX_PATH_LEN, L'\0'); fsf.GetCurrentDirectory(buf.capacity(), (PWSTR)buf.c_str()); if (!buf.empty()) ::PathAddBackslash((PWSTR)buf.c_str()); PluginPanelItem &PPI = pi[pi.CurrentItem()]; buf += PPI.FindData.lpwszFileName; cline = buf; } } else if (OpenFrom == OPEN_COMMANDLINE) { cline = (PCWSTR)Item; } FarList users; if (InitUsers(users)) { enum { HEIGHT = 14, WIDTH = 48, }; InitDialogItemF Items[] = { {DI_DOUBLEBOX, 3, 1, WIDTH - 4, HEIGHT - 2, 0, (PCWSTR)DlgTitle}, {DI_TEXT, 5, 2, 0, 0, 0, (PCWSTR)MUsername}, {DI_COMBOBOX, 5, 3, 42, 0, DIF_SELECTONENTRY, L""}, {DI_TEXT, 5, 4, 0, 0, 0, (PCWSTR)MPasword}, {DI_PSWEDIT, 5, 5, 42, 0, 0, L""}, {DI_CHECKBOX , 5, 6, 42, 0, 0, (PCWSTR)MRestricted}, {DI_TEXT, 0, 7, 0, 0, DIF_SEPARATOR, L""}, {DI_TEXT, 5, 8, 0, 0, 0, (PCWSTR)MCommandLine}, {DI_EDIT, 5, 9, 42, 0, DIF_HISTORY, cline.c_str()}, {DI_TEXT, 0, HEIGHT - 4, 0, 0, DIF_SEPARATOR, L""}, {DI_BUTTON, 0, HEIGHT - 3, 0, 0, DIF_CENTERGROUP, (PCWSTR)txtBtnOk}, {DI_BUTTON, 0, HEIGHT - 3, 0, 0, DIF_CENTERGROUP, (PCWSTR)txtBtnCancel}, }; size_t size = sizeofa(Items); FarDialogItem FarItems[size]; InitDialogItemsF(Items, FarItems, size); FarItems[size - 2].DefaultButton = 1; FarItems[2].ListItems = &users; FarItems[8].History = L"runas.comline"; FarDlg hDlg; if (hDlg.Init(psi.ModuleNumber, -1, -1, WIDTH, HEIGHT, L"Contents", FarItems, size)) { HRESULT err = NO_ERROR; while (true) { int ret = hDlg.Run(); if (ret > 0 && Items[ret].Data == (PCWSTR)txtBtnOk) { AutoUTF cmd(hDlg.Str(8)); if (hDlg.Check(5)) { err = ExecRestricted(cmd.c_str()); } else { AutoUTF user(hDlg.Str(2)); AutoUTF pass(hDlg.Str(4)); err = ExecAsUser(cmd.c_str(), user.c_str(), pass.c_str()); } if (err == NO_ERROR) { break; } else { PCWSTR Msg[] = {GetMsg(MError), cmd.c_str(), L"", GetMsg(txtBtnOk), }; ::SetLastError(err); psi.Message(psi.ModuleNumber, FMSG_WARNING | FMSG_ERRORTYPE, L"Contents", Msg, sizeofa(Msg), 1); } } else { break; } } } FreeUsers(users); } return INVALID_HANDLE_VALUE; }
BOOL cmd_run(IMP) { register Ship_t *rsh; register Nav_t *nav; Fleet_t fl; ULONG shNum, curNum; USHORT msc, flagRow, flagCol, flagMobil, minMobil, i; char progBuf[MAX_PROG_STEPS]; char fleet; BOOL gotOne, tooMany; /* get the number of the ship */ if (reqShip(IS, &shNum, "Run program on which ship")) { rsh = &IS->is_request.rq_u.ru_ship; server(IS, rt_readShip, shNum); gotOne = FALSE; tooMany = FALSE; if (rsh->sh_owner != IS->is_player.p_number) { user(IS, "You don't own that ship\n"); } else if (rsh->sh_type == st_m) { user(IS, "You do not need to use the 'run' command with a " "miner\n"); return FALSE; } else if (rsh->sh_course[0] == '\0') { user(IS, "Ship has no program!\n"); } else { msc = 0; /* copy the current course */ strcpy(&progBuf[0], &rsh->sh_course[0]); /* set the default for the fleet */ fleet = '*'; /* see if the ship is in a fleet */ if (rsh->sh_fleet != '*') { /* it is, so set fleet apropriately */ fleet = rsh->sh_fleet; } /* was there a fleet? */ if (fleet == '*') { /* no, so do single-ship things */ accessShip(IS, shNum); if (rsh->sh_efficiency < EFFIC_WARN) { err(IS, "that ship isn't efficient enough to navigate"); } else { IS->is_movingShipCount = 1; msc = 1; nav = &IS->is_movingShips[0]; nav->n_ship = shNum; nav->n_mobil = ((short)rsh->sh_energy) * 10; nav->n_active = TRUE; flagMobil = rsh->sh_energy; minMobil = rsh->sh_energy; flagRow = rsh->sh_row; flagCol = rsh->sh_col; decrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } else { /* yes, so set it up */ i = fleetPos(fleet); if (IS->is_player.p_fleets[i] == NO_FLEET) { log3(IS, "attempted to run a program for fleet not used " "by player ", &IS->is_player.p_name[0], ""); err(IS, "you are not using the fleet listed for the ship!" " Notify the deity!"); } else { server(IS, rt_readFleet, IS->is_player.p_fleets[i]); fl = IS->is_request.rq_u.ru_fleet; if (fl.f_count == 0) { log3(IS, "attempted to run a program for fleet " "which believed itself to be empty " "by player ", &IS->is_player.p_name[0], ""); err(IS, "fleet believes it has no ships! " "Notify the deity!"); } else { gotOne = TRUE; for (i = 0; i < fl.f_count; i++) { curNum = fl.f_ship[i]; accessShip(IS, curNum); if (rsh->sh_efficiency < EFFIC_WARN) { user(IS, getShipName(rsh->sh_type)); userN3(IS, " #", curNum, " isn't efficient enough to " "navigate.\n"); } else if (rsh->sh_planet != NO_ITEM) { user(IS, getShipName(rsh->sh_type)); userN3(IS, " #", curNum, " is on the surface of a planet\n"); } else { if (msc == 0) { flagMobil = rsh->sh_energy; minMobil = rsh->sh_energy; flagRow = rsh->sh_row; flagCol = rsh->sh_col; } if (msc == MAX_NAV_SHIPS) { if (!tooMany) { tooMany = TRUE; err(IS, "too many ships to navigate " "at once"); } } else { nav = &IS->is_movingShips[msc]; nav->n_ship = curNum; nav->n_mobil = ((short)rsh->sh_energy) * 10; nav->n_active = TRUE; msc++; IS->is_movingShipCount = msc; if (rsh->sh_energy < minMobil) { minMobil = rsh->sh_energy; } decrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } } } } } if (msc == 0) { if (gotOne) { err(IS, "no ships in that fleet can navigate"); } } else if (flagMobil == 0) { err(IS, "no energy"); } else if (!tooMany) { /* scale mobilities by 10 */ flagMobil = flagMobil * 10; minMobil = minMobil * 10; /* now actually run the program */ runNavProg(IS, &progBuf[0], &flagRow, &flagCol, &flagMobil, &minMobil); /* now remove the ships from the navlist */ for (i = 0; i < IS->is_movingShipCount; i++) { nav = &IS->is_movingShips[i]; if (nav->n_active) { curNum = nav->n_ship; server(IS, rt_lockShip, curNum); rsh->sh_energy = nav->n_mobil / 10; server(IS, rt_unlockShip, curNum); incrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } /* copy the modifief course back into the ship */ server(IS, rt_lockShip, shNum); strcpy(&rsh->sh_course[0], &progBuf[0]); server(IS, rt_unlockShip, shNum); } } return TRUE; } return FALSE; }
bool isLoggedIn() { return user(); }
void minerEmpty(IMP) { register Ship_t *rsh, *rp; ULONG shipNumber, mineNum; USHORT ore, bars; /* get the number of the miner */ if (reqShip(IS, &mineNum, "Miner to empty")) { rsh = &IS->is_request.rq_u.ru_ship; rp = &IS->is_request.rq_u.ru_shipPair[0]; (void) skipBlanks(IS); server(IS, rt_readShip, mineNum); if (rsh->sh_owner != IS->is_player.p_number) { err(IS, "you don't own that miner"); } else if (rsh->sh_type != st_m) { err(IS, "that ship is not a miner"); } /* make sure the ship is on a planet */ else if (rsh->sh_planet != NO_ITEM) { err(IS, "miner is on the surface of a planet"); return; } else { /* make sure the miner is in a ship */ if (rsh->sh_dragger == NO_ITEM) { err(IS, "miner is not inside a ship - tell system owner!"); return; } /* get the number of the ship the miner is on */ shipNumber = rsh->sh_dragger; /* update the carrying ship */ server(IS, rt_lockShip, shipNumber); updateShip(IS); server(IS, rt_unlockShip, shipNumber); /* now do the actual transfer */ server2(IS, rt_lockShipPair, mineNum, shipNumber); /* get the maximum amount of ore that may be transfered */ ore = umin(rp[0].sh_items[it_ore], (USHORT) MAX_WORK - rp[1].sh_items[it_ore]); /* remove that amount from the miner */ rp[0].sh_items[it_ore] -= ore; /* get the maximum amount of bars that may be transfered */ bars = umin(rp[0].sh_items[it_bars], (USHORT) MAX_WORK - rp[1].sh_items[it_bars]); /* remove that amount from the miner */ rp[0].sh_items[it_bars] -= bars; /* now handle the weight */ rp[0].sh_cargo -= (ore * IS->is_world.w_weight[it_ore]); rp[0].sh_cargo -= (bars * IS->is_world.w_weight[it_bars]); /* now put the items onto the carrying ship */ rp[1].sh_items[it_ore] += ore; rp[1].sh_items[it_bars] += bars; server2(IS, rt_unlockShipPair, mineNum, shipNumber); /* see if we transfered anything */ if ((ore == 0) && (bars == 0)) { user(IS, "Unable to transfer anything from that miner\n"); } else { userN3(IS, "Transfered ", ore, " units of ore "); userN3(IS, "and ", bars, " gold bars "); userN3(IS, "to ship ", shipNumber, "\n"); } /* put out the dirty ship numbers */ feShDirty(IS, mineNum); feShDirty(IS, shipNumber); } } }
//----------------------------------------------------------------------------- // Purpose: MyTouch function for the healthkit //----------------------------------------------------------------------------- bool CHealthKit::MyTouch( CBasePlayer *pPlayer ) { bool bSuccess = false; if ( ValidTouch( pPlayer ) ) { if (GetPowerupSize() == POWERUP_TINY) // TF2C tiny medkit, overheals. can't pick up if hp would exceed max { if (pPlayer->GetHealth() < pPlayer->GetMaxHealth() * (tf_max_health_boost.GetFloat() - PackRatios[GetPowerupSize()])) { if (pPlayer->TakeHealth(ceil(pPlayer->GetMaxHealth() * PackRatios[GetPowerupSize()]), DMG_IGNORE_MAXHEALTH)) { CSingleUserRecipientFilter user(pPlayer); user.MakeReliable(); UserMessageBegin(user, "ItemPickup"); WRITE_STRING(GetClassname()); MessageEnd(); if (pPlayer->GetHealth() > pPlayer->GetMaxHealth()) { EmitSound( user, entindex(), "OverhealPillRattle.Touch" ); } else { EmitSound(user, entindex(), "OverhealPillNoRattle.Touch"); } bSuccess = true; } } } else { if ( pPlayer->TakeHealth( ceil(pPlayer->GetMaxHealth() * PackRatios[GetPowerupSize()]), DMG_GENERIC ) ) bSuccess = true; CTFPlayer *pTFPlayer = ToTFPlayer( pPlayer ); Assert( pTFPlayer ); // Remove any negative conditions whether player got healed or not. if ( pTFPlayer->m_Shared.InCond( TF_COND_BURNING ) ) { pTFPlayer->m_Shared.RemoveCond( TF_COND_BURNING ); bSuccess = true; } if ( pTFPlayer->m_Shared.InCond( TF_COND_SLOWED ) ) { pTFPlayer->m_Shared.RemoveCond( TF_COND_SLOWED ); bSuccess = true; } if ( bSuccess ) { CSingleUserRecipientFilter user( pPlayer ); user.MakeReliable(); UserMessageBegin( user, "ItemPickup" ); WRITE_STRING( GetClassname() ); MessageEnd(); EmitSound( user, entindex(), TF_HEALTHKIT_PICKUP_SOUND ); } } } return bSuccess; }
int main() { user(); }
void PrivateChat::slotSend(const QString& line_) { QString line = line_; if (line.isEmpty()) return; if(line.startsWith("//")) { line = line.mid(1); } else if(line[0] == '/') { QStringList s; QString cmd(""); if(line.length() > 1) { s = line.mid(1).split(' ', QString::KeepEmptyParts); cmd = s[0].toLower(); s.pop_front(); } if(cmd == "me") { museeq->sayPrivate(user(), line); mChatPanel->append(QString::null, line); } else if(cmd == "ip" ) { if (s.empty()) museeq->mainwin()->showIPDialog(user()); else museeq->mainwin()->showIPDialog(s.join(" ")); } else if((cmd == "c" || cmd == "chat") && s.empty()) museeq->mainwin()->changeCMode(); else if(cmd == "pm" || cmd == "private") { if(! s.empty()) museeq->mainwin()->showPrivateChat(s.join(" ")); else museeq->mainwin()->changePMode(); } else if(cmd == "transfers" || cmd == "transfer") museeq->mainwin()->changeTMode(); else if(cmd == "clear") mChatPanel->clear(); else if(cmd == "s" || cmd == "search") { if(! s.empty()) museeq->mainwin()->startSearch(s.join(" ")); else museeq->mainwin()->changeSMode(); } else if(cmd == "u" || cmd == "userinfo") { if(! s.empty()) museeq->mainwin()->showUserInfo(s.join(" ")); else museeq->mainwin()->showUserInfo(user()); } else if(cmd == "b" || cmd == "browse") { if(! s.empty()) museeq->mainwin()->showBrowser(s.join(" ")); else museeq->mainwin()->showBrowser(user()); } else if(cmd == "commands") museeq->mainwin()->displayCommandsDialog(); else if(cmd == "about") museeq->mainwin()->displayAboutDialog(); else if(cmd == "help") museeq->mainwin()->displayHelpDialog(); else if(cmd == "ban" && s.empty()) museeq->addBanned(user(), ""); else if(cmd == "unban" && s.empty()) museeq->removeBanned(user()); else if(cmd == "ignore" && s.empty()) museeq->addIgnored(user(), ""); else if(cmd == "unignore" && s.empty()) museeq->removeIgnored(user()); else if(cmd == "buddy" && s.empty()) museeq->addBuddy(user(), ""); else if(cmd == "unbuddy" && s.empty()) museeq->removeBuddy(user()); else if(cmd == "trust" && s.empty()) museeq->addTrusted(user(), ""); else if(cmd == "distrust" && s.empty()) museeq->removeTrusted(user()); else if(cmd == "slap" && s.empty()) { museeq->sayPrivate(user(), "/me slaps "+user()+" around with a large trout"); mChatPanel->append(QString::null, "/me slaps "+user()+" around with a large trout"); } else if((cmd == "j" || cmd == "join") && ! s.empty()) museeq->joinRoom(s.join(" ")); else if((cmd == "jp" || cmd == "joinpriv") && ! s.empty()) // Private room museeq->joinRoom(s.join(" "), true); else if(cmd == "settings") museeq->mainwin()->changeSettings(); else if(cmd == "log") museeq->mainwin()->toggleLog(); else if(cmd == "ticker" || cmd == "tickers" || cmd == "t") museeq->mainwin()->toggleTickers(); else if(cmd == "colors" || cmd == "fonts" || cmd == "f") museeq->mainwin()->changeColors(); else if(cmd == "p" || cmd== "part" || cmd == "l" || cmd == "leave") { if(! s.empty()) museeq->leaveRoom(s.join(" ")); } else mChatPanel->entry()->setText(line); return; } museeq->sayPrivate(user(), line); QStringList lines = line.split("\n"); QStringList::iterator it, end = lines.end(); for(it = lines.begin(); it != end; ++it) { logMessage(user(), museeq->nickname(), *it); mChatPanel->append(QString::null, *it); } }
bool MainWindow::openDatabase() { bool ok; QString host, user, pw, dBase; QFile file("../UHCore/Core/config/database.yaml"); if (!file.exists()) { qDebug()<<"No database config found!!"; } if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { closeDownRequest = true; return false; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if (line.startsWith("mysql_log_user")) { user = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_password")) { pw = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_server")) { host = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_db")) { dBase = line.section(":",1,1).trimmed(); } } if (param != "BATCH") { user = QInputDialog::getText ( this, "Accompany DB", "User:"******"Accompany DB", "Password:"******"Accompany DB", "Host:",QLineEdit::Normal, host, &ok); if (!ok) { closeDownRequest = true; return false; }; dBase = QInputDialog::getText ( this, "Accompany DB", "Database:",QLineEdit::Normal, dBase, &ok); if (!ok) { closeDownRequest = true; return false; }; } QString dbUser = "******" + user + ":" + host + ":" + dBase; db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(host); db.setDatabaseName(dBase); db.setUserName(user); db.setPassword(pw); dbOpen = db.open(); if (!dbOpen) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Database error - login problem - see console log!"); msgBox.exec(); qCritical("Cannot open database: %s (%s)", db.lastError().text().toLatin1().data(), qt_error_string().toLocal8Bit().data()); return false; } qDebug() << "Database Opened"; QSqlQuery query("SELECT ExperimentalLocationId, SessionUser FROM SessionControl WHERE SessionId = 1 LIMIT 1"); if (query.next()) { experimentLocation = query.value(0).toInt(); expLocation.setNum(experimentLocation); defaultUser = query.value(1).toString(); QSqlQuery locn("select location from ExperimentalLocation where id = '" + expLocation + "' LIMIT 1"); locn.next(); dbUser += " :: Location: " + locn.value(0).toString(); QSqlQuery user("select nickname from Users where userId = '" + defaultUser + "' LIMIT 1"); user.next(); dbUser += " :: User: "******"Can find session control table!"); msgBox.exec(); closeDownRequest = true; return false; } ui->dbLabel->setText(dbUser); return true; }
void CVoiceGameMgr::UpdateMasks() { m_UpdateInterval = 0; bool bAllTalk = !!sv_alltalk.GetInt(); for(int iClient=0; iClient < m_nMaxPlayers; iClient++) { CBaseEntity *pEnt = UTIL_PlayerByIndex(iClient+1); if(!pEnt || !pEnt->IsPlayer()) continue; CBasePlayer *pPlayer = (CBasePlayer*)pEnt; CSingleUserRecipientFilter user( pPlayer ); // Request the state of their "VModEnable" cvar. if(g_bWantModEnable[iClient]) { UserMessageBegin( user, "RequestState" ); MessageEnd(); // Since this is reliable, only send it once g_bWantModEnable[iClient] = false; } CPlayerBitVec gameRulesMask; CPlayerBitVec ProximityMask; bool bProximity = false; if( g_PlayerModEnable[iClient] ) { // Build a mask of who they can hear based on the game rules. for(int iOtherClient=0; iOtherClient < m_nMaxPlayers; iOtherClient++) { CBaseEntity *pEnt = UTIL_PlayerByIndex(iOtherClient+1); if(pEnt && pEnt->IsPlayer() && (bAllTalk || m_pHelper->CanPlayerHearPlayer(pPlayer, (CBasePlayer*)pEnt, bProximity )) ) { gameRulesMask[iOtherClient] = true; ProximityMask[iOtherClient] = bProximity; } } } // If this is different from what the client has, send an update. if(gameRulesMask != g_SentGameRulesMasks[iClient] || g_BanMasks[iClient] != g_SentBanMasks[iClient]) { g_SentGameRulesMasks[iClient] = gameRulesMask; g_SentBanMasks[iClient] = g_BanMasks[iClient]; UserMessageBegin( user, "VoiceMask" ); int dw; for(dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++) { WRITE_LONG(gameRulesMask.GetDWord(dw)); WRITE_LONG(g_BanMasks[iClient].GetDWord(dw)); } WRITE_BYTE( !!g_PlayerModEnable[iClient] ); MessageEnd(); } // Tell the engine. for(int iOtherClient=0; iOtherClient < m_nMaxPlayers; iOtherClient++) { bool bCanHear = gameRulesMask[iOtherClient] && !g_BanMasks[iClient][iOtherClient]; g_pVoiceServer->SetClientListening( iClient+1, iOtherClient+1, bCanHear ); if ( bCanHear ) { g_pVoiceServer->SetClientProximity( iClient+1, iOtherClient+1, !!ProximityMask[iOtherClient] ); } } } }
message * message_register::duplicate() { return new message_register(id(), user(), pass(), mail()); }
void doMinerRep(IMP, ULONG minerNumber, register Ship_t *sh) { #ifdef DEBUG_LIB Ship_t saveSh; #endif #ifdef DEBUG_LIB if (IS->is_DEBUG) { saveSh = *sh; log3(IS, ">>> In doMinerRep", "", ""); *sh = saveSh; } #endif /* display the miner's number */ userF(IS, minerNumber, 8); user(IS, " | "); if (sh->sh_dragger == NO_ITEM) { /* the miner is on a planet */ if (sh->sh_planet == NO_ITEM) { /* should never happen */ user(IS, "******** | ?"); } else { userF(IS, sh->sh_planet, 8); user(IS, " | \x50"); } } else { userF(IS, sh->sh_dragger, 8); user(IS, " | S"); } user(IS, " | "); userF(IS, sh->sh_efficiency, 3); user(IS, " | "); userF(IS, sh->sh_items[it_ore], 5); user(IS, " | "); userF(IS, sh->sh_items[it_bars], 5); user(IS, " | "); userF(IS, IS->is_world.w_shipCargoLim[st_m] - sh->sh_cargo, 5); user(IS, " | "); userF(IS, sh->sh_energy, 5); user(IS, " | "); switch(sh->sh_weapon[0]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } switch(sh->sh_weapon[1]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } switch(sh->sh_weapon[2]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } userNL(IS); #ifdef DEBUG_LIB if (IS->is_DEBUG) { saveSh = *sh; log3(IS, "<<< Out of doMinerRep", "", ""); *sh = saveSh; } #endif }
/*! Respond to the sockets readyRead() signal by reading a line of message reply (if a full line is available). Also trigger sending more messages. */ void DeviceConnector::socketReadyRead() { // qDebug() << "socketReadyRead() - bytes:" << mSocket->bytesAvailable(); if ( !mSocket->canReadLine() ) return; QString reply; while ( mSocket->canReadLine() ) { QByteArray bytes = mSocket->readLine(); reply = QString( bytes ).trimmed(); qDebug() << "recv:" << reply; replyQueue.append( reply ); } while ( replyQueue.count() > 0 ) { reply = replyQueue.takeFirst(); if ( messageQueue.isEmpty() ) { qDebug() << "ignoring:" << reply; } else { if ( messageQueue.first()->state == WaitForWelcome && reply.startsWith( "220" )) { QRegExp user("loginname=([^;]+)"); if ( user.indexIn(reply) > -1 ) { loginName = user.cap(1); } messageQueue.first()->state = User; qDebug() << "welcome ok:" << reply; break; } else if ( messageQueue.first()->state == WaitForUserOk && reply.startsWith( "331" )) { messageQueue.first()->state = Password; qDebug() << "user ok:" << reply; break; } else if ( messageQueue.first()->state == WaitForPasswordOk && reply.startsWith( "230" )) { messageQueue.first()->state = Message; qDebug() << "pass ok:" << reply; loginDone = true; break; } else if ( messageQueue.first()->state == WaitForMessageOk ) { if ( reply.startsWith( "200" )) { messageQueue.first()->state = MessageDelivered; qDebug() << "msg ok:" << reply; } else if ( reply.startsWith( "500" )) { messageQueue.first()->state = MessageFailed; qDebug() << "msg fail:" << reply; } } else { qDebug() << "ignoring:" << reply; } } } if ( !messageQueue.isEmpty() ) QTimer::singleShot( 0, this, SLOT(processMessages()) ); }
char *doCountNavOnce(IMP, char *oPtr, char *program, USHORT *flagRow, USHORT *flagCol, USHORT *flagMobil, USHORT *minMobil) { char *bPtr, *mPtr, *ePtr, *sPtr; USHORT current, end; BOOL cont; char num1[16], num2[10], course[MAX_PROG_STEPS]; memset(num1, '\0', 16 * sizeof(char)); memset(num2, '\0', 10 * sizeof(char)); memset(course, '\0', MAX_PROG_STEPS * sizeof(char)); sPtr = program; if (program[0] == '@') { sPtr += sizeof(char); } bPtr = sPtr + sizeof(char); /* make sure that there is at least one digit */ if (*bPtr == '\0') { user(IS, "unexpected end of program\n"); rollString(bPtr - sPtr, program); return NULL; } if ((*bPtr < '0') || (*bPtr > '9')) { user(IS, "invalid character in first number of loop: '"); userC(IS, *bPtr); user(IS, "'\n"); rollString((bPtr - sPtr) + 1, program); return oPtr + (bPtr - sPtr); } mPtr = bPtr; while ((*mPtr >= '0') && (*mPtr <= '9')) { mPtr++; } if (*mPtr == '\0') { user(IS, "unexpected end of program\n"); rollString(mPtr - sPtr, program); return NULL; } /* verify that the seperator is a "," */ if (*mPtr != ',') { user(IS, "invalid seperation character: '"); userC(IS, *mPtr); user(IS, "'\n"); rollString((mPtr - sPtr) + 1, program); return oPtr + (mPtr - sPtr); } memcpy(&num1[0], bPtr, umin((mPtr - bPtr), (USHORT) 5) * sizeof(char)); mPtr++; if (*mPtr == '\0') { user(IS, "unexpected end of program\n"); rollString(mPtr - sPtr, program); return NULL; } if ((*mPtr < '0') || (*mPtr > '9')) { user(IS, "invalid character in 2nd number in loop: '"); userC(IS, *mPtr); user(IS, "'\n"); rollString((mPtr - sPtr) + 1, program); return oPtr + (mPtr - sPtr); } ePtr = mPtr; while ((*ePtr >= '0') && (*ePtr <= '9')) { ePtr++; } if (*ePtr == '\0') { user(IS, "unexpected end of program\n"); rollString(ePtr - sPtr, program); return NULL; } /* verify that we got the proper closure character */ if (*ePtr != ']') { user(IS, "invalid closure character: '"); userC(IS, *ePtr); user(IS, "'\n"); rollString((ePtr - sPtr) + 1, program); return oPtr + (ePtr - sPtr); } memcpy(&num2[0], mPtr, umin((ePtr - mPtr), (USHORT) 5) * sizeof(char)); ePtr++; /* verify that there is a valid direction following the count */ if (*ePtr == '\0') { user(IS, "unexpected end of program\n"); rollString(ePtr - sPtr, program); return NULL; } if ((*ePtr < '0') || (*ePtr > '9')) { user(IS, "invalid navigation character: '"); userC(IS, *ePtr); user(IS, "'\n"); rollString((ePtr - sPtr) + 1, program); return oPtr + (ePtr - sPtr); } current = atoi(num1); end = atoi(num2); if (current >= end) { userN2(IS, "first number (", current); userN3(IS, ") is >= other number (", end, ")\n"); rollString((ePtr - sPtr) + 1, program); return oPtr + (ePtr - sPtr); } cont = TRUE; while(cont && (current < end)) { cont = ((navOnce(IS, *ePtr, flagRow, flagCol, flagMobil, minMobil)) == m_continue); if (cont) { current++; } } /* if cont is TRUE, then must have done all desired movements */ if (cont) { current = 0; } sprintf(num1, "[%d,%d]%c", current, end, *ePtr); /* make sure that the loop is not the first thing */ if (sPtr != program) { course[0] = '@'; bPtr = &course[1]; } else { bPtr = course; } strcat(course, num1); strcat(course, ePtr + sizeof(char)); if (!cont) { strcpy(program, course); return NULL; } mPtr = &course[3]; while(*mPtr != ']') { mPtr++; } mPtr++; rollString((mPtr - bPtr) + 1, course); strcpy(program, course); return oPtr + (ePtr - sPtr); }
PlayersWindow::PlayersWindow(QWidget *parent, int expireDays) : QWidget (parent) { setAttribute(Qt::WA_DeleteOnClose, true); resize(726, this->height()); QGridLayout *mylayout = new QGridLayout(this); mytable = new QCompactTable(0,7); mytable->setShowGrid(true); mylayout->addWidget(mytable,0,0,1,6); QMap<int, QString> authgrade; authgrade[0] = "User"; authgrade[1] = "Mod"; authgrade[2] = "Admin"; authgrade[3] = "Owner"; QStringList headers; headers << "Player" << "Authority" << "Banned Status" << "Registered" << "IP" << "Last Appearance" << "Expires In"; mytable->setHorizontalHeaderLabels(headers); QSqlQuery q; q.setForwardOnly(true); q.exec("select count(*) from trainers"); if (q.next()) { mytable->setRowCount(q.value(0).toInt()); } q.exec("select name, auth, banned, hash, ip, laston, ban_expire_time from trainers order by name asc"); int i = 0; while(q.next()) { QTableWidgetItem *witem = new QTableWidgetItem(q.value(0).toString()); mytable->setItem(i, 0, witem); witem = new QTableWidgetItem(authgrade[q.value(1).toInt()]); mytable->setItem(i, 1, witem); QString bannedString = "Banned"; int expiration = q.value(6).toInt() - QDateTime::currentDateTimeUtc().toTime_t(); if(expiration < 0) { if (q.value(6).toInt() != 0) bannedString = "Expires on Login"; } else { if(expiration < 60) { if(expiration == 1) { bannedString.append(QString(" (%1 second)").arg(expiration)); } else { bannedString.append(QString(" (%2 seconds)").arg(expiration)); } } else { if(expiration >= 60) { expiration = expiration / 60; if(expiration == 1) { bannedString.append(QString(" (%1 minute)").arg(expiration)); } else { bannedString.append(QString(" (%2 minutes)").arg(expiration)); } } } } witem = new QTableWidgetItem(q.value(2).toBool() ? bannedString : "Fine"); mytable->setItem(i, 2, witem); witem = new QTableWidgetItem(q.value(3).toString().length() > 0 ? "Yes" : "No"); mytable->setItem(i, 3, witem); witem = new QTableWidgetItem(q.value(4).toString()); mytable->setItem(i, 4, witem); witem = new QTableWidgetItem(q.value(5).toString()); mytable->setItem(i, 5, witem); witem = new QTableWidgetItem(QString::number(expireDays - QDate::fromString(q.value(5).toString(), "yyyy-MM-dd").daysTo(QDate::currentDate())) + " Days"); mytable->setItem(i, 6, witem); i++; } mytable->sortByColumn(0, Qt::AscendingOrder); mytable->setSortingEnabled(true); QPushButton *_authority = new QPushButton(tr("&Authority")); QMenu *m = new QMenu(_authority); m->addAction(tr("User"), this, SLOT(user())); m->addAction(tr("Moderator"), this, SLOT(mod())); m->addAction(tr("Administrator"), this, SLOT(admin())); m->addAction(tr("Owner"), this, SLOT(owner())); _authority->setMenu(m); QPushButton *_ban = new QPushButton(tr("&Ban")); QPushButton *_unban = new QPushButton(tr("U&nban")); QPushButton *_clpass = new QPushButton(tr("&Clear Password")); mylayout->addWidget(_authority,1,0); mylayout->addWidget(_ban,1,2); mylayout->addWidget(_unban,1,3); mylayout->addWidget(_clpass,1,4); if (mytable->rowCount() == 0) return; connect(_ban,SIGNAL(clicked()),SLOT(ban())); connect(_unban,SIGNAL(clicked()),SLOT(unban())); connect(_clpass,SIGNAL(clicked()),SLOT(clpass())); }
void runNavProg(IMP, char *program, USHORT *flagRow, USHORT *flagCol, USHORT *flagMobil, USHORT *minMobil) { BOOL cont, needRoll; char progBuf[MAX_PROG_STEPS]; char *sPtr; sPtr = &progBuf[0]; /* copy initial program, since we will be munging it up */ /* and we only want to loop through the program once */ strcpy(sPtr, program); /* skip past any loop characters */ if (*sPtr == '@') { sPtr++; } /* loop until end of program or no more fuel */ cont = TRUE; while (cont) { /* need to roll string unless told otherwise */ needRoll = TRUE; /* look for a "plain" navigation direction */ if ((*sPtr >= '0') && (*sPtr <= '9')) { /* execute movement command */ cont = ((navOnce(IS, *sPtr, flagRow, flagCol, flagMobil, minMobil)) == m_continue); /* don't roll if it returns bad */ needRoll = cont; } else if ((*sPtr >= 'a') && (*sPtr <= 'z')) { /* execute an action */ cont = handleAction(IS, *sPtr); /* don't roll if it returns bad */ needRoll = cont; } else if (*sPtr == '[') { /* try and execute a counted movement command */ needRoll = FALSE; sPtr = doCountNavOnce(IS, sPtr, program, flagRow, flagCol, flagMobil, minMobil); if (sPtr == NULL) { cont = FALSE; } } else { /* some other character */ if (*sPtr == '\0') { /* end of line */ cont = FALSE; } else { /* is it an embedded loop character? */ if (*sPtr != '@') { /* nope */ user(IS, "invalid character in program: '"); userC(IS, *sPtr); user(IS, "'\n"); } else { needRoll = FALSE; } } } /* if not at end of line, roll by one */ if (needRoll && (*sPtr != '\0')) { rollString(1, program); } /* look at next character */ sPtr++; } }
exception( hresult Result = user(), const ierrorinfo &ErrorInfo = ierrorinfo()): Result(Result), ErrorInfo(ErrorInfo) { }
void JabberProtocol::ParseRosterList(XMLEntity *iq_roster_entity) { XMLEntity *entity = iq_roster_entity; // go one level deep to query if (entity->Child("query")) { entity = entity->Child("query"); } else { return; } JRoster::Instance()->Lock(); for (int i=0; i<entity->CountChildren(); ++i) { // handle the item child if (!strcasecmp(entity->Child(i)->Name(), "item")) { if (!entity->Child(i)->Attribute("jid")) { continue; } // make a user UserID user(string(entity->Child(i)->Attribute("jid"))); // set subscription status if (entity->Child(i)->Attribute("subscription")) { //fprintf(stderr, "User %s subscription status: %s.\n", user.JabberHandle().c_str(), // entity->Child(i)->Attribute("subscription")); user.SetSubscriptionStatus(string(entity->Child(i)->Attribute("subscription"))); } // set user type if (entity->Child(i)->Child("group") && !strcasecmp(entity->Child(i)->Child("group")->Data(), "#Conference")) { user.SetUsertype(UserID::CONFERENCE); user.SetOnlineStatus(UserID::CONF_STATUS); fprintf(stderr, "Roster item %s (conference).\n", user.JabberHandle().c_str()); } else { user.SetUsertype(UserID::JABBER); fprintf(stderr, "Roster item %s.\n", user.JabberHandle().c_str()); } // set friendly name if (entity->Child(i)->Attribute("name")) { user.SetFriendlyName(string(entity->Child(i)->Attribute("name"))); } UserID *roster_user = JRoster::Instance()->FindUser(&user); if (roster_user) { // Roster item updating never changes Online Status // Online Status can only be changed by <presence> messages if (!user.SubscriptionStatus().empty()) { if (user.SubscriptionStatus() == "remove") { JRoster::Instance()->RemoveUser(roster_user); fprintf(stderr, "User %s was removed from roster.\n", roster_user->JabberHandle().c_str()); continue; } else { if (user.SubscriptionStatus() == "from" && (roster_user->OnlineStatus() == UserID::UNKNOWN)) { roster_user->SetOnlineStatus(UserID::OFFLINE); } else if (user.SubscriptionStatus() == "none" && roster_user->OnlineStatus() == UserID::OFFLINE) { roster_user->SetOnlineStatus(UserID::UNKNOWN); } fprintf(stderr, "User %s in roster just updated subscription from '%s' to '%s'.\n", roster_user->JabberHandle().c_str(), user.SubscriptionStatus().c_str(), roster_user->SubscriptionStatus().c_str()); roster_user->SetSubscriptionStatus(user.SubscriptionStatus()); } } if (!user.FriendlyName().empty()) roster_user->SetFriendlyName(user.FriendlyName()); } else { // Handle Roster Item from Server that is not in our Roster List // Determine OFFLINE or UNKNOWN nodes to initial placing if (user.UserType() == UserID::JABBER) { if (user.SubscriptionStatus() == "none") user.SetOnlineStatus(UserID::UNKNOWN); else user.SetOnlineStatus(UserID::OFFLINE); } roster_user = new UserID(string(entity->Child(i)->Attribute("jid"))); roster_user->SetSubscriptionStatus(user.SubscriptionStatus()); roster_user->SetFriendlyName(user.FriendlyName()); roster_user->SetOnlineStatus(user.OnlineStatus()); roster_user->SetUsertype(user.UserType()); JRoster::Instance()->AddRosterUser(roster_user); fprintf(stderr, "User %s was added to roster subscription='%s'.\n", roster_user->JabberHandle().c_str(), roster_user->SubscriptionStatus().c_str()); } } } JRoster::Instance()->Unlock(); JRoster::Instance()->RefreshRoster(); }