bool KUser::CheckUser(unsigned long ip,unsigned gid) { KUser_int_map::iterator it; m_lock.Lock(); it=m_user.find(ip); if(it!=m_user.end()){ if(gid==ALLUSER||gid==(*it).second.user_id){ // printf("gid==0 or gid == loginid\n"); goto done; } for(int i=0;i<(*it).second.gids->size();i++){ if(gid==(*it).second.gids->operator[](i)){ // printf("loginid in group gid.\n"); goto done; } } } m_lock.Unlock(); return false; done: (*it).second.last_active_time=time(NULL); m_lock.Unlock(); return true; }
UploadDialog::UploadDialog(/*Engine *engine,*/ QWidget *parent) : KDialog(parent) { m_entry = NULL; // popuplate dialog with stuff QWidget* _mainWidget = new QWidget(this); setMainWidget(_mainWidget); setupUi(_mainWidget); setCaption(i18n("Share Hot New Stuff")); setButtons(Ok | Cancel); setDefaultButton(Cancel); setModal(false); mTitleWidget->setText(i18nc("Program name followed by 'Add On Uploader'", "%1 Add-On Uploader", KGlobal::activeComponent().aboutData()->programName())); mTitleWidget->setPixmap(KIcon(KGlobal::activeComponent().aboutData()->programIconName())); QStringList languagecodes = KGlobal::locale()->languageList(); for (int i = 0; i < languagecodes.count(); i++) { QString languagecode = languagecodes.at(i); QString language = KGlobal::locale()->languageCodeToName(languagecode); mLanguageCombo->addItem(language); m_languages.insert(language, languagecode); } KUser user; mAuthorEdit->setText(user.property(KUser::FullName).toString()); connect(this, SIGNAL(okClicked()), this, SLOT(slotOk())); }
bool KUser::operator ==(const KUser& user) const { if (isValid() != user.isValid()) return false; if (isValid()) return uid() == user.uid(); else return true; }
void SelfTestDialog::testRootUser() { KUser user; if ( user.isSuperUser() ) { report( Error, ki18n( "Akonadi was started as root" ), ki18n( "Running Internet-facing applications as root/administrator exposes you to many security risks. MySQL, used by this Akonadi installation, will not allow itself to run as root, to protect you from these risks." ) ); } else { report( Success, ki18n( "Akonadi is not running as root" ), ki18n( "Akonadi is not running as a root/administrator user, which is the recommended setup for a secure system." ) ); } }
int main(int argc, char **argv) { KAboutData aboutData("kdepasswd", 0, ki18n("KDE passwd"), KDE_VERSION_STRING, ki18n("Changes a UNIX password."), KAboutData::License_Artistic, ki18n("Copyright (c) 2000 Geert Jansen")); aboutData.addAuthor(ki18n("Geert Jansen"), ki18n("Maintainer"), "*****@*****.**"); aboutData.setProgramIconName( "preferences-desktop-user-password" ); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineOptions options; options.add("+[user]", ki18n("Change password of this user")); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KUniqueApplication::start()) { kDebug() << "kdepasswd is already running"; return 2; } KUniqueApplication app; KUser ku; QString user; bool bRoot = ku.isSuperUser(); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->count()) user = args->arg(0); /* You must be able to run "kdepasswd loginName" */ if ( !user.isEmpty() && user!=KUser().loginName() && !bRoot) { KMessageBox::sorry(0, i18n("You need to be root to change the password of other users.")); return 1; } QByteArray oldpass; if (!bRoot) { int result = KDEpasswd1Dialog::getPassword(oldpass); if (result != KDEpasswd1Dialog::Accepted) return 1; } KDEpasswd2Dialog *dlg = new KDEpasswd2Dialog(oldpass, user.toLocal8Bit()); dlg->exec(); if (dlg->result() == KDEpasswd2Dialog::Rejected) return 1; return 0; }
//===================Main function================= int main(int argc, char* argv) { int buf_len; char main_buffer[MAX_MAIN_BUFFER]; KConnectionManager::Initialize(); KConnectionManager km = KConnectionManager(); KConnection* main_con = km.create_con(MAIN_PORT); KLobby lobby = KLobby(&km); //Handle signal signal(SIGINT, TerminalHandler); //Debug memory leak #ifdef MEMORY_LEAK _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW ); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif//MEMORY_LEAK sockaddr remote_addr; while(Running) {//MainLoop km.check(1,0); if (main_con->has_data()) { //Reinitialize buffer and len buf_len = MAX_MAIN_BUFFER; memset(main_buffer, 0, sizeof(main_buffer)); memset(&remote_addr, 0, sizeof(remote_addr)); //Recv data buf_len = main_con->recv_data(main_buffer, buf_len, false); main_con->get_raddr(&remote_addr); if (strncmp("PING", main_buffer, MAX_MAIN_BUFFER) == 0) {//Echo message //TODO:Send "PONG" } else if (strncmp("HELLO", main_buffer, 5) == 0) { if (strncmp("0.83", main_buffer + 5, MAX_MAIN_BUFFER - 5) == 0) { //XXX:Rember to delete user and game at list KUser* nuser = lobby.new_user(); __PRINT("Port:%d\n", nuser->get_port()); snprintf(main_buffer, MAX_MAIN_BUFFER, "HELLOD00D%i", nuser->get_port()); main_con->send(main_buffer,sizeof(main_buffer)); } else { //Version error //TODO:Send "VER" } } else { printf("Got an unexcept data:%s", main_buffer); } __PRINT("Recvdata:%s\n", main_buffer); } lobby.tick(); } km.Release(); return 0; }
bool KUser::CheckLogin(const char *user) { KUser_int_map::iterator it; m_lock.Lock(); for(it=m_user.begin();it!=m_user.end();it++){ if((*it).second.user->user==user){ m_lock.Unlock(); return true; } } m_lock.Unlock(); return false; }
/* 根据ID寻找用户 */ KUser* KLobby::findUserByID(unsigned short id) { KList<KUser*>::iterator it = m_userlist.begin(); KUser* result = NULL; KListNode<KUser*>* p_node; while ((p_node = it.next()) !=0) { result = p_node->m_data; if (result->GetID() == id) { break; } } return result; }
void KUser::SaveAll() { unsigned stay_time=0; KUser_int_map::iterator it; int now_time=time(NULL); m_lock.Lock(); for(it=m_user.begin();it!=m_user.end();it++){ (*it).second.user->total_time+=now_time-(*it).second.login_time; } m_lock.Unlock(); Save(); }
SessionWidget::SessionWidget( QGraphicsItem * parent, Qt::WindowFlags wFlags) : QGraphicsWidget ( parent, wFlags) { this->setFocusPolicy(Qt::ClickFocus); m_signalMapper = new QSignalMapper(this); QGraphicsLinearLayout* mainLayout = new QGraphicsLinearLayout(Qt::Vertical); mainLayout->setSpacing(0); mainLayout->addStretch(); this->setLayout(mainLayout); connect( m_signalMapper, SIGNAL(mapped(int)), this, SLOT(slotSwitchSession(int))); Q_ASSERT(mainLayout->count() == 0); //Cache the icon pixmaps QSize iconSize = QSize(KIconLoader::SizeSmallMedium, KIconLoader::SizeSmallMedium); SessList sessions; KDisplayManager manager; manager.localSessions(sessions); QList<QGraphicsWidget*> entries; foreach(SessEnt session, sessions) { QPixmap pixmap; KUser user (session.user); if (!user.isValid()) continue; if (session.tty) continue; Plasma::IconWidget* entry = createButton(this); pixmap = getUserIcon(user); entry->setIcon(pixmap); QString username = getUsername(false, user); entry->setText(username); connect(entry, SIGNAL(clicked()), m_signalMapper, SLOT(map())); m_signalMapper->setMapping(entry, session.vt); if (session.self) entry->setEnabled(false); entries << entry; }
Settings AddBackupWizard::settings() { KUser user; QString source = user.homeDir(); QString destination = page2->destination(); QString relativeDest = page2->relativeDestination(); QString deviceUDI = page2->deviceUDI(); QStringList excludedDirs = page3->excludedDirs(); QString mountPoint = page2->mountPoint(); Settings settings (source, deviceUDI, relativeDest, excludedDirs); settings.setMount( mountPoint); return settings; }
std::string KUser::ListLoginUser() { stringstream s; int now_time=time(NULL); // std::vector<std::string> user_list; s << "<table><tr><td></td><td>user</td><td>from</td><td>stay time(sec)</td><td>inactive time(sec)</td></tr>\n"; KUser_int_map::iterator it; m_lock.Lock(); for(it=m_user.begin();it!=m_user.end();it++){ s << "<tr><td><a href=/killloginuser?user="******">kill</a></td><td>" << (*it).second.user->user << "</td><td>" << make_ip((*it).first) << "</td><td>" << (now_time-(*it).second.login_time) << "</td><td>" << (now_time-(*it).second.last_active_time) << "</td></tr>\n"; } // user_list.push_back((*it).second.user); m_lock.Unlock(); s << "</table>"; return s.str(); }
void HomeImpl::createHomeEntry(KIO::UDSEntry &entry, const KUser &user) { kdDebug() << "HomeImpl::createHomeEntry" << endl; entry.clear(); QString full_name = user.loginName(); if (!user.fullName().isEmpty()) { full_name = user.fullName()+" ("+user.loginName()+")"; } full_name = KIO::encodeFileName( full_name ); addAtom(entry, KIO::UDS_NAME, 0, full_name); addAtom(entry, KIO::UDS_URL, 0, "home:/"+user.loginName()); addAtom(entry, KIO::UDS_FILE_TYPE, S_IFDIR); addAtom(entry, KIO::UDS_MIME_TYPE, 0, "inode/directory"); QString icon_name = "folder_home2"; if (user.uid()==m_effectiveUid) { icon_name = "folder_home"; } addAtom(entry, KIO::UDS_ICON_NAME, 0, icon_name); KURL url; url.setPath(user.homeDir()); entry += extractUrlInfos(url); }
bool KUser::ForceLogout(const char *user,bool use_lock) { KUser_int_map::iterator it; if(use_lock) m_lock.Lock(); for(it=m_user.begin();it!=m_user.end();it++){ if((*it).second.user->user==user){ (*it).second.user->state=0; klog(RUN_LOG,"Force logou user %s success\n",(*it).second.user->user.c_str()); m_user.erase(it); m_lock.Unlock(); return true; } } if(use_lock) m_lock.Unlock(); return false; }
int KUser::Logout(unsigned long ip) { unsigned stay_time=0; KUser_int_map::iterator it; m_lock.Lock(); it=m_user.find(ip); if(it==m_user.end()){ m_lock.Unlock(); return stay_time; } stay_time=time(NULL)-(*it).second.login_time; //m_user.total_time+=stay_time; (*it).second.user->total_time+=stay_time; (*it).second.user->state=0;//set the user logout klog(RUN_LOG,"user %s logout success\n",(*it).second.user->user.c_str()); m_user.erase(it); m_lock.Unlock(); return stay_time; }
QStringList PortListener::processServiceTemplate(const QString &a) { QStringList l; QValueVector<KInetInterface> v = KInetInterface::getAllInterfaces(false); QValueVector<KInetInterface>::Iterator it = v.begin(); while (it != v.end()) { KInetSocketAddress *address = (*(it++)).address(); if (!address) continue; QString hostName = address->nodeName(); KUser u; QString x = a; // replace does not work in const QString. Why?? l.append(x.replace(QRegExp("%h"), KServiceRegistry::encodeAttributeValue(hostName)) .replace(QRegExp("%p"), QString::number(m_port)) .replace(QRegExp("%u"), KServiceRegistry::encodeAttributeValue(u.loginName())) .replace(QRegExp("%i"), KServiceRegistry::encodeAttributeValue(m_uuid)) .replace(QRegExp("%f"), KServiceRegistry::encodeAttributeValue(u.fullName()))); } return l; }
bool KUser::Login(unsigned long ip,const char *user) { UserInfo m_userinfo; if(!LoadUserInfo(user,m_userinfo)) return false; LoginUserInfo tmpuser; stringmap::iterator it2; KUser_int_map::iterator it; tmpuser.login_time=time(NULL); tmpuser.last_active_time=tmpuser.login_time; //tmpuser.user=user; m_root_lock.Lock(); it2=m_all_user.find(user); if(it2==m_all_user.end()){ m_root_lock.Unlock(); return false; } (*it2).second->last_ip=ip; (*it2).second->state=1;//set the user login (*it2).second->last_time=tmpuser.login_time; tmpuser.user=(*it2).second; tmpuser.user_id=(*it2).second->uid; tmpuser.gids=&(*it2).second->gids; m_root_lock.Unlock(); if(tmpuser.user_id==0){ klog(ERR_LOG,"user %s user_id is 0,It may be a bug in %s:%d\n",user,__FILE__,__LINE__); return false; } m_lock.Lock(); it=m_user.find(ip); if(it!=m_user.end()) goto err; ForceLogout(user,false); m_user[ip]=tmpuser; m_lock.Unlock(); char ips[18]; make_ip(ip,ips); klog(RUN_LOG,"user %s(%d) login from %s success\n",user,tmpuser.user_id,ips); return true; err: m_lock.Unlock(); return false; }
unsigned KUser::CheckLogin(unsigned long ip,LoginUserInfo *user_info) { unsigned uid=0; KUser_int_map::iterator it; m_lock.Lock(); it=m_user.find(ip); if(it!=m_user.end()){ uid=(*it).second.user_id; if(user_info!=NULL){ //memcpy(user_info,&(*it).second,sizeof(LoginUserInfo)); user_info->user_id=uid; user_info->user=(*it).second.user; user_info->login_time=(*it).second.login_time; //user_info->last_ip=(*it).second.last_ip; } } m_lock.Unlock(); return uid; }
void KUser::FlushLoginUser() { if(conf.user_time_out<=0) return; int now_time=time(NULL); KUser_int_map::iterator it; m_lock.Lock(); for(it=m_user.begin();it!=m_user.end();){ if(now_time-(*it).second.last_active_time>conf.user_time_out){ #ifndef _WIN32 (*it).second.user->state=0; m_user.erase(it); it++; #else it=m_user.erase(it); #endif }else{ it++; } } m_lock.Unlock(); }
void KUser::UpdateSendRecvSize(unsigned long ip,int send_size,int recv_size,unsigned uid) { assert(send_size>=0 && recv_size>=0); KUser_int_map::iterator it; if(uid>STARTUID){ map<unsigned,UserInfo *>::iterator it2; m_root_lock.Lock(); it2=m_all_user2.find(uid); if(it2!=m_all_user2.end()){ (*it2).second->send_size+=send_size; (*it2).second->recv_size+=recv_size; } m_root_lock.Unlock(); return; } m_lock.Lock(); it=m_user.find(ip); if(it!=m_user.end()){ (*it).second.user->send_size+=send_size; (*it).second.user->recv_size+=recv_size; } m_lock.Unlock(); }
void SetupServer::readSettings() { m_folderArchiveSettingPage->loadSettings(); m_ui->accountName->setText(m_parentResource->name()); m_oldResourceName = m_ui->accountName->text(); KUser *currentUser = new KUser(); KEMailSettings esetting; m_ui->imapServer->setText( !m_parentResource->settings()->imapServer().isEmpty() ? m_parentResource->settings()->imapServer() : esetting.getSetting(KEMailSettings::InServer)); m_ui->portSpin->setValue(m_parentResource->settings()->imapPort()); m_ui->userName->setText( !m_parentResource->settings()->userName().isEmpty() ? m_parentResource->settings()->userName() : currentUser->loginName()); const QString safety = m_parentResource->settings()->safety(); int i = 0; if (safety == QLatin1String("SSL")) { i = KIMAP::LoginJob::AnySslVersion; } else if (safety == QLatin1String("STARTTLS")) { i = KIMAP::LoginJob::TlsV1; } else { i = KIMAP::LoginJob::Unencrypted; } QAbstractButton *safetyButton = m_ui->safeImapGroup->button(i); if (safetyButton) { safetyButton->setChecked(true); } populateDefaultAuthenticationOptions(); i = m_parentResource->settings()->authentication(); qCDebug(IMAPRESOURCE_LOG) << "read IMAP auth mode: " << authenticationModeString((MailTransport::Transport::EnumAuthenticationType::type) i); setCurrentAuthMode(m_ui->authenticationCombo, (MailTransport::Transport::EnumAuthenticationType::type) i); i = m_parentResource->settings()->alternateAuthentication(); setCurrentAuthMode(m_ui->authenticationAlternateCombo, (MailTransport::Transport::EnumAuthenticationType::type) i); bool rejected = false; const QString password = m_parentResource->settings()->password(&rejected); if (rejected) { m_ui->password->setEnabled(false); KMessageBox::information(Q_NULLPTR, i18n("Could not access KWallet. " "If you want to store the password permanently then you have to " "activate it. If you do not " "want to use KWallet, check the box below, but note that you will be " "prompted for your password when needed."), i18n("Do not use KWallet"), QStringLiteral("warning_kwallet_disabled")); } else { m_ui->password->insert(password); } m_ui->subscriptionEnabled->setChecked(m_parentResource->settings()->subscriptionEnabled()); m_ui->checkInterval->setValue(m_parentResource->settings()->intervalCheckTime()); m_ui->disconnectedModeEnabled->setChecked(m_parentResource->settings()->disconnectedModeEnabled()); m_ui->managesieveCheck->setChecked(m_parentResource->settings()->sieveSupport()); m_ui->sameConfigCheck->setChecked(m_parentResource->settings()->sieveReuseConfig()); m_ui->sievePortSpin->setValue(m_parentResource->settings()->sievePort()); m_ui->alternateURL->setText(m_parentResource->settings()->sieveAlternateUrl()); m_vacationFileName = m_parentResource->settings()->sieveVacationFilename(); Akonadi::Collection trashCollection(m_parentResource->settings()->trashCollection()); if (trashCollection.isValid()) { Akonadi::CollectionFetchJob *fetchJob = new Akonadi::CollectionFetchJob(trashCollection, Akonadi::CollectionFetchJob::Base, this); connect(fetchJob, &Akonadi::CollectionFetchJob::collectionsReceived, this, &SetupServer::targetCollectionReceived); } else { Akonadi::SpecialMailCollectionsRequestJob *requestJob = new Akonadi::SpecialMailCollectionsRequestJob(this); connect(requestJob, &Akonadi::SpecialMailCollectionsRequestJob::result, this, &SetupServer::localFolderRequestJobFinished); requestJob->requestDefaultCollection(Akonadi::SpecialMailCollections::Trash); requestJob->start(); } m_ui->useDefaultIdentityCheck->setChecked(m_parentResource->settings()->useDefaultIdentity()); if (!m_ui->useDefaultIdentityCheck->isChecked()) { m_identityCombobox->setCurrentIdentity(m_parentResource->settings()->accountIdentity()); } m_ui->enableMailCheckBox->setChecked(m_parentResource->settings()->intervalCheckEnabled()); if (m_ui->enableMailCheckBox->isChecked()) { m_ui->checkInterval->setValue(m_parentResource->settings()->intervalCheckTime()); } else { m_ui->checkInterval->setEnabled(false); } m_ui->autoExpungeCheck->setChecked(m_parentResource->settings()->automaticExpungeEnabled()); if (m_vacationFileName.isEmpty()) { m_vacationFileName = QStringLiteral("kmail-vacation.siv"); } m_ui->customUsername->setText(m_parentResource->settings()->sieveCustomUsername()); rejected = false; const QString customPassword = m_parentResource->settings()->sieveCustomPassword(&rejected); if (rejected) { m_ui->customPassword->setEnabled(false); KMessageBox::information(Q_NULLPTR, i18n("Could not access KWallet. " "If you want to store the password permanently then you have to " "activate it. If you do not " "want to use KWallet, check the box below, but note that you will be " "prompted for your password when needed."), i18n("Do not use KWallet"), QStringLiteral("warning_kwallet_disabled")); } else { m_ui->customPassword->insert(customPassword); } const QString sieverCustomAuth(m_parentResource->settings()->sieveCustomAuthentification()); if (sieverCustomAuth == QLatin1String("ImapUserPassword")) { m_ui->imapUserPassword->setChecked(true); } else if (sieverCustomAuth == QLatin1String("NoAuthentification")) { m_ui->noAuthentification->setChecked(true); } else if (sieverCustomAuth == QLatin1String("CustomUserPassword")) { m_ui->customUserPassword->setChecked(true); } delete currentUser; }
static int startApp() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // Stop daemon and exit? if (args->isSet("s")) { KDEsuClient client; if (client.ping() == -1) { kError(1206) << "Daemon not running -- nothing to stop\n"; exit(1); } if (client.stopServer() != -1) { kDebug(1206) << "Daemon stopped\n"; exit(0); } kError(1206) << "Could not stop daemon\n"; exit(1); } QString icon; if ( args->isSet("i")) icon = args->getOption("i"); bool prompt = true; if ( args->isSet("d")) prompt = false; // Get target uid QByteArray user = args->getOption("u").toLocal8Bit(); QByteArray auth_user = user; struct passwd *pw = getpwnam(user); if (pw == 0L) { kError(1206) << "User " << user << " does not exist\n"; exit(1); } bool other_uid = (getuid() != pw->pw_uid); bool change_uid = other_uid; if (!change_uid) { char *cur_user = getenv("USER"); if (!cur_user) cur_user = getenv("LOGNAME"); change_uid = (!cur_user || user != cur_user); } // If file is writeable, do not change uid QString file = args->getOption("f"); if (other_uid && !file.isEmpty()) { if (file.at(0) != '/') { KStandardDirs dirs; file = dirs.findResource("config", file); if (file.isEmpty()) { kError(1206) << "Config file not found: " << file << "\n"; exit(1); } } QFileInfo fi(file); if (!fi.exists()) { kError(1206) << "File does not exist: " << file << "\n"; exit(1); } change_uid = !fi.isWritable(); } // Get priority/scheduler QString tmp = args->getOption("p"); bool ok; int priority = tmp.toInt(&ok); if (!ok || (priority < 0) || (priority > 100)) { KCmdLineArgs::usageError(i18n("Illegal priority: %1", tmp)); exit(1); } int scheduler = SuProcess::SchedNormal; if (args->isSet("r")) scheduler = SuProcess::SchedRealtime; if ((priority > 50) || (scheduler != SuProcess::SchedNormal)) { change_uid = true; auth_user = "******"; } // Get command if (args->isSet("c")) { command = args->getOption("c").toLocal8Bit(); // Accepting additional arguments here is somewhat weird, // but one can conceive use cases: have a complex command with // redirections and additional file names which need to be quoted // safely. } else { if( args->count() == 0 ) { KCmdLineArgs::usageError(i18n("No command specified.")); exit(1); } } for (int i = 0; i < args->count(); i++) { command += ' '; command += QFile::encodeName(KShell::quoteArg(args->arg(i))); } // Don't change uid if we're don't need to. if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } // Check for daemon and start if necessary bool just_started = false; bool have_daemon = true; KDEsuClient client; if (!client.isServerSGID()) { kWarning(1206) << "Daemon not safe (not sgid), not using it.\n"; have_daemon = false; } else if (client.ping() == -1) { if (client.startServer() == -1) { kWarning(1206) << "Could not start daemon, reduced functionality.\n"; have_daemon = false; } just_started = true; } // Try to exec the command with kdesud. bool keep = !args->isSet("n") && have_daemon; bool terminal = args->isSet("t"); bool withIgnoreButton = args->isSet("ignorebutton"); int winid = -1; bool attach = args->isSet("attach"); if(attach) { winid = args->getOption("attach").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. if(!attach) kWarning(1206) << "Specified winid to attach to is not a valid number"; } else if(args->isSet("embed")) { /* KDialog originally used --embed for attaching the dialog box. However this is misleading and so we changed to --attach. * For consistancy, we silently map --embed to --attach */ attach = true; winid = args->getOption("embed").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. if(!attach) kWarning(1206) << "Specified winid to attach to is not a valid number"; } QList<QByteArray> env; QByteArray options; env << ( "DESKTOP_STARTUP_ID=" + kapp->startupId()); if (pw->pw_uid) { // Only propagate KDEHOME for non-root users, // root uses KDEROOTHOME // Translate the KDEHOME of this user to the new user. QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir()); if (kdeHome[0] != '/') kdeHome.prepend("~/"); else kdeHome.clear(); // Use default env << ("KDEHOME="+ QFile::encodeName(kdeHome)); } KUser u; env << (QByteArray) ("KDESU_USER="******"rlimit(): " << ERR << "\n"; exit(1); } // Read configuration KConfigGroup config(KGlobal::config(), "Passwords"); int timeout = config.readEntry("Timeout", defTimeout); // Check if we need a password SuProcess proc; proc.setUser(auth_user); int needpw = proc.checkNeedPassword(); if (needpw < 0) { QString err = i18n("Su returned with an error.\n"); KMessageBox::error(0L, err); exit(1); } if (needpw == 0) { keep = 0; kDebug() << "Don't need password!!\n"; } // Start the dialog QString password; if (needpw) { #ifdef Q_WS_X11 KStartupInfoId id; id.initId( kapp->startupId()); KStartupInfoData data; data.setSilent( KStartupInfoData::Yes ); KStartupInfo::sendChange( id, data ); #endif KDEsuDialog dlg(user, auth_user, keep && !terminal, icon, withIgnoreButton); if (prompt) dlg.addCommentLine(i18n("Command:"), QFile::decodeName(command)); if (defKeep) dlg.setKeepPassword(true); if ((priority != 50) || (scheduler != SuProcess::SchedNormal)) { QString prio; if (scheduler == SuProcess::SchedRealtime) prio += i18n("realtime: "); prio += QString("%1/100").arg(priority); if (prompt) dlg.addCommentLine(i18n("Priority:"), prio); } //Attach dialog #ifdef Q_WS_X11 if(attach) KWindowSystem::setMainWindow(&dlg, (WId)winid); #endif int ret = dlg.exec(); if (ret == KDEsuDialog::Rejected) { #ifdef Q_WS_X11 KStartupInfo::sendFinish( id ); #endif exit(1); } if (ret == KDEsuDialog::AsUser) change_uid = false; password = dlg.password(); keep = dlg.keepPassword(); #ifdef Q_WS_X11 data.setSilent( KStartupInfoData::No ); KStartupInfo::sendChange( id, data ); #endif } // Some events may need to be handled (like a button animation) kapp->processEvents(); // Run command if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } else if (keep && have_daemon) { client.setPass(password.toLocal8Bit(), timeout); client.setPriority(priority); client.setScheduler(scheduler); int result = client.exec(command, user, options, env); if (result == 0) { result = client.exitCode(); return result; } } else { SuProcess proc; proc.setTerminal(terminal); proc.setErase(true); proc.setUser(user); proc.setEnvironment(env); proc.setPriority(priority); proc.setScheduler(scheduler); proc.setCommand(command); int result = proc.exec(password.toLocal8Bit()); return result; } return -1; }
HomeImpl::HomeImpl() { KUser user; m_effectiveUid = user.uid(); }
bool KStandardDirs::addCustomized(KConfig *config) { if (addedCustoms && !d->checkRestrictions) // there are already customized entries return false; // we just quit and hope they are the right ones // save the numbers of config directories. If this changes, // we will return true to give KConfig a chance to reparse uint configdirs = resourceDirs("config").count(); // Remember original group QString oldGroup = config->group(); if (!addedCustoms) { // We only add custom entries once addedCustoms = true; // reading the prefixes in QString group = QString::fromLatin1("Directories"); config->setGroup(group); QString kioskAdmin = config->readEntry("kioskAdmin"); if (!kioskAdmin.isEmpty() && !kde_kiosk_admin) { int i = kioskAdmin.find(':'); QString user = kioskAdmin.left(i); QString host = kioskAdmin.mid(i+1); KUser thisUser; char hostname[ 256 ]; hostname[ 0 ] = '\0'; if (!gethostname( hostname, 255 )) hostname[sizeof(hostname)-1] = '\0'; if ((user == thisUser.loginName()) && (host.isEmpty() || (host == hostname))) { kde_kiosk_admin = true; } } bool readProfiles = true; if (kde_kiosk_admin && !QCString(getenv("KDE_KIOSK_NO_PROFILES")).isEmpty()) readProfiles = false; QString userMapFile = config->readEntry("userProfileMapFile"); QString profileDirsPrefix = config->readEntry("profileDirsPrefix"); if (!profileDirsPrefix.isEmpty() && !profileDirsPrefix.endsWith("/")) profileDirsPrefix.append('/'); QStringList profiles; if (readProfiles) profiles = lookupProfiles(userMapFile); QString profile; bool priority = false; while(true) { config->setGroup(group); QStringList list = config->readListEntry("prefixes"); for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { addPrefix(*it, priority); addXdgConfigPrefix(*it+"/etc/xdg", priority); addXdgDataPrefix(*it+"/share", priority); } // If there are no prefixes defined, check if there is a directory // for this profile under <profileDirsPrefix> if (list.isEmpty() && !profile.isEmpty() && !profileDirsPrefix.isEmpty()) { QString dir = profileDirsPrefix + profile; addPrefix(dir, priority); addXdgConfigPrefix(dir+"/etc/xdg", priority); addXdgDataPrefix(dir+"/share", priority); } // iterating over all entries in the group Directories // to find entries that start with dir_$type QMap<QString, QString> entries = config->entryMap(group); for (QMap<QString, QString>::ConstIterator it2 = entries.begin(); it2 != entries.end(); it2++) { QString key = it2.key(); if (key.startsWith("dir_")) { // generate directory list, there may be more than 1. QStringList dirs = QStringList::split(',', *it2); QStringList::Iterator sIt(dirs.begin()); QString resType = key.mid(4, key.length()); for (; sIt != dirs.end(); ++sIt) { addResourceDir(resType.latin1(), *sIt, priority); } } } if (profiles.isEmpty()) break; profile = profiles.back(); group = QString::fromLatin1("Directories-%1").arg(profile); profiles.pop_back(); priority = true; } } // Process KIOSK restrictions. if (!kde_kiosk_admin || QCString(getenv("KDE_KIOSK_NO_RESTRICTIONS")).isEmpty()) { config->setGroup("KDE Resource Restrictions"); QMap<QString, QString> entries = config->entryMap("KDE Resource Restrictions"); for (QMap<QString, QString>::ConstIterator it2 = entries.begin(); it2 != entries.end(); it2++) { QString key = it2.key(); if (!config->readBoolEntry(key, true)) { d->restrictionsActive = true; d->restrictions.insert(key.latin1(), &d->restrictionsActive); // Anything will do dircache.remove(key.latin1()); } } } config->setGroup(oldGroup); // check if the number of config dirs changed bool configDirsChanged = (resourceDirs("config").count() != configdirs); // If the config dirs changed, we check kiosk restrictions again. d->checkRestrictions = configDirsChanged; // return true if the number of config dirs changed: reparse config file return configDirsChanged; }
bool KatePrinter::print (KateDocument *doc) { QPrinter printer; readSettings(printer); // docname is now always there, including the right Untitled name printer.setDocName(doc->documentName()); KatePrintTextSettings *kpts = new KatePrintTextSettings; KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter; KatePrintLayout *kpl = new KatePrintLayout; QList<QWidget*> tabs; tabs << kpts; tabs << kphf; tabs << kpl; QWidget *parentWidget=doc->widget(); if ( !parentWidget ) parentWidget=QApplication::activeWindow(); QScopedPointer<QPrintDialog> printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget)); if ( doc->activeView()->selection() ) { printer.setPrintRange(QPrinter::Selection); printDialog->setOption(QAbstractPrintDialog::PrintSelection, true); } if ( printDialog->exec() ) { writeSettings(printer); KateRenderer renderer(doc, doc->activeKateView()); renderer.config()->setSchema (kpl->colorScheme()); renderer.setPrinterFriendly(true); QPainter paint( &printer ); /* * We work in tree cycles: * 1) initialize variables and retrieve print settings * 2) prepare data according to those settings * 3) draw to the printer */ uint pdmWidth = printer.width(); uint pdmHeight = printer.height(); int y = 0; uint xstart = 0; // beginning point for painting lines uint lineCount = 0; uint maxWidth = pdmWidth; int headerWidth = pdmWidth; int startCol = 0; int endCol = 0; bool pageStarted = true; int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page) // Text Settings Page bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection); bool useGuide = kpts->printGuide(); bool printLineNumbers = kpts->printLineNumbers(); uint lineNumberWidth( 0 ); // Header/Footer Page QFont headerFont(kphf->font()); // used for header/footer bool useHeader = kphf->useHeader(); QColor headerBgColor(kphf->headerBackground()); QColor headerFgColor(kphf->headerForeground()); uint headerHeight( 0 ); // further init only if needed QStringList headerTagList; // do bool headerDrawBg = false; // do bool useFooter = kphf->useFooter(); QColor footerBgColor(kphf->footerBackground()); QColor footerFgColor(kphf->footerForeground()); uint footerHeight( 0 ); // further init only if needed QStringList footerTagList; // do bool footerDrawBg = false; // do // Layout Page renderer.config()->setSchema( kpl->colorScheme() ); bool useBackground = kpl->useBackground(); bool useBox = kpl->useBox(); int boxWidth(kpl->boxWidth()); QColor boxColor(kpl->boxColor()); int innerMargin = useBox ? kpl->boxMargin() : 6; // Post initialization int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight); uint currentPage( 1 ); uint lastline = doc->lastLine(); // necessary to print selection only uint firstline( 0 ); const int fontHeight = renderer.fontHeight(); KTextEditor::Range selectionRange; /* * Now on for preparations... * during preparations, variable names starting with a "_" means * those variables are local to the enclosing block. */ { if ( selectionOnly ) { // set a line range from the first selected line to the last selectionRange = doc->activeView()->selectionRange(); firstline = selectionRange.start().line(); lastline = selectionRange.end().line(); lineCount = firstline; } if ( printLineNumbers ) { // figure out the horiizontal space required QString s( QString("%1 ").arg( doc->lines() ) ); s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers // FIXME calculate which is actually the widest... lineNumberWidth = renderer.currentFontMetrics().width( s ); // a small space between the line numbers and the text int _adj = renderer.currentFontMetrics().width( "5" ); // adjust available width and set horizontal start point for data maxWidth -= (lineNumberWidth + _adj); xstart += lineNumberWidth + _adj; } if ( useHeader || useFooter ) { // Set up a tag map // This retrieves all tags, ued or not, but // none of theese operations should be expensive, // and searcing each tag in the format strings is avoided. QDateTime dt = QDateTime::currentDateTime(); QMap<QString,QString> tags; KUser u (KUser::UseRealUserID); tags["u"] = u.loginName(); tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate); tags["D"] = KGlobal::locale()->formatDateTime(dt, KLocale::LongDate); tags["h"] = KGlobal::locale()->formatTime(dt.time(), false); tags["y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate); tags["Y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate); tags["f"] = doc->url().fileName(); tags["U"] = doc->url().prettyUrl(); if ( selectionOnly ) { QString s( i18n("(Selection of) ") ); tags["f"].prepend( s ); tags["U"].prepend( s ); } QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%<TAG>" if (useHeader) { headerDrawBg = kphf->useHeaderBackground(); headerHeight = QFontMetrics( headerFont ).height(); if ( useBox || headerDrawBg ) headerHeight += innerMargin * 2; else headerHeight += 1 + QFontMetrics( headerFont ).leading(); headerTagList = kphf->headerFormat(); QMutableStringListIterator it(headerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!headerBgColor.isValid()) headerBgColor = Qt::lightGray; if (!headerFgColor.isValid()) headerFgColor = Qt::black; } if (useFooter) { footerDrawBg = kphf->useFooterBackground(); footerHeight = QFontMetrics( headerFont ).height(); if ( useBox || footerDrawBg ) footerHeight += 2*innerMargin; else footerHeight += 1; // line only footerTagList = kphf->footerFormat(); QMutableStringListIterator it(footerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!footerBgColor.isValid()) footerBgColor = Qt::lightGray; if (!footerFgColor.isValid()) footerFgColor = Qt::black; // adjust maxheight, so we can know when/where to print footer maxHeight -= footerHeight; } } // if ( useHeader || useFooter ) if ( useBackground ) { if ( ! useBox ) { xstart += innerMargin; maxWidth -= innerMargin * 2; } } if ( useBox ) { if (!boxColor.isValid()) boxColor = Qt::black; if (boxWidth < 1) // shouldn't be pssible no more! boxWidth = 1; // set maxwidth to something sensible maxWidth -= ( ( boxWidth + innerMargin ) * 2 ); xstart += boxWidth + innerMargin; // maxheight too.. maxHeight -= boxWidth; } else boxWidth = 0; // now that we know the vertical amount of space needed, // it is possible to calculate the total number of pages // if needed, that is if any header/footer tag contains "%P". if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() ) { kDebug(13020)<<"'%P' found! calculating number of pages..."; int pageHeight = maxHeight; if ( useHeader ) pageHeight -= ( headerHeight + innerMargin ); if ( useFooter ) pageHeight -= innerMargin; const int linesPerPage = pageHeight / fontHeight; // kDebug() << "Lines per page:" << linesPerPage; // calculate total layouted lines in the document int totalLines = 0; // TODO: right now ignores selection printing for (int i = firstline; i <= lastline; ++i) { KateLineLayoutPtr rangeptr(new KateLineLayout(doc)); rangeptr->setLine(i); renderer.layoutLine(rangeptr, (int)maxWidth, false); totalLines += rangeptr->viewLineCount(); } int totalPages = (totalLines / linesPerPage) + ((totalLines % linesPerPage) > 0 ? 1 : 0); // kDebug() << "_______ pages:" << (totalLines / linesPerPage); // kDebug() << "________ rest:" << (totalLines % linesPerPage); // TODO: add space for guide if required // if ( useGuide ) // _lt += (guideHeight + (fontHeight /2)) / fontHeight; // substitute both tag lists QString re("%P"); QStringList::Iterator it; for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); } } // end prepare block /* On to draw something :-) */ while ( lineCount <= lastline ) { startCol = 0; endCol = 0; if ( y + fontHeight > maxHeight ) { kDebug(13020)<<"Starting new page,"<<lineCount<<"lines up to now."; printer.newPage(); paint.resetTransform(); currentPage++; pageStarted = true; y=0; } if ( pageStarted ) { if ( useHeader ) { paint.setPen(headerFgColor); paint.setFont(headerFont); if ( headerDrawBg ) paint.fillRect(0, 0, headerWidth, headerHeight, headerBgColor); if (headerTagList.count() == 3) { int valign = ( (useBox||headerDrawBg||useBackground) ? Qt::AlignVCenter : Qt::AlignTop ); int align = valign|Qt::AlignLeft; int marg = ( useBox || headerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = headerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, 0, headerWidth-(marg*2), headerHeight, align, s); align = valign|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } if ( ! ( headerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate header from contents { paint.drawLine( 0, headerHeight-1, headerWidth, headerHeight-1 ); //y += 1; now included in headerHeight } y += headerHeight + innerMargin; } if ( useFooter ) { paint.setPen(footerFgColor); if ( ! ( footerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate footer from contents paint.drawLine( 0, maxHeight + innerMargin - 1, headerWidth, maxHeight + innerMargin - 1 ); if ( footerDrawBg ) paint.fillRect(0, maxHeight+innerMargin+boxWidth, headerWidth, footerHeight, footerBgColor); if (footerTagList.count() == 3) { int align = Qt::AlignVCenter|Qt::AlignLeft; int marg = ( useBox || footerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = footerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, maxHeight+innerMargin, headerWidth-(marg*2), footerHeight, align, s); align = Qt::AlignVCenter|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } } // done footer if ( useBackground ) { // If we have a box, or the header/footer has backgrounds, we want to paint // to the border of those. Otherwise just the contents area. int _y = y, _h = maxHeight - y; if ( useBox ) { _y -= innerMargin; _h += 2 * innerMargin; } else { if ( headerDrawBg ) { _y -= innerMargin; _h += innerMargin; } if ( footerDrawBg ) { _h += innerMargin; } } paint.fillRect( 0, _y, pdmWidth, _h, renderer.config()->backgroundColor()); } if ( useBox ) { paint.setPen(QPen(boxColor, boxWidth)); paint.drawRect(0, 0, pdmWidth, pdmHeight); if (useHeader) paint.drawLine(0, headerHeight, headerWidth, headerHeight); else y += innerMargin; if ( useFooter ) // drawline is not trustable, grr. paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor ); } if ( useGuide && currentPage == 1 ) { // FIXME - this may span more pages... // draw a box unless we have boxes, in which case we end with a box line int _ystart = y; QString _hlName = doc->highlight()->name(); QList<KateExtendedAttribute::Ptr> _attributes; // list of highlight attributes for the legend doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes); KateAttributeList _defaultAttributes; KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes ); QColor _defaultPen = _defaultAttributes.at(0)->foreground().color(); paint.setPen(_defaultPen); int _marg = 0; if ( useBox ) _marg += (2*boxWidth) + (2*innerMargin); else { if ( useBackground ) _marg += 2*innerMargin; _marg += 1; y += 1 + innerMargin; } // draw a title string QFont _titleFont = renderer.config()->font(); _titleFont.setBold(true); paint.setFont( _titleFont ); QRect _r; paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y), Qt::AlignTop|Qt::AlignHCenter, i18n("Typographical Conventions for %1", _hlName ), &_r ); int _w = pdmWidth - (_marg*2) - (innerMargin*2); int _x = _marg + innerMargin; y += _r.height() + innerMargin; paint.drawLine( _x, y, _x + _w, y ); y += 1 + innerMargin; int _widest( 0 ); foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest); int _guideCols = _w/( _widest + innerMargin ); // draw attrib names using their styles int _cw = _w/_guideCols; int _i(0); _titleFont.setUnderline(true); QString _currentHlName; foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) { QString _hl = attribute->name().section(':',0,0); QString _name = attribute->name().section(':',1,1); if ( _hl != _hlName && _hl != _currentHlName ) { _currentHlName = _hl; if ( _i%_guideCols ) y += fontHeight; y += innerMargin; paint.setFont(_titleFont); paint.setPen(_defaultPen); paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") ); y += fontHeight; _i = 0; } KTextEditor::Attribute _attr = *_defaultAttributes[attribute->defaultStyleIndex()]; _attr += *attribute; paint.setPen( _attr.foreground().color() ); paint.setFont( _attr.font() ); if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) { QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name); _rect.moveTo(_x + ((_i%_guideCols)*_cw), y); paint.fillRect(_rect, _attr.background() ); } paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name ); _i++; if ( _i && ! ( _i%_guideCols ) ) y += fontHeight; } if ( _i%_guideCols ) y += fontHeight;// last row not full // draw a box around the legend paint.setPen ( _defaultPen ); if ( useBox ) paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor ); else { _marg -=1; paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin ); } y += ( useBox ? boxWidth : 1 ) + (innerMargin*2); } // useGuide paint.translate(xstart,y); pageStarted = false; } // pageStarted; move on to contents:)
bool KUser::operator !=(const KUser& user) const { return (uid() != user.uid()) || (uid() == uid_t(-1)); }
bool KUser::operator==(const KUser &user) const { if (!isValid() || !user.isValid()) return false; return EqualSid(d->sid, user.d->sid); }
bool KShortUriFilter::filterUri( KUriFilterData& data ) const { /* * Here is a description of how the shortURI deals with the supplied * data. First it expands any environment variable settings and then * deals with special shortURI cases. These special cases are the "smb:" * URL scheme which is very specific to KDE, "#" and "##" which are * shortcuts for man:/ and info:/ protocols respectively. It then handles * local files. Then it checks to see if the URL is valid and one that is * supported by KDE's IO system. If all the above checks fails, it simply * lookups the URL in the user-defined list and returns without filtering * if it is not found. TODO: the user-defined table is currently only manually * hackable and is missing a config dialog. */ KUrl url = data.uri(); QString cmd = data.typedString(); // WORKAROUND: Allow the use of '@' in the username component of a URL since // other browsers such as firefox in their infinite wisdom allow such blatant // violations of RFC 3986. BR# 69326/118413. if (cmd.count(QLatin1Char('@')) > 1) { const int lastIndex = cmd.lastIndexOf(QLatin1Char('@')); // Percent encode all but the last '@'. QString encodedCmd = QUrl::toPercentEncoding(cmd.left(lastIndex), ":/"); encodedCmd += cmd.mid(lastIndex); KUrl u (encodedCmd); if (u.isValid()) { cmd = encodedCmd; url = u; } } const bool isMalformed = !url.isValid(); QString protocol = url.protocol(); kDebug(7023) << cmd; // Fix misparsing of "foo:80", QUrl thinks "foo" is the protocol and "80" is the path. // However, be careful not to do that for valid hostless URLs, e.g. file:///foo! if (!protocol.isEmpty() && url.host().isEmpty() && !url.path().isEmpty() && cmd.contains(':') && !KProtocolInfo::protocols().contains(protocol)) { protocol.clear(); } //kDebug(7023) << "url=" << url << "cmd=" << cmd << "isMalformed=" << isMalformed; if (!isMalformed && (protocol.length() == 4) && (protocol != QLatin1String("http")) && (protocol[0]=='h') && (protocol[1]==protocol[2]) && (protocol[3]=='p')) { // Handle "encrypted" URLs like: h++p://www.kde.org url.setProtocol( QLatin1String("http")); setFilteredUri( data, url); setUriType( data, KUriFilterData::NetProtocol ); return true; } // TODO: Make this a bit more intelligent for Minicli! There // is no need to make comparisons if the supplied data is a local // executable and only the argument part, if any, changed! (Dawit) // You mean caching the last filtering, to try and reuse it, to save stat()s? (David) const QString starthere_proto = QL1S("start-here:"); if (cmd.indexOf(starthere_proto) == 0 ) { setFilteredUri( data, KUrl("system:/") ); setUriType( data, KUriFilterData::LocalDir ); return true; } // Handle MAN & INFO pages shortcuts... const QString man_proto = QL1S("man:"); const QString info_proto = QL1S("info:"); if( cmd[0] == '#' || cmd.indexOf( man_proto ) == 0 || cmd.indexOf( info_proto ) == 0 ) { if( cmd.left(2) == QL1S("##") ) cmd = QL1S("info:/") + cmd.mid(2); else if ( cmd[0] == '#' ) cmd = QL1S("man:/") + cmd.mid(1); else if ((cmd==info_proto) || (cmd==man_proto)) cmd+='/'; setFilteredUri( data, KUrl( cmd )); setUriType( data, KUriFilterData::Help ); return true; } // Detect UNC style (aka windows SMB) URLs if ( cmd.startsWith( QLatin1String( "\\\\") ) ) { // make sure path is unix style cmd.replace('\\', '/'); cmd.prepend( QLatin1String( "smb:" ) ); setFilteredUri( data, KUrl( cmd )); setUriType( data, KUriFilterData::NetProtocol ); return true; } bool expanded = false; // Expanding shortcut to HOME URL... QString path; QString ref; QString query; QString nameFilter; if (KUrl::isRelativeUrl(cmd) && QDir::isRelativePath(cmd)) { path = cmd; //kDebug(7023) << "path=cmd=" << path; } else { if (url.isLocalFile()) { //kDebug(7023) << "hasRef=" << url.hasRef(); // Split path from ref/query // but not for "/tmp/a#b", if "a#b" is an existing file, // or for "/tmp/a?b" (#58990) if( ( url.hasRef() || !url.query().isEmpty() ) && !url.path().endsWith(QL1S("/")) ) // /tmp/?foo is a namefilter, not a query { path = url.path(); ref = url.ref(); //kDebug(7023) << "isLocalFile set path to " << stringDetails( path ); //kDebug(7023) << "isLocalFile set ref to " << stringDetails( ref ); query = url.query(); if (path.isEmpty() && url.hasHost()) path = '/'; } else { path = cmd; //kDebug(7023) << "(2) path=cmd=" << path; } } } if( path[0] == '~' ) { int slashPos = path.indexOf('/'); if( slashPos == -1 ) slashPos = path.length(); if( slashPos == 1 ) // ~/ { path.replace ( 0, 1, QDir::homePath() ); } else // ~username/ { const QString userName (path.mid( 1, slashPos-1 )); KUser user (userName); if( user.isValid() && !user.homeDir().isEmpty()) { path.replace (0, slashPos, user.homeDir()); } else { if (user.isValid()) { setErrorMsg(data, i18n("<qt><b>%1</b> does not have a home folder.</qt>", userName)); } else { setErrorMsg(data, i18n("<qt>There is no user called <b>%1</b>.</qt>", userName)); } setUriType( data, KUriFilterData::Error ); // Always return true for error conditions so // that other filters will not be invoked !! return true; } } expanded = true; } else if ( path[0] == '$' ) { // Environment variable expansion. if ( sEnvVarExp.indexIn( path ) == 0 ) { QByteArray exp = qgetenv( path.mid( 1, sEnvVarExp.matchedLength() - 1 ).toLocal8Bit().data() ); if(! exp.isNull()) { path.replace( 0, sEnvVarExp.matchedLength(), QString::fromLocal8Bit(exp.constData()) ); expanded = true; } } } if ( expanded || cmd.startsWith( '/' ) ) { // Look for #ref again, after $ and ~ expansion (testcase: $QTDIR/doc/html/functions.html#s) // Can't use KUrl here, setPath would escape it... const int pos = path.indexOf('#'); if ( pos > -1 ) { const QString newPath = path.left( pos ); if ( QFile::exists( newPath ) ) { ref = path.mid( pos + 1 ); path = newPath; //kDebug(7023) << "Extracted ref: path=" << path << " ref=" << ref; } } } bool isLocalFullPath = (!path.isEmpty() && path[0] == '/'); // Checking for local resource match... // Determine if "uri" is an absolute path to a local resource OR // A local resource with a supplied absolute path in KUriFilterData const QString abs_path = data.absolutePath(); const bool canBeAbsolute = (protocol.isEmpty() && !abs_path.isEmpty()); const bool canBeLocalAbsolute = (canBeAbsolute && abs_path[0] =='/' && !isMalformed); bool exists = false; /*kDebug(7023) << "abs_path=" << abs_path << "protocol=" << protocol << "canBeAbsolute=" << canBeAbsolute << "canBeLocalAbsolute=" << canBeLocalAbsolute << "isLocalFullPath=" << isLocalFullPath;*/ KDE_struct_stat buff; if ( canBeLocalAbsolute ) { QString abs = QDir::cleanPath( abs_path ); // combine absolute path (abs_path) and relative path (cmd) into abs_path int len = path.length(); if( (len==1 && path[0]=='.') || (len==2 && path[0]=='.' && path[1]=='.') ) path += '/'; //kDebug(7023) << "adding " << abs << " and " << path; abs = QDir::cleanPath(abs + '/' + path); //kDebug(7023) << "checking whether " << abs << " exists."; // Check if it exists if( KDE::stat( abs, &buff ) == 0 ) { path = abs; // yes -> store as the new cmd exists = true; isLocalFullPath = true; } } if (isLocalFullPath && !exists && !isMalformed) { exists = ( KDE::stat( path, &buff ) == 0 ); if ( !exists ) { // Support for name filter (/foo/*.txt), see also KonqMainWindow::detectNameFilter // If the app using this filter doesn't support it, well, it'll simply error out itself int lastSlash = path.lastIndexOf( '/' ); if ( lastSlash > -1 && path.indexOf( ' ', lastSlash ) == -1 ) // no space after last slash, otherwise it's more likely command-line arguments { QString fileName = path.mid( lastSlash + 1 ); QString testPath = path.left( lastSlash + 1 ); if ( ( fileName.indexOf( '*' ) != -1 || fileName.indexOf( '[' ) != -1 || fileName.indexOf( '?' ) != -1 ) && KDE::stat( testPath, &buff ) == 0 ) { nameFilter = fileName; //kDebug(7023) << "Setting nameFilter to " << nameFilter; path = testPath; exists = true; } } } } //kDebug(7023) << "path =" << path << " isLocalFullPath=" << isLocalFullPath << " exists=" << exists; if( exists ) { KUrl u; u.setPath(path); //kDebug(7023) << "ref=" << stringDetails(ref) << " query=" << stringDetails(query); u.setRef(ref); u.setQuery(query); if (!KAuthorized::authorizeUrlAction( QLatin1String("open"), KUrl(), u)) { // No authorization, we pretend it's a file will get // an access denied error later on. setFilteredUri( data, u ); setUriType( data, KUriFilterData::LocalFile ); return true; } // Can be abs path to file or directory, or to executable with args bool isDir = S_ISDIR( buff.st_mode ); if( !isDir && access ( QFile::encodeName(path).data(), X_OK) == 0 ) { //kDebug(7023) << "Abs path to EXECUTABLE"; setFilteredUri( data, u ); setUriType( data, KUriFilterData::Executable ); return true; } // Open "uri" as file:/xxx if it is a non-executable local resource. if( isDir || S_ISREG( buff.st_mode ) ) { //kDebug(7023) << "Abs path as local file or directory"; if ( !nameFilter.isEmpty() ) u.setFileName( nameFilter ); setFilteredUri( data, u ); setUriType( data, ( isDir ) ? KUriFilterData::LocalDir : KUriFilterData::LocalFile ); return true; } // Should we return LOCAL_FILE for non-regular files too? kDebug(7023) << "File found, but not a regular file nor dir... socket?"; } if( data.checkForExecutables()) { // Let us deal with possible relative URLs to see // if it is executable under the user's $PATH variable. // We try hard to avoid parsing any possible command // line arguments or options that might have been supplied. QString exe = removeArgs( cmd ); //kDebug(7023) << "findExe with" << exe; if (!KStandardDirs::findExe( exe ).isNull() ) { //kDebug(7023) << "EXECUTABLE exe=" << exe; setFilteredUri( data, KUrl::fromPath( exe )); // check if we have command line arguments if( exe != cmd ) setArguments(data, cmd.right(cmd.length() - exe.length())); setUriType( data, KUriFilterData::Executable ); return true; } } // Process URLs of known and supported protocols so we don't have // to resort to the pattern matching scheme below which can possibly // slow things down... if ( !isMalformed && !isLocalFullPath && !protocol.isEmpty() ) { //kDebug(7023) << "looking for protocol " << protocol; if ( KProtocolInfo::isKnownProtocol( protocol ) ) { setFilteredUri( data, url ); if ( protocol == QL1S("man") || protocol == QL1S("help") ) setUriType( data, KUriFilterData::Help ); else setUriType( data, KUriFilterData::NetProtocol ); return true; } } // Short url matches if ( !cmd.contains( ' ' ) ) { // Okay this is the code that allows users to supply custom matches for // specific URLs using Qt's regexp class. This is hard-coded for now. // TODO: Make configurable at some point... Q_FOREACH(const URLHint& hint, m_urlHints) { if (hint.regexp.indexIn(cmd) == 0) { //kDebug(7023) << "match - prepending" << (*it).prepend; const QString cmdStr = hint.prepend + cmd; KUrl url(cmdStr); if (KProtocolInfo::isKnownProtocol(url)) { setFilteredUri( data, url ); setUriType( data, hint.type ); return true; } } } // No protocol and not malformed means a valid short URL such as kde.org or // [email protected]. However, it might also be valid only because it lacks // the scheme component, e.g. www.kde,org (illegal ',' before 'org'). The // check below properly deciphers the difference between the two and sends // back the proper result. if (protocol.isEmpty() && isPotentialShortURL(cmd)) { QString urlStr = data.defaultUrlScheme(); if (urlStr.isEmpty()) urlStr = m_strDefaultUrlScheme; const int index = urlStr.indexOf(QL1C(':')); if (index == -1 || !KProtocolInfo::isKnownProtocol(urlStr.left(index))) urlStr += QL1S("://"); urlStr += cmd; KUrl url (urlStr); if (url.isValid()) { setFilteredUri(data, url); setUriType(data, KUriFilterData::NetProtocol); } else if (KProtocolInfo::isKnownProtocol(url.protocol())) { setFilteredUri(data, data.uri()); setUriType(data, KUriFilterData::Error); } return true; } }
static int startApp() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // Stop daemon and exit? if (args->isSet("s")) { KDEsuClient client; if (client.ping() == -1) { kdError(1206) << "Daemon not running -- nothing to stop\n"; exit(1); } if (client.stopServer() != -1) { kdDebug(1206) << "Daemon stopped\n"; exit(0); } kdError(1206) << "Could not stop daemon\n"; exit(1); } QString icon; if ( args->isSet("i")) icon = args->getOption("i"); bool prompt = true; if ( args->isSet("d")) prompt = false; // Get target uid QCString user = args->getOption("u"); QCString auth_user = user; struct passwd *pw = getpwnam(user); if (pw == 0L) { kdError(1206) << "User " << user << " does not exist\n"; exit(1); } bool change_uid = (getuid() != pw->pw_uid); // If file is writeable, do not change uid QString file = QFile::decodeName(args->getOption("f")); if (change_uid && !file.isEmpty()) { if (file.at(0) != '/') { KStandardDirs dirs; dirs.addKDEDefaults(); file = dirs.findResource("config", file); if (file.isEmpty()) { kdError(1206) << "Config file not found: " << file << "\n"; exit(1); } } QFileInfo fi(file); if (!fi.exists()) { kdError(1206) << "File does not exist: " << file << "\n"; exit(1); } change_uid = !fi.isWritable(); } // Get priority/scheduler QCString tmp = args->getOption("p"); bool ok; int priority = tmp.toInt(&ok); if (!ok || (priority < 0) || (priority > 100)) { KCmdLineArgs::usage(i18n("Illegal priority: %1").arg(tmp)); exit(1); } int scheduler = SuProcess::SchedNormal; if (args->isSet("r")) scheduler = SuProcess::SchedRealtime; if ((priority > 50) || (scheduler != SuProcess::SchedNormal)) { change_uid = true; auth_user = "******"; } // Get command if (args->isSet("c")) { command = args->getOption("c"); for (int i=0; i<args->count(); i++) { QString arg = QFile::decodeName(args->arg(i)); KRun::shellQuote(arg); command += " "; command += QFile::encodeName(arg); } } else { if( args->count() == 0 ) { KCmdLineArgs::usage(i18n("No command specified.")); exit(1); } command = args->arg(0); for (int i=1; i<args->count(); i++) { QString arg = QFile::decodeName(args->arg(i)); KRun::shellQuote(arg); command += " "; command += QFile::encodeName(arg); } } // Don't change uid if we're don't need to. if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } // Check for daemon and start if necessary bool just_started = false; bool have_daemon = true; KDEsuClient client; if (!client.isServerSGID()) { kdWarning(1206) << "Daemon not safe (not sgid), not using it.\n"; have_daemon = false; } else if (client.ping() == -1) { if (client.startServer() == -1) { kdWarning(1206) << "Could not start daemon, reduced functionality.\n"; have_daemon = false; } just_started = true; } // Try to exec the command with kdesud. bool keep = !args->isSet("n") && have_daemon; bool terminal = args->isSet("t"); bool new_dcop = args->isSet("newdcop"); bool withIgnoreButton = args->isSet("ignorebutton"); QCStringList env; QCString options; env << ( "DESKTOP_STARTUP_ID=" + kapp->startupId()); if (pw->pw_uid) { // Only propagate KDEHOME for non-root users, // root uses KDEROOTHOME // Translate the KDEHOME of this user to the new user. QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir()); if (kdeHome[0] != '/') kdeHome.prepend("~/"); else kdeHome=QString::null; // Use default env << ("KDEHOME="+ QFile::encodeName(kdeHome)); } KUser u; env << (QCString) ("KDESU_USER="******"KDESYCOCA="+QFile::encodeName(locateLocal("cache", "ksycoca")); env << ksycoca; options += "xf"; // X-only, dcop forwarding enabled. } if (keep && !terminal && !just_started) { client.setPriority(priority); client.setScheduler(scheduler); int result = client.exec(command, user, options, env); if (result == 0) { result = client.exitCode(); return result; } } // Set core dump size to 0 because we will have // root's password in memory. struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 0; if (setrlimit(RLIMIT_CORE, &rlim)) { kdError(1206) << "rlimit(): " << ERR << "\n"; exit(1); } // Read configuration KConfig *config = KGlobal::config(); config->setGroup("Passwords"); int timeout = config->readNumEntry("Timeout", defTimeout); // Check if we need a password SuProcess proc; proc.setUser(auth_user); int needpw = proc.checkNeedPassword(); if (needpw < 0) { QString err = i18n("Su returned with an error.\n"); KMessageBox::error(0L, err); exit(1); } if (needpw == 0) { keep = 0; kdDebug() << "Don't need password!!\n"; } // Start the dialog QCString password; if (needpw) { KStartupInfoId id; id.initId( kapp->startupId()); KStartupInfoData data; data.setSilent( KStartupInfoData::Yes ); KStartupInfo::sendChange( id, data ); KDEsuDialog dlg(user, auth_user, keep && !terminal,icon, withIgnoreButton); if (prompt) dlg.addLine(i18n("Command:"), command); if ((priority != 50) || (scheduler != SuProcess::SchedNormal)) { QString prio; if (scheduler == SuProcess::SchedRealtime) prio += i18n("realtime: "); prio += QString("%1/100").arg(priority); if (prompt) dlg.addLine(i18n("Priority:"), prio); } int ret = dlg.exec(); if (ret == KDEsuDialog::Rejected) { KStartupInfo::sendFinish( id ); exit(0); } if (ret == KDEsuDialog::AsUser) change_uid = false; password = dlg.password(); keep = dlg.keep(); data.setSilent( KStartupInfoData::No ); KStartupInfo::sendChange( id, data ); } // Some events may need to be handled (like a button animation) kapp->processEvents(); // Run command if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } else if (keep && have_daemon) { client.setPass(password, timeout); client.setPriority(priority); client.setScheduler(scheduler); int result = client.exec(command, user, options, env); if (result == 0) { result = client.exitCode(); return result; } } else { SuProcess proc; proc.setTerminal(terminal); proc.setErase(true); proc.setUser(user); if (!new_dcop) { proc.setXOnly(true); proc.setDCOPForwarding(true); } proc.setEnvironment(env); proc.setPriority(priority); proc.setScheduler(scheduler); proc.setCommand(command); int result = proc.exec(password); return result; } return -1; }
UploadDialog::UploadDialog(Engine *engine, QWidget *parent) : KDialogBase(Plain, i18n("Share Hot New Stuff"), Ok | Cancel, Cancel, parent, 0, false, true), mEngine(engine) { mEntryList.setAutoDelete(true); QFrame *topPage = plainPage(); QGridLayout *topLayout = new QGridLayout(topPage); topLayout->setSpacing(spacingHint()); QLabel *nameLabel = new QLabel(i18n("Name:"), topPage); topLayout->addWidget(nameLabel, 0, 0); mNameEdit = new QLineEdit(topPage); topLayout->addWidget(mNameEdit, 0, 1); QLabel *authorLabel = new QLabel(i18n("Author:"), topPage); topLayout->addWidget(authorLabel, 1, 0); mAuthorEdit = new QLineEdit(topPage); topLayout->addWidget(mAuthorEdit, 1, 1); QLabel *emailLabel = new QLabel(i18n("Email:"), topPage); topLayout->addWidget(emailLabel, 2, 0); mEmailEdit = new QLineEdit(topPage); topLayout->addWidget(mEmailEdit, 2, 1); QLabel *versionLabel = new QLabel(i18n("Version:"), topPage); topLayout->addWidget(versionLabel, 3, 0); mVersionEdit = new QLineEdit(topPage); topLayout->addWidget(mVersionEdit, 3, 1); QLabel *releaseLabel = new QLabel(i18n("Release:"), topPage); topLayout->addWidget(releaseLabel, 4, 0); mReleaseSpin = new QSpinBox(topPage); mReleaseSpin->setMinValue(1); topLayout->addWidget(mReleaseSpin, 4, 1); QLabel *licenceLabel = new QLabel(i18n("License:"), topPage); topLayout->addWidget(licenceLabel, 5, 0); mLicenceCombo = new QComboBox(topPage); mLicenceCombo->setEditable(true); mLicenceCombo->insertItem(i18n("GPL")); mLicenceCombo->insertItem(i18n("LGPL")); mLicenceCombo->insertItem(i18n("BSD")); topLayout->addWidget(mLicenceCombo, 5, 1); QLabel *languageLabel = new QLabel(i18n("Language:"), topPage); topLayout->addWidget(languageLabel, 6, 0); mLanguageCombo = new QComboBox(topPage); topLayout->addWidget(mLanguageCombo, 6, 1); mLanguageCombo->insertStringList(KGlobal::locale()->languageList()); QLabel *previewLabel = new QLabel(i18n("Preview URL:"), topPage); topLayout->addWidget(previewLabel, 7, 0); mPreviewUrl = new KURLRequester(topPage); topLayout->addWidget(mPreviewUrl, 7, 1); QLabel *summaryLabel = new QLabel(i18n("Summary:"), topPage); topLayout->addMultiCellWidget(summaryLabel, 8, 8, 0, 1); mSummaryEdit = new KTextEdit(topPage); topLayout->addMultiCellWidget(mSummaryEdit, 9, 9, 0, 1); KUser user; mAuthorEdit->setText(user.fullName()); }