void exportBuiltin(char* param){ int index=indexOfEq(param); if(index<0){ printf("===Invalid env params:%s [error]!===\n",param==NULL?"NULL":param); printf("enter 'exit' to quit or other to continue!\n"); return; } char* varType=malloc(sizeof(char)*index); strncpy(varType,param,index); char* varVal=param+index+1; #ifdef DEBUG printf("type is: %s\n",varType); printf("value is: %s\n",varVal); #endif if(!strcmp(varType,"HOME")){ setEnv(env.HOME,varVal); }else if(!strcmp(varType,"PATH")){ setEnv(env.PATH,varVal); }else if(!strcmp(varType,"PS1")){ setEnv(env.PS1,varVal); }else{ printf("===Invalid env params:%s [error]!===\n",param); printf("enter 'exit' to quit or other to continue!\n"); } }
/* * ======== smain ======== */ int main(int argc, char **argv) { char *env = NULL; if ((argc <= 1) || (argc > 3)) { RETAILMSG(TRUE, (TEXT("Usage: osalsetenv_wince.exe <var> [val]\n"))); return (-1); } if (argc == 2) { if (!setEnv(argv[1], NULL)) { RETAILMSG(TRUE, (TEXT("Failed to unset environment variable\n"))); } else { RETAILMSG(TRUE, (TEXT("Environment variable unset\n"))); } } else { if (!setEnv(argv[1], argv[2])) { RETAILMSG(TRUE, (TEXT("Failed to set environment variable\n"))); } else { RETAILMSG(TRUE, (TEXT("Environment variable set\n"))); } } return (0); }
static std::string setLangEnv() { std::string lang = config.getStringValue("lang"); #if defined(ENABLE_NLS) && defined(WIN32) if (lang.empty()) lang = std::string(_nl_locale_name_default()); #elif defined(ENABLE_CUSTOMNLS) && defined(__native_client__) if (lang.empty()) { NaclMessageHandle *handle = naclRegisterMessageHandler( "get-uilanguage"); naclPostMessage("get-uilanguage", ""); lang = naclWaitForMessage(handle); } #endif // defined(ENABLE_NLS) && defined(WIN32) if (!lang.empty()) { #ifdef WIN32 putenv(const_cast<char*>(("LANG=" + lang).c_str())); putenv(const_cast<char*>(("LANGUAGE=" + lang).c_str())); #else // WIN32 if (!lang.empty()) { setEnv("LANG", lang.c_str()); setEnv("LANGUAGE", lang.c_str()); } #endif // WIN32 } return lang; }
void Foam::argList::getRootCase() { fileName casePath; // [-case dir] specified HashTable<string>::const_iterator iter = options_.find("case"); if (iter != options_.end()) { casePath = iter(); casePath.clean(); if (casePath.empty() || casePath == ".") { // Handle degenerate form and '-case .' like no -case specified casePath = cwd(); options_.erase("case"); } else if (!casePath.isAbsolute() && casePath.name() == "..") { // Avoid relative cases ending in '..' - makes for very ugly names casePath = cwd()/casePath; casePath.clean(); } } else { // Nothing specified, use the current dir casePath = cwd(); } rootPath_ = casePath.path(); globalCase_ = casePath.name(); case_ = globalCase_; // Set the case and case-name as an environment variable if (rootPath_.isAbsolute()) { // Absolute path - use as-is setEnv("FOAM_CASE", rootPath_/globalCase_, true); setEnv("FOAM_CASENAME", globalCase_, true); } else { // Qualify relative path casePath = cwd()/rootPath_/globalCase_; casePath.clean(); setEnv("FOAM_CASE", casePath, true); setEnv("FOAM_CASENAME", casePath.name(), true); } }
void updateEnv() { #if defined(WIN32) || defined(__APPLE__) if (config.getBoolValue("centerwindow")) setEnv("SDL_VIDEO_CENTERED", "1"); else setEnv("SDL_VIDEO_CENTERED", "0"); #endif if (config.getBoolValue("allowscreensaver")) setEnv("SDL_VIDEO_ALLOW_SCREENSAVER", "1"); else setEnv("SDL_VIDEO_ALLOW_SCREENSAVER", "0"); #ifndef WIN32 const int vsync = settings.options.test.empty() ? config.getIntValue("vsync") : 1; // __GL_SYNC_TO_VBLANK is nvidia variable. // vblank_mode is MESA variable. switch (vsync) { case 1: setEnv("__GL_SYNC_TO_VBLANK", "0"); setEnv("vblank_mode", "0"); break; case 2: setEnv("__GL_SYNC_TO_VBLANK", "1"); setEnv("vblank_mode", "1"); break; default: break; } #endif }
static int displayErrorDir(int error, t_root *root, char *pwd, char *old) { if (error == -1 || root->CmdArray[1] == NULL) return (displayCdAccesError(root->CmdArray[1])); if (old != NULL) setEnv(root->Env, "OLDPWD", old); if (pwd != NULL) setEnv(root->Env, "PWD", pwd); if (old == NULL || pwd == NULL) { print_error(ERROR_SETENV_CANTSET); return (-1); } return (0); }
/** * Executes the back-end process. * @param sName The name of the process (for error messages) * @param slArgs A list containing the command-line arguments * @param sWorkDir (Optional) working directory * @param bBlock (Optional) true to block, false otherwise * @return true if the process was executed successfully, false otherwise */ bool Frontend::run(const QString& sName, const QStringList& slArgs, const QString& incDirs, const QString& srcDirs, const QString& sWorkDir, bool bBlock) { // Cannot start if another controlled process is currently running if (QProcess::state() == QProcess::Running) { m_sError = i18n("Cannot restart while another process is still " "running"); return false; } // Reset variables m_nRecords = 0; m_bKilled = false; // Setup the command-line arguments clearProgram(); if (m_bUseShell) // Execute inside a shell; join all arguments in a single QString setShellCommand(slArgs.join(" ")); else // Or setup args directly setProgram(slArgs); // Set the working directory, if requested if (!sWorkDir.isEmpty()) setWorkingDirectory(sWorkDir); // Set environment variables (INCLUDEDIRS & SOURCEDIRS) if required if (! incDirs.isEmpty()) { setEnv("INCLUDEDIRS", incDirs); } if (! srcDirs.isEmpty()) { setEnv("SOURCEDIRS", srcDirs); } // Execute the child process setOutputChannelMode( KProcess::SeparateChannels ); start(); if (! ( bBlock ? waitForFinished( -1 ) : waitForStarted ( -1 ))) { m_sError = sName + i18n(": Failed to start process"); return false; } m_sError = i18n("No error"); return true; }
int main(int argc,char** argv){ LoadNcon(argc,argv); char file_type; if(argc>2){ if(strcmp(argv[2],"--sys-help")==0){ return 100; } String cd_dir=getAbsoluteLocation(argv[argc-1],false); //The directory that the user wants to change to will always be the last argument String absolute_cd_dir=getAbsoluteLocation(cd_dir); if(FileExists(absolute_cd_dir,&file_type)){ if(file_type=='D'){ setEnv("CWD",cd_dir); }else{ printf("\"%s\" is not a directory.\n",(char*)cd_dir); } }else{ printf("Directory \"%s\" does not exist.\n",(char*)cd_dir); } }else{ printf("The \"cd\" command requires at least one parameter to execute. Type \"cd --help\" for usage.\n"); } return 0; }
ImportFunction::ImportFunction(): FactorableTemplate<Function, ImportFunction>(), _doImport(false), _importDone(false) { setEnv(boost::shared_ptr<Env>(new Env)); }
void LuaInterface::setGlobalEnvironment(int env) { pushThread(); getRef(env); assert(isTable()); setEnv(); pop(); }
void Mysh::parseCommand(string s) { vector<string> commands; isExit = false; size_t foundPos = 0; size_t lastFoundPos = 0; string command = ""; while (1) { foundPos = s.find_first_of("\n|!", foundPos); if (foundPos == string::npos) break; /* 找|!后面第一个空格或换行 */ if (s[foundPos] == '|' || s[foundPos] == '!') { size_t tempPos = s.find_first_of(" \n", foundPos); command = s.substr(lastFoundPos, tempPos - lastFoundPos); commands.push_back(command); lastFoundPos = s.find_first_of(" ", foundPos + 1); foundPos = lastFoundPos; } else { /* foundPos 已经指到换行 * 提取lastFoundPos 到foundPos 即可结束 */ command = s.substr(lastFoundPos, foundPos - lastFoundPos); command += '\n'; commands.push_back(command); break; } } isUnkCmd = 0; for (string::size_type i = 0; i < commands.size(); i++) { if(commands[i].find("exit") != string::npos) { isExit = true; return; } else if(commands[i].find("printenv") != string::npos) { printEnv(); return; } else if(commands[i].find("setenv") != string::npos) { setEnv(commands[i]); return; } //cout << commands[i] << endl; pipeToCommand(commands[i]); if (isUnkCmd == 1) break; /* 清理掉countDown == 0 的pipe */ pipevector.eraseInvalidPipe(); } /* 将所有pipe vector中的留下pipe 的countDown减一 */ pipevector.updateCountDown(); }
/** * Executes the script using the "sh" shell. * @param sCscopePath If given, overrides the automatic check for Cscope's * path * @param sCtagsPath If given, overrides the automatic check for Ctags' * path * @param sDotPath If given, overrides the automatic check for Dot's * path * @param bCscopeOptsOnly Only verify cscope's path and options * @return true if successful, false otherwise */ bool ConfigFrontend::run(const QString& sCscopePath, const QString& sCtagsPath, const QString& sDotPath, bool bCscopeOptsOnly) { QStringList slArgs; KStandardDirs sd; QString sScript; // Execute using the user's shell setUseShell(); // Find the configuration script sScript = sd.findResource("data", "kscope/kscope_config"); if (sScript.isEmpty()) return false; // Set command line arguments slArgs << QString("sh") << sScript; // Initialise environment setEnv("CSCOPE_PATH", sCscopePath); if (bCscopeOptsOnly){ slArgs << QString("-co"); } else { setEnv("CTAGS_PATH", sCtagsPath); setEnv("DOT_PATH", sDotPath); } // Parser initialisation m_delim = Newline; m_nNextResult = CscopePath; if (!Frontend::run("sh", QStringList(slArgs))) return false; emit test(CscopePath); return true; }
// Address is the unix address for the socket. // MAX_CLIENTS is the maximum number of clients // that can connect at the same time. ServerSocket::ServerSocket(FileName const & addr) : fd_(socktools::listen(addr, 3)), address_(addr) { if (fd_ == -1) { LYXERR(Debug::LYXSERVER, "lyx: Disabling LyX socket."); return; } // These env vars are used by DVI inverse search // Needed by xdvi setEnv("XEDITOR", "lyxclient -g %f %l"); // Needed by lyxclient setEnv("LYXSOCKET", address_.absFileName()); theApp()->registerSocketCallback( fd_, bind(&ServerSocket::serverCallback, this) ); LYXERR(Debug::LYXSERVER, "lyx: New server socket " << fd_ << ' ' << address_.absFileName()); }
void setEnvPath(string const & name, vector<string> const & env) { char const separator(os::path_separator()); ostringstream ss; vector<string>::const_iterator const begin = env.begin(); vector<string>::const_iterator const end = env.end(); vector<string>::const_iterator it = begin; for (; it != end; ++it) { if (it != begin) ss << separator; ss << os::external_path(*it); } setEnv(name, ss.str()); }
static int cdHomeDir(t_root *root) { char *homedir; char *pwd; char *old; homedir = getEnv("HOME", root->Env); if (homedir == NULL) return (print_error(ERROR_SETENV_CANTGET)); old = getcwd(NULL, 512); if (chdir(homedir) == -1) return (print_error(ERROR_ACCES_HOME)); pwd = getcwd(NULL, 512); if (old != NULL) setEnv(root->Env, "OLDPWD", old); if (pwd != NULL) setEnv(root->Env, "PWD", pwd); if (old == NULL || pwd == NULL) { print_error(ERROR_SETENV_CANTSET); return (-1); } return (0); }
/* * Class: net_calit2_mooc_iot_db410c_webserver_WebServer * Method: beginServer * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_net_calit2_mooc_iot_1db410c_webserver_WebServer_beginServer (JNIEnv * env, jobject obj, jstring ipaddress, jstring port){ //grab ip and port strings const char * ip = (*env)->GetStringUTFChars(env,ipaddress,0); const char * pt = (*env)->GetStringUTFChars(env,port,0); //save class object and env to call later for callback setJClassObject(obj); setEnv(env); //start server code! beginServer(ip,pt); (*env)->ReleaseStringUTFChars(env,ipaddress,ip); (*env)->ReleaseStringUTFChars(env,port,pt); }
pid_t sysexec::doExec(const QString & execPath, int gid, int uid, const QValueList<QCString> & args, const QValueList<QCString> & env ) { //zEnter(); pid_t pid; pid = ::vfork(); if ( 0 == pid ) { int nv = getpriority( PRIO_PROCESS, 0 ); nice( -nv ); for ( int fd = 3; fd < 100; fd++ ) { ::close( fd ); } setSameGidUid(gid, uid); //set enviroments setEnv(env); //generate arguement QValueList<QCString> fullArgs(args); fullArgs.prepend(QFile::encodeName( execPath )); char ** argList = stringListToStr(fullArgs); if ( ::execv( QFile::encodeName( execPath ) ,argList) < 0 ) { perror( "::execl error:" ); } ::_exit( -1 ); } //zLeave(); return pid; }
/** * Initialize the environment for all requests. * @param env the JNI environment for this request */ bool JNIUtil::JNIInit(JNIEnv *env) { // Clear all standing exceptions. env->ExceptionClear(); // Remember the env parameter for the remainder of the request. setEnv(env); // Lock the list of finalized objects. JNICriticalSection cs(*g_finalizedObjectsMutex) ; if (isExceptionThrown()) return false; // Delete all finalized, but not yet deleted objects. for (std::list<SVNBase*>::iterator it = g_finalizedObjects.begin(); it != g_finalizedObjects.end(); ++it) { delete *it; } g_finalizedObjects.clear(); return true; }
void callEnter(JNIEnv *env, jmp_buf *jmpbuf) { setEnv(env); callErrorJmpBuf = jmpbuf; // printf("callEnter\n"); }
void MongoDBConnectionPool::initEnv() { mongoc_init(); ConnectionProperties props = getProperties(); std::string connectionString = ""; if(isUnixDomainSocket) { if(props.getNodes().at(0).getUsername()!="" && props.getNodes().at(0).getPassword()!="") { connectionString += (props.getNodes().at(0).getUsername() + ":" + props.getNodes().at(0).getPassword() + "@"); } connectionString += "/tmp/mongodb.sock"; if(props.getNodes().at(0).getDatabaseName()!="") { connectionString += "/" + props.getNodes().at(0).getDatabaseName(); } } else { std::string databaseName = ""; std::cout << props.getNodes().size() << std::endl; for (int var = 0; var < (int)props.getNodes().size(); ++var) { if(databaseName=="") { databaseName = props.getNodes().at(var).getDatabaseName(); } int port = props.getNodes().at(var).getPort(); if(props.getNodes().at(var).getHost()=="") { continue; } if(port==-1) { port = 27017; } std::cout << props.getNodes().at(var).getHost() << std::endl; if(props.getNodes().at(var).getUsername()!="" && props.getNodes().at(var).getPassword()!="") { connectionString += (props.getNodes().at(var).getUsername() + ":" + props.getNodes().at(var).getPassword() + "@"); } connectionString += props.getNodes().at(var).getHost() + ":" + CastUtil::lexical_cast<std::string>(port); if(var!=(int)props.getNodes().size()-1) { connectionString += ","; } } if(connectionString.at(connectionString.length()-1)==',') { connectionString = connectionString.substr(0, connectionString.length()-1); } connectionString += "/"; if(databaseName!="") { connectionString += databaseName; } connectionString += "?"; if(isReplicaSet && replicaSetName!="") { connectionString += "replicaSet="+replicaSetName; if(isSSL) { connectionString += "&ssl=true"; } } else if(isSSL) { connectionString += "ssl=true"; } } int poolmin = 2, poolmax = 5; if((props.getPoolWriteSize()+props.getPoolReadSize())>0) { poolmax = props.getPoolWriteSize()+props.getPoolReadSize(); if(poolmax<poolmin) poolmax += poolmin; } if(connectionString.at(connectionString.length()-1)=='?') { connectionString += "minPoolSize=" + CastUtil::lexical_cast<std::string>(poolmin); } else { connectionString += "&minPoolSize=" + CastUtil::lexical_cast<std::string>(poolmin); } connectionString += "&maxPoolSize=" + CastUtil::lexical_cast<std::string>(poolmax); connectionString = "mongodb://" + connectionString; std::cout << connectionString << std::endl; uri = mongoc_uri_new(connectionString.c_str()); mongoc_client_pool_t *pool = mongoc_client_pool_new(uri); setEnv(pool); props.setNewConnectionStrategy(true); }
static Bool StartClient ( struct verify_info *verify, struct display *d, int *pidp, char *name, char *passwd) { char **f, *home; char *failsafeArgv[2]; int pid; #ifdef HAS_SETUSERCONTEXT struct passwd* pwd; #endif #ifdef USE_PAM pam_handle_t *pamh = thepamh(); #endif if (verify->argv) { Debug ("StartSession %s: ", verify->argv[0]); for (f = verify->argv; *f; f++) Debug ("%s ", *f); Debug ("; "); } if (verify->userEnviron) { for (f = verify->userEnviron; *f; f++) Debug ("%s ", *f); Debug ("\n"); } #ifdef USE_PAM if (pamh) pam_open_session(pamh, 0); #endif switch (pid = fork ()) { case 0: CleanUpChild (); #ifdef XDMCP /* The chooser socket is not closed by CleanUpChild() */ DestroyWellKnownSockets(); #endif /* Do system-dependent login setup here */ #ifdef USE_PAM /* pass in environment variables set by libpam and modules it called */ if (pamh) { long i; char **pam_env = pam_getenvlist(pamh); for(i = 0; pam_env && pam_env[i]; i++) { verify->userEnviron = putEnv(pam_env[i], verify->userEnviron); } } #endif #ifndef AIXV3 #ifndef HAS_SETUSERCONTEXT if (setgid(verify->gid) < 0) { LogError("setgid %d (user \"%s\") failed, errno=%d\n", verify->gid, name, errno); return (0); } #if defined(BSD) && (BSD >= 199103) if (setlogin(name) < 0) { LogError("setlogin for \"%s\" failed, errno=%d", name, errno); return(0); } #endif #ifndef QNX4 if (initgroups(name, verify->gid) < 0) { LogError("initgroups for \"%s\" failed, errno=%d\n", name, errno); return (0); } #endif /* QNX4 doesn't support multi-groups, no initgroups() */ #ifdef USE_PAM if (thepamh()) { pam_setcred(thepamh(), PAM_ESTABLISH_CRED); } #endif if (setuid(verify->uid) < 0) { LogError("setuid %d (user \"%s\") failed, errno=%d\n", verify->uid, name, errno); return (0); } #else /* HAS_SETUSERCONTEXT */ /* * Set the user's credentials: uid, gid, groups, * environment variables, resource limits, and umask. */ pwd = getpwnam(name); if (pwd) { if (setusercontext(NULL, pwd, pwd->pw_uid, LOGIN_SETALL) < 0) { LogError("setusercontext for \"%s\" failed, errno=%d\n", name, errno); return (0); } endpwent(); } else { LogError("getpwnam for \"%s\" failed, errno=%d\n", name, errno); return (0); } #endif /* HAS_SETUSERCONTEXT */ #else /* AIXV3 */ /* * Set the user's credentials: uid, gid, groups, * audit classes, user limits, and umask. */ if (setpcred(name, NULL) == -1) { LogError("setpcred for \"%s\" failed, errno=%d\n", name, errno); return (0); } #endif /* AIXV3 */ /* * for user-based authorization schemes, * use the password to get the user's credentials. */ #ifdef SECURE_RPC /* do like "keylogin" program */ { char netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1]; int nameret, keyret; int len; int key_set_ok = 0; nameret = getnetname (netname); Debug ("User netname: %s\n", netname); len = strlen (passwd); if (len > 8) bzero (passwd + 8, len - 8); keyret = getsecretkey(netname,secretkey,passwd); Debug ("getsecretkey returns %d, key length %d\n", keyret, strlen (secretkey)); /* is there a key, and do we have the right password? */ if (keyret == 1) { if (*secretkey) { keyret = key_setsecret(secretkey); Debug ("key_setsecret returns %d\n", keyret); if (keyret == -1) LogError ("failed to set NIS secret key\n"); else key_set_ok = 1; } else { /* found a key, but couldn't interpret it */ LogError ("password incorrect for NIS principal \"%s\"\n", nameret ? netname : name); } } if (!key_set_ok) { /* remove SUN-DES-1 from authorizations list */ int i, j; for (i = 0; i < d->authNum; i++) { if (d->authorizations[i]->name_length == 9 && memcmp(d->authorizations[i]->name, "SUN-DES-1", 9) == 0) { for (j = i+1; j < d->authNum; j++) d->authorizations[j-1] = d->authorizations[j]; d->authNum--; break; } } } bzero(secretkey, strlen(secretkey)); } #endif #ifdef K5AUTH /* do like "kinit" program */ { int i, j; int result; extern char *Krb5CCacheName(); result = Krb5Init(name, passwd, d); if (result == 0) { /* point session clients at the Kerberos credentials cache */ verify->userEnviron = setEnv(verify->userEnviron, "KRB5CCNAME", Krb5CCacheName(d->name)); } else { for (i = 0; i < d->authNum; i++) { if (d->authorizations[i]->name_length == 14 && memcmp(d->authorizations[i]->name, "MIT-KERBEROS-5", 14) == 0) { /* remove Kerberos from authorizations list */ for (j = i+1; j < d->authNum; j++) d->authorizations[j-1] = d->authorizations[j]; d->authNum--; break; } } } } #endif /* K5AUTH */ bzero(passwd, strlen(passwd)); SetUserAuthorization (d, verify); home = getEnv (verify->userEnviron, "HOME"); if (home) if (chdir (home) == -1) { LogError ("user \"%s\": cannot chdir to home \"%s\" (err %d), using \"/\"\n", getEnv (verify->userEnviron, "USER"), home, errno); chdir ("/"); verify->userEnviron = setEnv(verify->userEnviron, "HOME", "/"); } if (verify->argv) { Debug ("executing session %s\n", verify->argv[0]); execute (verify->argv, verify->userEnviron); LogError ("Session \"%s\" execution failed (err %d)\n", verify->argv[0], errno); } else { LogError ("Session has no command/arguments\n"); } failsafeArgv[0] = d->failsafeClient; failsafeArgv[1] = 0; execute (failsafeArgv, verify->userEnviron); exit (1); case -1: bzero(passwd, strlen(passwd)); Debug ("StartSession, fork failed\n"); LogError ("can't start session on \"%s\", fork failed, errno=%d\n", d->name, errno); return 0; default: bzero(passwd, strlen(passwd)); Debug ("StartSession, fork succeeded %d\n", pid); *pidp = pid; return 1; } }
static Bool StartClient ( struct verify_info *verify, struct display *d, pid_t *pidp, char *name) { char **f, *home; char *failsafeArgv[2]; pid_t pid; struct passwd* pwd; if (pledge("stdio rpath wpath cpath fattr proc getpw id exec dns unix inet", NULL) != 0) exit(25); if (verify->argv) { Debug ("StartSession %s: ", verify->argv[0]); for (f = verify->argv; *f; f++) Debug ("%s ", *f); Debug ("; "); } if (verify->userEnviron) { for (f = verify->userEnviron; *f; f++) Debug ("%s ", *f); Debug ("\n"); } switch (pid = fork ()) { case 0: CleanUpChild (); /* * Set the user's credentials: uid, gid, groups, * environment variables, resource limits, and umask. */ pwd = getpwnam(name); if (pwd) { if (d->windowPath != NULL) { /* XXX not working because of pledge() */ Debug("login_fbtab %s %d\n", d->windowPath, geteuid()); login_fbtab(d->windowPath, pwd->pw_uid, pwd->pw_gid); } if (setusercontext(NULL, pwd, pwd->pw_uid, LOGIN_SETALL) < 0) { LogError ("setusercontext for \"%s\" failed: %s\n", name, _SysErrorMsg (errno)); return (0); } } else { LogError ("getpwnam for \"%s\" failed: %s\n", name, _SysErrorMsg (errno)); return (0); } if (d->windowPath) verify->userEnviron = setEnv(verify->userEnviron, "WINDOWPATH", d->windowPath); else Debug("No WINDOWPATH found\n"); SetUserAuthorization (d, verify); home = getEnv (verify->userEnviron, "HOME"); if (home) if (chdir (home) == -1) { LogError ("user \"%s\": cannot chdir to home \"%s\" (err %d), using \"/\"\n", getEnv (verify->userEnviron, "USER"), home, errno); chdir ("/"); verify->userEnviron = setEnv(verify->userEnviron, "HOME", "/"); } if (verify->argv) { LogInfo ("executing session %s\n", verify->argv[0]); execute (verify->argv, verify->userEnviron); LogError ("Session \"%s\" execution failed (err %d)\n", verify->argv[0], errno); } else { LogError ("Session has no command/arguments\n"); } failsafeArgv[0] = d->failsafeClient; failsafeArgv[1] = NULL; execute (failsafeArgv, verify->userEnviron); exit (1); case -1: Debug ("StartSession, fork failed\n"); LogError ("can't start session on \"%s\", fork failed: %s\n", d->name, _SysErrorMsg (errno)); return 0; default: Debug ("StartSession, fork succeeded %d\n", pid); *pidp = pid; return 1; } }
/** * Initialize the environment for all requests. * @param env the JNI environment for this request */ bool JNIUtil::JNIGlobalInit(JNIEnv *env) { // This method has to be run only once during the run a program. static bool run = false; svn_error_t *err; if (run) // already run return true; run = true; // Do not run this part more than one time. This leaves a small // time window when two threads create their first SVNClient and // SVNAdmin at the same time, but I do not see a better option // without APR already initialized if (g_inInit) return false; g_inInit = true; g_initEnv = env; apr_status_t status; /* Initialize the APR subsystem, and register an atexit() function * to Uninitialize that subsystem at program exit. */ status = apr_initialize(); if (status) { if (stderr) { char buf[1024]; apr_strerror(status, buf, sizeof(buf) - 1); fprintf(stderr, "%s: error: cannot initialize APR: %s\n", "svnjavahl", buf); } return FALSE; } /* This has to happen before any pools are created. */ if ((err = svn_dso_initialize2())) { if (stderr && err->message) fprintf(stderr, "%s", err->message); svn_error_clear(err); return FALSE; } if (0 > atexit(apr_terminate)) { if (stderr) fprintf(stderr, "%s: error: atexit registration failed\n", "svnjavahl"); return FALSE; } /* Create our top-level pool. */ g_pool = svn_pool_create(NULL); apr_allocator_t* allocator = apr_pool_allocator_get(g_pool); if (allocator) { /* Keep a maximum of 1 free block, to release memory back to the JVM (and other modules). */ apr_allocator_max_free_set(allocator, 1); } svn_utf_initialize2(FALSE, g_pool); /* Optimize character conversions */ svn_fs_initialize(g_pool); /* Avoid some theoretical issues */ svn_ra_initialize(g_pool); /* We shouldn't fill the JVMs memory with FS cache data unless explictly requested. */ { svn_cache_config_t settings = *svn_cache_config_get(); settings.cache_size = 0; settings.file_handle_count = 0; settings.single_threaded = FALSE; svn_cache_config_set(&settings); } #ifdef ENABLE_NLS #ifdef WIN32 { WCHAR ucs2_path[MAX_PATH]; char *utf8_path; const char *internal_path; apr_pool_t *pool; apr_status_t apr_err; apr_size_t inwords, outbytes; unsigned int outlength; pool = svn_pool_create(g_pool); /* get dll name - our locale info will be in '../share/locale' */ inwords = sizeof(ucs2_path) / sizeof(ucs2_path[0]); HINSTANCE moduleHandle = GetModuleHandle("libsvnjavahl-1"); GetModuleFileNameW(moduleHandle, ucs2_path, inwords); inwords = lstrlenW(ucs2_path); outbytes = outlength = 3 * (inwords + 1); utf8_path = reinterpret_cast<char *>(apr_palloc(pool, outlength)); apr_err = apr_conv_ucs2_to_utf8((const apr_wchar_t *) ucs2_path, &inwords, utf8_path, &outbytes); if (!apr_err && (inwords > 0 || outbytes == 0)) apr_err = APR_INCOMPLETE; if (apr_err) { if (stderr) fprintf(stderr, "Can't convert module path to UTF-8"); return FALSE; } utf8_path[outlength - outbytes] = '\0'; internal_path = svn_dirent_internal_style(utf8_path, pool); /* get base path name */ internal_path = svn_dirent_dirname(internal_path, pool); internal_path = svn_dirent_join(internal_path, SVN_LOCALE_RELATIVE_PATH, pool); bindtextdomain(PACKAGE_NAME, internal_path); svn_pool_destroy(pool); } #else bindtextdomain(PACKAGE_NAME, SVN_LOCALE_DIR); #endif #endif #if defined(WIN32) || defined(__CYGWIN__) /* See http://svn.apache.org/repos/asf/subversion/trunk/notes/asp-dot-net-hack.txt */ /* ### This code really only needs to be invoked by consumers of ### the libsvn_wc library, which basically means SVNClient. */ if (getenv("SVN_ASP_DOT_NET_HACK")) { err = svn_wc_set_adm_dir("_svn", g_pool); if (err) { if (stderr) { fprintf(stderr, "%s: error: SVN_ASP_DOT_NET_HACK failed: %s\n", "svnjavahl", err->message); } svn_error_clear(err); return FALSE; } } #endif svn_error_set_malfunction_handler(svn_error_raise_on_malfunction); // Build all mutexes. g_finalizedObjectsMutex = new JNIMutex(g_pool); if (isExceptionThrown()) return false; g_logMutex = new JNIMutex(g_pool); if (isExceptionThrown()) return false; // initialized the thread local storage if (!JNIThreadData::initThreadData()) return false; setEnv(env); if (isExceptionThrown()) return false; g_initEnv = NULL; g_inInit = false; return true; }
RExternalModule(const char *uri, SEXP e) { URI = new zorba::String(uri); setEnv(e); };
int startClient( volatile int *pid ) { const char *home, *sessargs, *desksess; char **env, *xma; char **argv, *fname, *str; #ifdef USE_PAM char ** volatile pam_env; # ifndef HAVE_PAM_GETENVLIST char **saved_env; # endif int pretc; #else # ifdef _AIX char *msg; char **theenv; extern char **newenv; /* from libs.a, this is set up by setpenv */ # endif #endif #ifdef HAVE_SETUSERCONTEXT extern char **environ; #endif char *failsafeArgv[2]; char *buf, *buf2; int i; if (strCmp( dmrcuser, curuser )) { if (curdmrc) { free( curdmrc ); curdmrc = 0; } if (dmrcuser) { free( dmrcuser ); dmrcuser = 0; } } #if defined(USE_PAM) || defined(_AIX) if (!(p = getpwnam( curuser ))) { logError( "getpwnam(%s) failed.\n", curuser ); pError: displayStr( V_MSG_ERR, 0 ); return 0; } #endif #ifndef USE_PAM # ifdef _AIX msg = NULL; loginsuccess( curuser, hostname, tty, &msg ); if (msg) { debug( "loginsuccess() - %s\n", msg ); free( (void *)msg ); } # else /* _AIX */ # if defined(KERBEROS) && defined(AFS) if (krbtkfile[0] != '\0') { if (k_hasafs()) { int fail = 0; if (k_setpag() == -1) { logError( "setpag() for %s failed\n", curuser ); fail = 1; } if ((ret = k_afsklog( NULL, NULL )) != KSUCCESS) { logError( "AFS Warning: %s\n", krb_get_err_text( ret ) ); fail = 1; } if (fail) displayMsg( V_MSG_ERR, "Warning: Problems during Kerberos4/AFS setup." ); } } # endif /* KERBEROS && AFS */ # endif /* _AIX */ #endif /* !PAM */ curuid = p->pw_uid; curgid = p->pw_gid; env = baseEnv( curuser ); xma = 0; strApp( &xma, "method=", curtype, (char *)0 ); if (td_setup) strApp( &xma, ",auto", (char *)0 ); if (xma) { env = setEnv( env, "XDM_MANAGED", xma ); free( xma ); } if (td->autoLock && cursource == PWSRC_AUTOLOGIN) env = setEnv( env, "DESKTOP_LOCKED", "true" ); env = setEnv( env, "PATH", curuid ? td->userPath : td->systemPath ); env = setEnv( env, "SHELL", p->pw_shell ); env = setEnv( env, "HOME", p->pw_dir ); #if !defined(USE_PAM) && !defined(_AIX) && defined(KERBEROS) if (krbtkfile[0] != '\0') env = setEnv( env, "KRBTKFILE", krbtkfile ); #endif userEnviron = inheritEnv( env, envvars ); env = systemEnv( curuser ); systemEnviron = setEnv( env, "HOME", p->pw_dir ); debug( "user environment:\n%[|''>'\n's" "system environment:\n%[|''>'\n's" "end of environments\n", userEnviron, systemEnviron ); /* * for user-based authorization schemes, * add the user to the server's allowed "hosts" list. */ for (i = 0; i < td->authNum; i++) { #ifdef SECURE_RPC if (td->authorizations[i]->name_length == 9 && !memcmp( td->authorizations[i]->name, "SUN-DES-1", 9 )) { XHostAddress addr; char netname[MAXNETNAMELEN+1]; char domainname[MAXNETNAMELEN+1]; getdomainname( domainname, sizeof(domainname) ); user2netname( netname, curuid, domainname ); addr.family = FamilyNetname; addr.length = strlen( netname ); addr.address = netname; XAddHost( dpy, &addr ); } #endif #ifdef K5AUTH if (td->authorizations[i]->name_length == 14 && !memcmp( td->authorizations[i]->name, "MIT-KERBEROS-5", 14 )) { /* Update server's auth file with user-specific info. * Don't need to AddHost because X server will do that * automatically when it reads the cache we are about * to point it at. */ XauDisposeAuth( td->authorizations[i] ); td->authorizations[i] = krb5GetAuthFor( 14, "MIT-KERBEROS-5", td->name ); saveServerAuthorizations( td, td->authorizations, td->authNum ); } #endif } if (*dmrcDir) mergeSessionArgs( TRUE ); debug( "now starting the session\n" ); #ifdef USE_PAM # ifdef HAVE_SETUSERCONTEXT if (setusercontext( lc, p, p->pw_uid, LOGIN_SETGROUP )) { logError( "setusercontext(groups) for %s failed: %m\n", curuser ); goto pError; } # else if (!setGid( curuser, curgid )) goto pError; # endif # ifndef HAVE_PAM_GETENVLIST if (!(pam_env = initStrArr( 0 ))) { resetGids(); goto pError; } saved_env = environ; environ = pam_env; # endif removeCreds = 1; /* set it first - i don't trust PAM's rollback */ pretc = pam_setcred( pamh, 0 ); reInitErrorLog(); # ifndef HAVE_PAM_GETENVLIST pam_env = environ; environ = saved_env; # endif # ifdef HAVE_INITGROUPS /* This seems to be a strange place for it, but do it: - after the initial groups are set - after pam_setcred might have set something, even in the error case - before pam_setcred(DELETE_CRED) might need it */ if (!saveGids()) goto pError; # endif if (pretc != PAM_SUCCESS) { logError( "pam_setcred() for %s failed: %s\n", curuser, pam_strerror( pamh, pretc ) ); resetGids(); return 0; } removeSession = 1; /* set it first - same as above */ pretc = pam_open_session( pamh, 0 ); reInitErrorLog(); if (pretc != PAM_SUCCESS) { logError( "pam_open_session() for %s failed: %s\n", curuser, pam_strerror( pamh, pretc ) ); resetGids(); return 0; } /* we don't want sessreg and the startup/reset scripts run with user credentials. unfortunately, we can reset only the gids. */ resetGids(); # define D_LOGIN_SETGROUP LOGIN_SETGROUP #else /* USE_PAM */ # define D_LOGIN_SETGROUP 0 #endif /* USE_PAM */ removeAuth = 1; chownCtrl( &td->ctrl, curuid ); endpwent(); #if !defined(USE_PAM) && defined(USESHADOW) && !defined(_AIX) endspent(); #endif ctltalk.pipe = &ctlpipe; ASPrintf( &buf, "sub-daemon for display %s", td->name ); ASPrintf( &buf2, "client for display %s", td->name ); switch (gFork( &ctlpipe, buf, buf2, 0, 0, mstrtalk.pipe, pid )) { case 0: gCloseOnExec( ctltalk.pipe ); if (Setjmp( ctltalk.errjmp )) exit( 1 ); gCloseOnExec( mstrtalk.pipe ); if (Setjmp( mstrtalk.errjmp )) goto cError; #ifndef NOXDMTITLE setproctitle( "%s'", td->name ); #endif strApp( &prog, " '", (char *)0 ); reInitErrorLog(); setsid(); sessreg( td, getpid(), curuser, curuid ); /* We do this here, as we want to have the session as parent. */ switch (source( systemEnviron, td->startup, td_setup )) { case 0: break; case wcCompose( 0, 0, 127 ): goto cError; default: /* Explicit failure => message already displayed. */ logError( "Startup script returned non-zero exit code\n" ); exit( 1 ); } /* Memory leaks are ok here as we exec() soon. */ #if defined(USE_PAM) || !defined(_AIX) # ifdef USE_PAM /* pass in environment variables set by libpam and modules it called */ # ifdef HAVE_PAM_GETENVLIST pam_env = pam_getenvlist( pamh ); reInitErrorLog(); # endif if (pam_env) for (; *pam_env; pam_env++) userEnviron = putEnv( *pam_env, userEnviron ); # endif # ifdef HAVE_SETLOGIN if (setlogin( curuser ) < 0) { logError( "setlogin for %s failed: %m\n", curuser ); goto cError; } # define D_LOGIN_SETLOGIN LOGIN_SETLOGIN # else # define D_LOGIN_SETLOGIN 0 # endif # if defined(USE_PAM) && defined(HAVE_INITGROUPS) if (!restoreGids()) goto cError; # endif # ifndef HAVE_SETUSERCONTEXT # ifdef USE_PAM if (!setUid( curuser, curuid )) goto cError; # else if (!setUser( curuser, curuid, curgid )) goto cError; # endif # else /* !HAVE_SETUSERCONTEXT */ /* * Destroy environment. * We need to do this before setusercontext() because that may * set or reset some environment variables. */ if (!(environ = initStrArr( 0 ))) goto cError; /* * Set the user's credentials: uid, gid, groups, * environment variables, resource limits, and umask. */ if (setusercontext( lc, p, p->pw_uid, LOGIN_SETALL & ~(D_LOGIN_SETGROUP|D_LOGIN_SETLOGIN) ) < 0) { logError( "setusercontext for %s failed: %m\n", curuser ); goto cError; } for (i = 0; environ[i]; i++) userEnviron = putEnv( environ[i], userEnviron ); # endif /* !HAVE_SETUSERCONTEXT */ #else /* PAM || !_AIX */ /* * Set the user's credentials: uid, gid, groups, * audit classes, user limits, and umask. */ if (setpcred( curuser, NULL ) == -1) { logError( "setpcred for %s failed: %m\n", curuser ); goto cError; } /* * Set the users process environment. Store protected variables and * obtain updated user environment list. This call will initialize * global 'newenv'. */ if (setpenv( curuser, PENV_INIT | PENV_ARGV | PENV_NOEXEC, userEnviron, NULL ) != 0) { logError( "Cannot set %s's process environment\n", curuser ); goto cError; } userEnviron = newenv; #endif /* _AIX */ /* * for user-based authorization schemes, * use the password to get the user's credentials. */ #ifdef SECURE_RPC /* do like "keylogin" program */ if (!curpass[0]) logInfo( "No password for NIS provided.\n" ); else { char netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1]; int nameret, keyret; int len; int key_set_ok = 0; struct key_netstarg netst; nameret = getnetname( netname ); debug( "user netname: %s\n", netname ); len = strlen( curpass ); if (len > 8) bzero( curpass + 8, len - 8 ); keyret = getsecretkey( netname, secretkey, curpass ); debug( "getsecretkey returns %d, key length %d\n", keyret, strlen( secretkey ) ); netst.st_netname = netname; memcpy( netst.st_priv_key, secretkey, HEXKEYBYTES ); memset( netst.st_pub_key, 0, HEXKEYBYTES ); if (key_setnet( &netst ) < 0) debug( "Could not set secret key.\n" ); /* is there a key, and do we have the right password? */ if (keyret == 1) { if (*secretkey) { keyret = key_setsecret( secretkey ); debug( "key_setsecret returns %d\n", keyret ); if (keyret == -1) logError( "Failed to set NIS secret key\n" ); else key_set_ok = 1; } else { /* found a key, but couldn't interpret it */ logError( "Password incorrect for NIS principal %s\n", nameret ? netname : curuser ); } } if (!key_set_ok) nukeAuth( 9, "SUN-DES-1" ); bzero( secretkey, strlen( secretkey ) ); } #endif #ifdef K5AUTH /* do like "kinit" program */ if (!curpass[0]) logInfo( "No password for Kerberos5 provided.\n" ); else if ((str = krb5Init( curuser, curpass, td->name ))) userEnviron = setEnv( userEnviron, "KRB5CCNAME", str ); else nukeAuth( 14, "MIT-KERBEROS-5" ); #endif /* K5AUTH */ if (td->autoReLogin) { gSet( &mstrtalk ); gSendInt( D_ReLogin ); gSendStr( curuser ); gSendStr( curpass ); gSendStr( newdmrc ); } if (curpass) bzero( curpass, strlen( curpass ) ); setUserAuthorization( td ); home = getEnv( userEnviron, "HOME" ); if (home && chdir( home ) < 0) { logError( "Cannot chdir to %s's home %s: %m\n", curuser, home ); sendStr( V_MSG_ERR, "Cannot enter home directory. Using /.\n" ); chdir( "/" ); userEnviron = setEnv( userEnviron, "HOME", "/" ); home = 0; } if (home || td->clientLogFile[0] == '/') { if (!createClientLog( td->clientLogFile )) { logWarn( "Session log file according to %s cannot be created: %m\n", td->clientLogFile ); goto tmperr; } } else { tmperr: if (!createClientLog( td->clientLogFallback )) logError( "Fallback session log file according to %s cannot be created: %m\n", td->clientLogFallback ); /* Could inform the user, but I guess this is only confusing. */ } if (!*dmrcDir) mergeSessionArgs( home != 0 ); if (!(desksess = iniEntry( curdmrc, "Desktop", "Session", 0 ))) desksess = "failsafe"; /* only due to OOM */ gSet( &mstrtalk ); gSendInt( D_User ); gSendInt( curuid ); gSendStr( curuser ); gSendStr( desksess ); close( mstrtalk.pipe->fd.w ); userEnviron = setEnv( userEnviron, "DESKTOP_SESSION", desksess ); for (i = 0; td->sessionsDirs[i]; i++) { fname = 0; if (strApp( &fname, td->sessionsDirs[i], "/", desksess, ".desktop", (char *)0 )) { if ((str = iniLoad( fname ))) { if (!strCmp( iniEntry( str, "Desktop Entry", "Hidden", 0 ), "true" ) || !(sessargs = iniEntry( str, "Desktop Entry", "Exec", 0 ))) sessargs = ""; free( str ); free( fname ); goto gotit; } free( fname ); } } if (!strcmp( desksess, "failsafe" ) || !strcmp( desksess, "default" ) || !strcmp( desksess, "custom" )) sessargs = desksess; else sessargs = ""; gotit: if (!(argv = parseArgs( (char **)0, td->session )) || !(argv = addStrArr( argv, sessargs, -1 ))) exit( 1 ); if (argv[0] && *argv[0]) { debug( "executing session %\"[s\n", argv ); execute( argv, userEnviron ); logError( "Session %\"s execution failed: %m\n", argv[0] ); } else logError( "Session has no command/arguments\n" ); failsafeArgv[0] = td->failsafeClient; failsafeArgv[1] = 0; execute( failsafeArgv, userEnviron ); logError( "Failsafe client %\"s execution failed: %m\n", failsafeArgv[0] ); cError: sendStr( V_MSG_ERR, 0 ); exit( 1 ); case -1: free( buf ); return 0; } debug( "StartSession, fork succeeded %d\n", *pid ); free( buf ); gSet( &ctltalk ); if (!Setjmp( ctltalk.errjmp )) while (gRecvCmd( &i )) { buf = gRecvStr(); displayStr( i, buf ); free( buf ); gSet( &ctltalk ); gSendInt( 0 ); } gClosen( ctltalk.pipe ); finishGreet(); return 1; }
/* * Find the matching handler for a request. If any errors occur, the pass handler is used to pass errors onto the * net/sendfile connectors to send to the client. This routine may rewrite the request URI and may redirect the request. */ void maMatchHandler(MaConn *conn) { MaRequest *req; MaResponse *resp; MaHost *host; MaAlias *alias; MaStage *handler; bool rescan; int loopCount; req = conn->request; resp = conn->response; host = req->host; /* * Find the alias that applies for this url. There is always a catch-all alias for the document root. */ alias = req->alias = maGetAlias(host, req->url); mprAssert(alias); if (alias->redirectCode) { // TODO - what about internal redirects? maRedirect(conn, alias->redirectCode, alias->uri); return; } if (conn->requestFailed || conn->request->method & (MA_REQ_OPTIONS | MA_REQ_TRACE)) { handler = conn->http->passHandler; return; } /* * Get the best (innermost) location block and see if a handler is explicitly set for that location block. * Possibly rewrite the url and retry. */ loopCount = MA_MAX_REWRITE; do { rescan = 0; if ((handler = findLocationHandler(conn)) == 0) { /* * Didn't find a location block handler, so try to match by extension and by handler match() routines. * This may invoke processDirectory which may redirect and thus require reprocessing -- hence the loop. */ handler = findHandlerByExtension(conn); } if (handler && !(handler->flags & MA_STAGE_VIRTUAL)) { if (!mapToFile(conn, &rescan)) { return; } } } while (handler && rescan && loopCount-- > 0); if (handler == 0) { maFailRequest(conn, MPR_HTTP_CODE_BAD_METHOD, "Requested method %s not supported for URL: %s", req->methodName, req->url); handler = conn->http->passHandler; } resp->handler = handler; mprLog(resp, 4, "Select handler: \"%s\" for \"%s\"", handler->name, req->url); setEnv(conn); }
void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) { SCRIPTAPI_PRECHECKHEADER verbosestream<<"scriptapi_add_environment"<<std::endl; setEnv(env); /* Add ActiveBlockModifiers to environment */ // Get core.registered_abms lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_abms"); luaL_checktype(L, -1, LUA_TTABLE); int registered_abms = lua_gettop(L); if(lua_istable(L, registered_abms)){ int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 int id = lua_tonumber(L, -2); int current_abm = lua_gettop(L); std::set<std::string> trigger_contents; lua_getfield(L, current_abm, "nodenames"); if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); trigger_contents.insert(lua_tostring(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if(lua_isstring(L, -1)){ trigger_contents.insert(lua_tostring(L, -1)); } lua_pop(L, 1); std::set<std::string> required_neighbors; lua_getfield(L, current_abm, "neighbors"); if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); required_neighbors.insert(lua_tostring(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if(lua_isstring(L, -1)){ required_neighbors.insert(lua_tostring(L, -1)); } lua_pop(L, 1); float trigger_interval = 10.0; getfloatfield(L, current_abm, "interval", trigger_interval); int trigger_chance = 50; getintfield(L, current_abm, "chance", trigger_chance); int neighbors_range = 1; getintfield(L, current_abm, "neighbors_range", neighbors_range); LuaABM *abm = new LuaABM(L, id, trigger_contents, required_neighbors, neighbors_range, trigger_interval, trigger_chance); env->addActiveBlockModifier(abm); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); }
SDLWindow::SDLWindow(const DisplayParams& dp, GLConfig glConfig) : Window(dp.getWindowParams(0), dp.isFullscreen()), m_pLastMouseEvent(new MouseEvent(Event::CURSOR_MOTION, false, false, false, IntPoint(-1, -1), MouseEvent::NO_BUTTON, glm::vec2(-1, -1), 0)) { initTranslationTable(); // This "fixes" the default behaviour of SDL under x11, avoiding it // to report relative mouse coordinates when going fullscreen and // the mouse cursor is hidden (grabbed). So far libavg and apps based // on it don't use relative coordinates. setEnv("SDL_MOUSE_RELATIVE", "0"); const WindowParams& wp = dp.getWindowParams(0); stringstream ss; IntPoint pos = getPos(); if (pos.x != -1) { ss << pos.x << "," << pos.y; setEnv("SDL_VIDEO_WINDOW_POS", ss.str().c_str()); } unsigned int flags = 0; if (dp.isFullscreen()) { flags |= SDL_FULLSCREEN; } if (!wp.m_bHasWindowFrame) { flags |= SDL_NOFRAME; } IntPoint size = wp.m_Size; SDL_Surface * pSDLSurface = 0; #ifndef linux if (glConfig.m_bUseDebugContext) { glConfig.m_bUseDebugContext = false; } switch (dp.getBPP()) { case 24: SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 24); break; case 16: SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 16); break; default: AVG_LOG_ERROR("Unsupported bpp " << dp.getBPP() << "in Window::init()"); exit(-1); } SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL , 0); flags |= SDL_OPENGL; while (glConfig.m_MultiSampleSamples && !pSDLSurface) { if (glConfig.m_MultiSampleSamples > 1) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, glConfig.m_MultiSampleSamples); } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } pSDLSurface = SDL_SetVideoMode(size.x, size.y, dp.getBPP(), flags); if (!pSDLSurface) { glConfig.m_MultiSampleSamples = GLContext::nextMultiSampleValue( glConfig.m_MultiSampleSamples); } } #else // Linux version: Context created manually, not by SDL pSDLSurface = SDL_SetVideoMode(size.x, size.y, dp.getBPP(), flags); #endif if (!pSDLSurface) { throw Exception(AVG_ERR_UNSUPPORTED, string("Setting SDL video mode failed: ") + SDL_GetError() + ". (size=" + toString(size) + ", bpp=" + toString(dp.getBPP()) + ")."); } SDL_SysWMinfo info; SDL_VERSION(&info.version); int rc = SDL_GetWMInfo(&info); AVG_ASSERT(rc != -1); GLContext* pGLContext = GLContextManager::get()->createContext(glConfig, size, &info); setGLContext(pGLContext); #if defined(HAVE_XI2_1) || defined(HAVE_XI2_2) SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); m_pXIMTInputDevice = 0; #endif SDL_WM_SetCaption("libavg", 0); pGLContext->logConfig(); }
void KProcess::setShellCommand(const QString &cmd) { Q_D(KProcess); KShell::Errors err; d->args = KShell::splitArgs( cmd, KShell::AbortOnMeta | KShell::TildeExpand, &err); if (err == KShell::NoError && !d->args.isEmpty()) { d->prog = KStandardDirs::findExe(d->args[0]); if (!d->prog.isEmpty()) { d->args.removeFirst(); #ifdef Q_OS_WIN setNativeArguments(QString()); #endif return; } } d->args.clear(); #ifdef Q_OS_UNIX // #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh # if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__GNU__) // If /bin/sh is a symlink, we can be pretty sure that it points to a // POSIX shell - the original bourne shell is about the only non-POSIX // shell still in use and it is always installed natively as /bin/sh. d->prog = QFile::symLinkTarget(QString::fromLatin1("/bin/sh")); if (d->prog.isEmpty()) { // Try some known POSIX shells. d->prog = KStandardDirs::findExe(QString::fromLatin1("ksh")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("ash")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("bash")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("zsh")); if (d->prog.isEmpty()) // We're pretty much screwed, to be honest ... d->prog = QString::fromLatin1("/bin/sh"); } } } } # else d->prog = QString::fromLatin1("/bin/sh"); # endif d->args << QString::fromLatin1("-c") << cmd; #else // Q_OS_UNIX // KMacroExpander::expandMacrosShellQuote(), KShell::quoteArg() and // KShell::joinArgs() may generate these for security reasons. setEnv(PERCENT_VARIABLE, QLatin1String("%")); #ifndef _WIN32_WCE WCHAR sysdir[MAX_PATH + 1]; UINT size = GetSystemDirectoryW(sysdir, MAX_PATH + 1); d->prog = QString::fromUtf16((const ushort *) sysdir, size); d->prog += QLatin1String("\\cmd.exe"); setNativeArguments(QLatin1String("/V:OFF /S /C \"") + cmd + QLatin1Char('"')); #else d->prog = QLatin1String("\\windows\\cmd.exe"); setNativeArguments(QLatin1String("/S /C \"") + cmd + QLatin1Char('"')); #endif #endif }
int executeBuiltinCommand(char* cmd, int argc, char** argv) { int status = SUCCESS; if (strcmp(cmd, "cd") == 0) { char* dest = (char*)malloc(MAX_LENGTH); if (argc == 2) { dest = argv[1]; fixPath(dest); } else if (argc > 2) { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "cd: too many arguments\n"); setTermColor(stderr, oldColor); status = ERROR; } else { sprintf(dest, "%s", getenv("HOME")); } int val = chdir(dest); } else if (strcmp(cmd, "alias") == 0) { if (argc == 3) { char* name = argv[1]; char* word = argv[2]; mapAlias(name, word); } else if (argc == 1) { printAliasTable(); } else { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "alias: need 3 arguments, got %d\n", argc); setTermColor(stderr, oldColor); status = ERROR; } } else if (strcmp(cmd, "unalias") == 0) { if (argc == 2) { char* name = argv[1]; unmapAlias(name); } else { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "unalias: need 2 arguments, got %d\n", argc); setTermColor(stderr, oldColor); status = ERROR; } } else if (strcmp(cmd, "printenv") == 0) { if (argc < 2) { printEnv(); } else { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "printenv: too many arguments"); setTermColor(stderr, oldColor); status = ERROR; } } else if (strcmp(cmd, "setenv") == 0) { if (argc == 3) { char* variable = argv[1]; char* word = argv[2]; setEnv(variable, word); } else { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "setenv: need 3 arguments, got %d\n", argc); setTermColor(stderr, oldColor); status = ERROR; } } else if (strcmp(cmd, "unsetenv") == 0) { if (argc == 2) { char* variable = argv[1]; unsetEnv(variable); } else { const char* oldColor = setTermColor(stderr, KRED); fprintf(stderr, "unsetenv: need 2 arguments, got %d\n", argc); setTermColor(stderr, oldColor); status = ERROR; } } else if (strcmp(cmd, "bye") == 0) { exit(EXIT_SUCCESS); } else { status = ERROR; } return status; }