void verbose_expose(void) { char level[3]; if (verbose_level == 99) { setup_environment("HUGETLB_DEBUG", "yes"); } snprintf(level, sizeof(level), "%d", verbose_level); setup_environment("HUGETLB_VERBOSE", level); }
static void edit_file(const struct passwd *pas, const char *file) { const char *ptr; pid_t pid; pid = xvfork(); if (pid) { /* parent */ wait4pid(pid); return; } /* CHILD - change user and run editor */ /* initgroups, setgid, setuid */ change_identity(pas); setup_environment(pas->pw_shell, SETUP_ENV_CHANGEENV | SETUP_ENV_TO_TMP, pas); ptr = getenv("VISUAL"); if (!ptr) { ptr = getenv("EDITOR"); if (!ptr) ptr = "vi"; } BB_EXECLP(ptr, ptr, file, NULL); bb_perror_msg_and_die("can't execute '%s'", ptr); }
/* REPL */ int main() { atexit(on_exit); init(); global_environment = setup_environment(); init_procs(global_environment); printf("Welcome to BoboScheme\nUse ctrl-c to exit.\n"); write(load_file("src/stdlib.scm")); printf("\n"); while(1) { printf("> "); object_t *r = read(stdin); if(!isemptylist(r)) { write(eval( r, global_environment )); } else { // Ctrl+D exit(0); } printf("\n"); } return 0; }
object *make_environment(void) { object *env; env = setup_environment(); populate_environment(env); return env; }
SchemeObject* SchemeObjectCreator::make_environment() { Environment::Ptr env = std::make_shared<Environment>(); setup_environment(env.get()); SchemeObject* obj = new SchemeEnvironment(env); SchemeGarbageCollector::the_gc().add(obj); return obj; }
int main(int argc, char *argv[]) { int server; char *port = NULL; char *docroot; int do_chroot = 0; char *user = NULL; char *group = NULL; int opt; while ((opt = getopt_long(argc, argv, "p:h:", longopts, NULL)) != -1) { switch (opt) { case 0: break; case 'c': do_chroot = 1; break; case 'u': user = optarg; break; case 'g': group = optarg; break; case 'p': port = optarg; break; case 'h': fprintf(stdout, USAGE, argv[0]); exit(0); case '?': fprintf(stderr, USAGE, argv[0]); exit(1); } } if (optind != argc - 1) { fprintf(stderr, USAGE, argv[0]); exit(1); } docroot = argv[optind]; if (do_chroot) { setup_environment(docroot, user, group); docroot = ""; } install_signal_handlers(); server = listen_socket(port); if (!debug_mode) { openlog(SERVER_NAME, LOG_PID|LOG_NDELAY, LOG_DAEMON); become_daemon(); } server_main(server, docroot); exit(0); }
int main(int argc, char **argv) { t_environment *env; if (argc < 2) ft_putendl_fd_exit("Usage: ft_select [parameters]", 2, 1); env = malloc(sizeof(t_environment)); setup_environment(env, argc, argv); get_set_environment(env); set_signals(&restart); refresh_screen(0); input_loop(); return (0); }
int main(int argc, char *argv[]) { setup_environment(); // any other early configuration should be here if( argc > 1 ){ start(true); } else{ start(false); } return 0; }
pSlip slip_init(void) { pSlip s; pSlipEnvironment env; s = calloc(1, sizeof(uSlip)); assert(s != NULL); s->lstObjects = NewDList(NULL); s->lstSymbols = NewDList(NULL); s->lstStrings = NewDList(NULL); s->lstGlobalEnvironment = NewDList(FreeEnvironment); env = setup_environment(s, NULL, s->singleton_EmptyList, s->singleton_EmptyList); s->singleton_False = s_NewBool(s, S_FALSE); s->singleton_True = s_NewBool(s, S_TRUE); s->singleton_EmptyList = s_NewObject(s); s->singleton_EmptyList->type = eType_EMPTY_LIST; s->singleton_QuoteSymbol = s_NewSymbol(s, "quote"); s->singleton_DefineSymbol = s_NewSymbol(s, "define"); s->singleton_OKSymbol = s_NewSymbol(s, "ok"); s->singleton_SetSymbol = s_NewSymbol(s, "set!"); s->singleton_IFSymbol = s_NewSymbol(s, "if"); s->singleton_Nil = s_NewSymbol(s, "nil"); define_variable(s, s->singleton_Nil, s_NewObject(s), env); s->singleton_Lambda = s_NewSymbol(s, "lambda"); s->singleton_Begin = s_NewSymbol(s, "begin"); s->singleton_Cond = s_NewSymbol(s, "cond"); s->singleton_Else = s_NewSymbol(s, "else"); s->singleton_Let = s_NewSymbol(s, "let"); s->obj_id = USER_OBJECT_ID_START; s->running = SLIP_RUNNING; s->parse_data.lstTokens = NewDList(FreeToken); slip_install_primitives(s, env); return s; }
int main (int argc, char *argv[]) { /* * all the arguments are intended to feed the real shell */ if (argc > 1) shargs = &(argv[1]); else { // Cal mostrar l'ajuda i sortir fprintf (stderr, PACKAGE_NAME": Arguments needed!\n"); shargs = NULL; exit (1); } // process_arguments(argc,argv); process_mpitrace_arguments (argc - 1, &argv[1]); setup_environment (); launch (shargs); return 0; }
int main(void) { int r = 1, wait = 1, prefix_args_len = -1, needs_env_setup = 1, is_git_command = 1, full_path = 1, skip_arguments = 0, allocate_console = 0, show_console = 0, append_quote_to_cmdline = 0; WCHAR exepath[MAX_PATH], exe[MAX_PATH], top_level_path[MAX_PATH]; LPWSTR cmd = NULL, exep = exe, prefix_args = NULL, basename; LPWSTR working_directory = NULL; /* Determine MSys2-based Git path. */ swprintf(msystem_bin, sizeof(msystem_bin), L"mingw%d\\bin", (int) sizeof(void *) * 8); *top_level_path = L'\0'; /* get the installation location */ GetModuleFileName(NULL, exepath, MAX_PATH); if (!PathRemoveFileSpec(exepath)) { fwprintf(stderr, L"Invalid executable path: %s\n", exepath); ExitProcess(1); } basename = exepath + wcslen(exepath) + 1; if (configure_via_resource(basename, exepath, exep, &prefix_args, &prefix_args_len, &is_git_command, &working_directory, &full_path, &skip_arguments, &allocate_console, &show_console, &append_quote_to_cmdline)) { /* do nothing */ } else if (!wcsicmp(basename, L"git-gui.exe")) { static WCHAR buffer[BUFSIZE]; wait = 0; allocate_console = 1; initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"wish.exe"); if (_waccess(exe, 0) != -1) swprintf(buffer, BUFSIZE, L"\"%s\\%.*s\\libexec\\git-core\"", top_level_path, wcslen(msystem_bin) - 4, msystem_bin); else { wcscpy(exe, top_level_path); PathAppend(exe, L"mingw\\bin\\wish.exe"); swprintf(buffer, BUFSIZE, L"\"%s\\mingw\\libexec\\git-core\"", top_level_path); } PathAppend(buffer, L"git-gui"); prefix_args = buffer; prefix_args_len = wcslen(buffer); } else if (!wcsnicmp(basename, L"git-", 4)) { needs_env_setup = 0; /* Call a builtin */ prefix_args = basename + 4; prefix_args_len = wcslen(prefix_args); if (!wcsicmp(prefix_args + prefix_args_len - 4, L".exe")) prefix_args_len -= 4; /* set the default exe module */ wcscpy(exe, exepath); PathAppend(exe, L"git.exe"); } else if (!wcsicmp(basename, L"git.exe")) { initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"git.exe"); if (_waccess(exe, 0) == -1) { wcscpy(exe, top_level_path); PathAppend(exe, L"bin\\git.exe"); } } else if (!wcsicmp(basename, L"gitk.exe")) { static WCHAR buffer[BUFSIZE]; allocate_console = 1; initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); swprintf(buffer, BUFSIZE, L"\"%s\"", top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"wish.exe"); if (_waccess(exe, 0) != -1) PathAppend(buffer, msystem_bin); else { wcscpy(exe, top_level_path); PathAppend(exe, L"mingw\\bin\\wish.exe"); PathAppend(buffer, L"mingw\\bin"); } PathAppend(buffer, L"gitk"); prefix_args = buffer; prefix_args_len = wcslen(buffer); } if (needs_env_setup) { if (!top_level_path[0]) initialize_top_level_path(top_level_path, exepath, msystem_bin, -4); setup_environment(top_level_path, full_path); } cmd = fixup_commandline(exepath, &exep, &wait, prefix_args, prefix_args_len, is_git_command, skip_arguments, append_quote_to_cmdline); if (working_directory == (LPWSTR)1) { int len = GetEnvironmentVariable(L"HOME", NULL, 0); if (len) { working_directory = malloc(sizeof(WCHAR) * len); GetEnvironmentVariable(L"HOME", working_directory, len); } } { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT; HANDLE console_handle; BOOL br = FALSE; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); if (allocate_console | show_console) creation_flags |= CREATE_NEW_CONSOLE; else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) CloseHandle(console_handle); else { #define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE STD_HANDLE(Input, INPUT_HANDLE); STD_HANDLE(Output, OUTPUT_HANDLE); STD_HANDLE(Error, ERROR_HANDLE); si.dwFlags = STARTF_USESTDHANDLES; creation_flags |= CREATE_NO_WINDOW; } if (show_console) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; } br = CreateProcess(/* module: null means use command line */ exep, cmd, /* modified command line */ NULL, /* process handle inheritance */ NULL, /* thread handle inheritance */ /* handles inheritable? */ allocate_console ? FALSE : TRUE, creation_flags, NULL, /* environment: use parent */ working_directory, /* use parent's */ &si, &pi); if (br) { if (wait) WaitForSingleObject(pi.hProcess, INFINITE); if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r)) print_error(L"error reading exit code", GetLastError()); CloseHandle(pi.hProcess); } else { print_error(L"error launching git", GetLastError()); r = 1; } } free(cmd); ExitProcess(r); }
int main(int argc, char **argv) { int ret = EXIT_SUCCESS; int i; struct passwd *pwd; static FILE *fp; char *to_chdir; char *from_user; char *cwd = get_current_dir_name(); char cmdpath[PATH_MAX]; if (argc < 3) { fprintf(stderr, "Usage: runasuser user program [args ...]\n"); ret = EXIT_FAILURE; goto out; } pwd = getpwnam(argv[1]); if (!pwd) { fprintf(stderr, "Error: No such user %s\n", argv[1]); ret = EXIT_FAILURE; goto out; } fp = fopen("/etc/runasuser.conf", "r"); if (!fp) { fp = fopen("/usr/local/etc/runasuser.conf", "r"); if (!fp) { perror("fopen runasuser.conf"); ret = EXIT_FAILURE; goto out; } } /* Check the user calling runasuser */ pwd = getpwuid(getuid()); /* Yes, we want the _real_ uid */ from_user = pwd->pw_name; /* Allow root to run as any user */ if (getuid() > 0) { if (!check_user_auth(from_user, argv[1], fp)) { fprintf(stderr, "Error: You are not authorized to run " "as %s\n", argv[1]); ret = EXIT_FAILURE; goto out; } } fclose(fp); /* Drop all supplementary groups of the calling user */ if (setgroups(0, NULL) != 0) { perror("setgroups"); ret = EXIT_FAILURE; goto out; } pwd = getpwnam(argv[1]); /* * Set the supplementary groups for the new user * * This needs to come before setuid() as this needs the * CAP_SETGID capability */ if (initgroups(pwd->pw_name, pwd->pw_gid) != 0) { perror("initgroups"); ret = EXIT_FAILURE; goto out; } /* * Order is important, if setuid comes first, * then the setgid is unable to perform. */ if (setgid(pwd->pw_gid) != 0) { perror("setgid"); ret = EXIT_FAILURE; goto out; } if (setuid(pwd->pw_uid) != 0) { /* It's important to bail if the setuid() fails. */ perror("setuid"); ret = EXIT_FAILURE; goto out; } /* * Check whether to chdir() into the users home directory * * Needs to come before clearenv() * * YES, if RUNASUSER_CHDIR = 1 (default) * NO, if RUNASUSER_CHDIR = 0 */ to_chdir = getenv("RUNASUSER_CHDIR"); if (!to_chdir || atoi(to_chdir) != 0) { if (chdir(pwd->pw_dir) != 0) { perror("chdir"); ret = EXIT_FAILURE; goto out; } } /* Clear the shell environment before setting up a new one */ if (clearenv() != 0) { perror("clearenv"); ret = EXIT_FAILURE; goto out; } if (setenv("HOME", pwd->pw_dir, 1) != 0) { SETENV_ERR("HOME"); ret = EXIT_FAILURE; goto out; } if (setenv("USER", pwd->pw_name, 1) != 0) { SETENV_ERR("USER"); ret = EXIT_FAILURE; goto out; } if (setenv("RUNASUSER_USER", from_user, 1) != 0) { SETENV_ERR("RUNASUSER_USER"); ret = EXIT_FAILURE; goto out; } if (setenv("PATH", "/usr/local/bin:/bin:/usr/bin", 1) != 0) { SETENV_ERR("PATH"); ret = EXIT_FAILURE; goto out; } /* Read the rest of the environment from the config file */ fp = fopen("/etc/runasuser.env.conf", "r"); if (!fp) fp = fopen("/usr/local/etc/runasuser.env.conf", "r"); if (fp) { if (!setup_environment(pwd->pw_name, fp)) { ret = EXIT_FAILURE; goto out; } fclose(fp); } /* check if the command to run exists */ if (!command_found(argv[2], cmdpath)) { fprintf(stderr, "runasuser: %s: command not found\n", argv[2]); ret = EXIT_FAILURE; goto out; } printf("Execing [ "); for (i = 2; i < argc; i++) printf("%s ", argv[i]); printf("]\n"); /* Log info to syslog, same format as sudo */ ret = do_log(from_user, pwd->pw_name, cwd, cmdpath, argv); if (!ret) { ret = EXIT_FAILURE; goto out; } /* Close all open file descriptors above 2 */ close_fds(); if (execvp(argv[2], argv + 2) == -1) { perror("exec"); ret = EXIT_FAILURE; } out: free(cwd); exit(ret); }
/* Run the given command line as if with exec. What we actually do is fork the command line as a subprocess, then loop, relaying data between the socket and the subprocess. This allows Ncat to handle SSL from the socket and give plain text to the subprocess, and also allows things like logging and line delays. Never returns. */ void netexec(struct fdinfo *info, char *cmdexec) { int child_stdin[2]; int child_stdout[2]; int pid; int crlf_state; char buf[DEFAULT_TCP_BUF_LEN]; int maxfd; if (o.debug) { switch (o.execmode) { case EXEC_SHELL: logdebug("Executing with shell: %s\n", cmdexec); break; #ifdef HAVE_LUA case EXEC_LUA: logdebug("Executing as lua script: %s\n", cmdexec); break; #endif default: logdebug("Executing: %s\n", cmdexec); break; } } if (pipe(child_stdin) == -1 || pipe(child_stdout) == -1) bye("Can't create child pipes: %s", strerror(errno)); pid = fork(); if (pid == -1) bye("Error in fork: %s", strerror(errno)); if (pid == 0) { /* This is the child process. Exec the command. */ close(child_stdin[1]); close(child_stdout[0]); /* We might have turned off SIGPIPE handling in ncat_listen.c. Since the child process SIGPIPE might mean that the connection got broken, ignoring it could result in an infinite loop if the code here ignores the error codes of read()/write() calls. So, just in case, let's restore SIGPIPE so that writing to a broken pipe results in killing the child process. */ Signal(SIGPIPE, SIG_DFL); /* rearrange stdin and stdout */ Dup2(child_stdin[0], STDIN_FILENO); Dup2(child_stdout[1], STDOUT_FILENO); setup_environment(info); switch (o.execmode) { char **cmdargs; case EXEC_SHELL: execl("/bin/sh", "sh", "-c", cmdexec, (void *) NULL); break; #ifdef HAVE_LUA case EXEC_LUA: lua_run(); break; #endif default: cmdargs = cmdline_split(cmdexec); execv(cmdargs[0], cmdargs); break; } /* exec failed. */ die("exec"); } close(child_stdin[0]); close(child_stdout[1]); maxfd = child_stdout[0]; if (info->fd > maxfd) maxfd = info->fd; /* This is the parent process. Enter a "caretaker" loop that reads from the socket and writes to the subprocess, and reads from the subprocess and writes to the socket. We exit the loop on any read error (or EOF). On a write error we just close the opposite side of the conversation. */ crlf_state = 0; for (;;) { fd_set fds; int r, n_r; FD_ZERO(&fds); FD_SET(info->fd, &fds); FD_SET(child_stdout[0], &fds); r = fselect(maxfd + 1, &fds, NULL, NULL, NULL); if (r == -1) { if (errno == EINTR) continue; else break; } if (FD_ISSET(info->fd, &fds)) { int pending; do { n_r = ncat_recv(info, buf, sizeof(buf), &pending); if (n_r <= 0) goto loop_end; write_loop(child_stdin[1], buf, n_r); } while (pending); } if (FD_ISSET(child_stdout[0], &fds)) { char *crlf = NULL, *wbuf; n_r = read(child_stdout[0], buf, sizeof(buf)); if (n_r <= 0) break; wbuf = buf; if (o.crlf) { if (fix_line_endings((char *) buf, &n_r, &crlf, &crlf_state)) wbuf = crlf; } ncat_send(info, wbuf, n_r); if (crlf != NULL) free(crlf); } } loop_end: #ifdef HAVE_OPENSSL if (info->ssl != NULL) { SSL_shutdown(info->ssl); SSL_free(info->ssl); } #endif close(info->fd); exit(0); }
int main ( int argc , char * argv[] ) { if ( argc != 3 ) { cout << "Usage ./a.out <# students> <# course>" << endl; exit(0); } v.s = atoi(argv[1]); v.c = atoi(argv[2]); setup_environment(); sem_init ( &mutex , 0 , 1 ); for ( int i = 0 ; i < v.s ; i++ ) { pthread_create ( &s_thread[i] , NULL , student_thread , NULL ); } for ( int i = 0 ; i < v.s ; i++ ) { pthread_join ( s_thread[i] , NULL ); } int count = 0; cout << "Students who were not allocated all four courses : " << endl; for ( int i = 0 ; i < v.s ; i++ ) { /* Check for each type to knowledge_spectrum should be cover for course */ /* if ( s[i].c[0] == 0 && s[i].c[1] == 0 && s[i].c[2] == 0 && s[i].c[3] == 0 ) { count ++; } */ /* Check for the total number of courses to be allocated i.e. courses that can be allocated to the students can be from any knowledge spectrum */ if ( s[i].courses_to_be_allocated > 0 ) { cout << "Student #" << s[i].id << endl; count ++; } } for ( int i = 0 ; i < v.c ; i++ ) { fp << "Course #" << c[i].id << " has " << c[i].no_students << " students." << endl; } cout << "total : " << count << endl; /*for ( int i = 0 ; i < v.c ; i++ ) { cout << "course # " << c[i].id << " no_students = " << c[i].no_students << endl; }*/ //print_statistics(); fp.close(); return 0; }
static pSlipObject slip_eval(pSlip gd, pSlipObject exp, pSlipEnvironment env) { pSlipObject proc; pSlipObject args; tailcall: if (is_self_evaluating(exp) == S_TRUE) { return exp; } else if (is_variable(exp) == S_TRUE) { return lookup_variable_value(gd, exp, env); } else if (is_quoted(gd, exp) == S_TRUE) { return text_of_quotation(exp); } else if (is_assignment(gd, exp) == S_TRUE) { return eval_assignment(gd, exp, env); } else if (is_definition(gd, exp) == S_TRUE) { return eval_definition(gd, exp, env); } else if (is_if(gd, exp) == S_TRUE) { exp = is_true(gd, slip_eval(gd, if_predicate(exp), env)) == S_TRUE ? if_consequent(exp) : if_alternative(gd, exp); goto tailcall; } else if (is_lambda(gd, exp) == S_TRUE) { return s_NewCompoundProc(gd, lambda_parameters(exp), lambda_body(exp), env); } else if (is_begin(gd, exp) == S_TRUE) { exp = begin_actions(exp); while (!is_last_exp(gd, exp)) { slip_eval(gd, first_exp(exp), env); exp = rest_exps(exp); } exp = first_exp(exp); goto tailcall; } else if (is_cond(gd, exp) == S_TRUE) { exp = cond_to_if(gd, exp); goto tailcall; } else if (is_let(gd, exp) == S_TRUE) { exp = let_to_application(gd, exp); goto tailcall; } else if (is_application(exp) == S_TRUE) { proc = slip_eval(gd, slip_operator(exp), env); if (proc == NULL) return gd->singleton_False; if (proc->type == eType_PRIMITIVE_PROC || proc->type == eType_COMPOUND_PROC) { args = list_of_values(gd, operands(exp), env); if (args == NULL) return gd->singleton_False; if (sIsObject_PrimitiveProc(proc) == S_TRUE) { return proc->data.prim_proc.func(gd, args); } else if (sIsObject_CompoundProc(proc) == S_TRUE) { env = setup_environment(gd, proc->data.comp_proc.env, proc->data.comp_proc.params, args); exp = make_begin(gd, proc->data.comp_proc.code); goto tailcall; } else { throw_error(gd, "unknown procedure type\n"); return gd->singleton_False; } } else return proc; } else { throw_error(gd, "cannot eval unknown expression type\n"); return NULL; } throw_error(gd, "what??\n"); return NULL; }
int su_main(int argc UNUSED_PARAM, char **argv) { unsigned flags; char *opt_shell = NULL; char *opt_command = NULL; const char *opt_username = "******"; struct passwd *pw; uid_t cur_uid = getuid(); const char *tty; #if ENABLE_FEATURE_UTMP char user_buf[64]; #endif const char *old_user; flags = getopt32(argv, "mplc:s:", &opt_command, &opt_shell); //argc -= optind; argv += optind; if (argv[0] && LONE_DASH(argv[0])) { flags |= SU_OPT_l; argv++; } /* get user if specified */ if (argv[0]) { opt_username = argv[0]; argv++; } if (ENABLE_FEATURE_SU_SYSLOG) { /* The utmp entry (via getlogin) is probably the best way to * identify the user, especially if someone su's from a su-shell. * But getlogin can fail -- usually due to lack of utmp entry. * in this case resort to getpwuid. */ #if ENABLE_FEATURE_UTMP old_user = user_buf; if (getlogin_r(user_buf, sizeof(user_buf)) != 0) #endif { pw = getpwuid(cur_uid); old_user = pw ? xstrdup(pw->pw_name) : ""; } tty = xmalloc_ttyname(2); if (!tty) { tty = "none"; } openlog(applet_name, 0, LOG_AUTH); } pw = xgetpwnam(opt_username); if (cur_uid == 0 || correct_password(pw)) { if (ENABLE_FEATURE_SU_SYSLOG) syslog(LOG_NOTICE, "%c %s %s:%s", '+', tty, old_user, opt_username); } else { if (ENABLE_FEATURE_SU_SYSLOG) syslog(LOG_NOTICE, "%c %s %s:%s", '-', tty, old_user, opt_username); bb_error_msg_and_die("incorrect password"); } if (ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_SU_SYSLOG) { closelog(); } if (!opt_shell && (flags & SU_OPT_mp)) { /* -s SHELL is not given, but "preserve env" opt is */ opt_shell = getenv("SHELL"); } #if ENABLE_FEATURE_SU_CHECKS_SHELLS if (opt_shell && cur_uid != 0 && pw->pw_shell && restricted_shell(pw->pw_shell)) { /* The user being su'd to has a nonstandard shell, and so is * probably a uucp account or has restricted access. Don't * compromise the account by allowing access with a standard * shell. */ bb_error_msg("using restricted shell"); opt_shell = NULL; /* ignore -s PROG */ } /* else: user can run whatever he wants via "su -s PROG USER". * This is safe since PROG is run under user's uid/gid. */ #endif if (!opt_shell) opt_shell = pw->pw_shell; change_identity(pw); setup_environment(opt_shell, ((flags & SU_OPT_l) / SU_OPT_l * SETUP_ENV_CLEARENV) + (!(flags & SU_OPT_mp) * SETUP_ENV_CHANGEENV), pw); IF_SELINUX(set_current_security_context(NULL);)
int main(int argc, char **argv) { demux_res_t demux_res; unsigned int output_size, i; set_endian(); setup_environment(argc, argv); input_stream = stream_create_file(input_file, 1); if (!input_stream) { fprintf(stderr, "failed to create input stream from file\n"); return 0; } /* if qtmovie_read returns successfully, the stream is up to * the movie data, which can be used directly by the decoder */ if (!qtmovie_read(input_stream, &demux_res)) { fprintf(stderr, "failed to load the QuickTime movie headers\n"); return 0; } /* initialise the sound converter */ init_sound_converter(&demux_res); /* write wav output headers */ if (write_wav_format) { /* calculate output size */ output_size = 0; for (i = 0; i < demux_res.num_sample_byte_sizes; i++) { unsigned int thissample_duration; unsigned int thissample_bytesize; get_sample_info(&demux_res, i, &thissample_duration, &thissample_bytesize); output_size += thissample_duration * (demux_res.sample_size / 8) * demux_res.num_channels; } wavwriter_writeheaders(output_file, output_size, demux_res.num_channels, demux_res.sample_rate, demux_res.sample_size); } /* will convert the entire buffer */ GetBuffer(&demux_res); stream_destroy(input_stream); if (output_opened) fclose(output_file); if (input_opened) fclose(input_file); return 0; }
static void doit (void) { u_char buf[BUFSIZ]; u_char *p; struct sockaddr_storage thisaddr_ss; struct sockaddr *thisaddr = (struct sockaddr *)&thisaddr_ss; struct sockaddr_storage thataddr_ss; struct sockaddr *thataddr = (struct sockaddr *)&thataddr_ss; struct sockaddr_storage erraddr_ss; struct sockaddr *erraddr = (struct sockaddr *)&erraddr_ss; socklen_t thisaddr_len, thataddr_len; int port; int errsock = -1; char *client_user = NULL, *server_user = NULL, *cmd = NULL; struct passwd *pwd; int s = STDIN_FILENO; char **env; int ret; char that_host[NI_MAXHOST]; thisaddr_len = sizeof(thisaddr_ss); if (getsockname (s, thisaddr, &thisaddr_len) < 0) syslog_and_die("getsockname: %s", strerror(errno)); thataddr_len = sizeof(thataddr_ss); if (getpeername (s, thataddr, &thataddr_len) < 0) syslog_and_die ("getpeername: %s", strerror(errno)); /* check for V4MAPPED addresses? */ if (do_kerberos == 0 && !is_reserved(socket_get_port(thataddr))) fatal(s, NULL, "Permission denied."); p = buf; port = 0; for(;;) { if (net_read (s, p, 1) != 1) syslog_and_die ("reading port number: %s", strerror(errno)); if (*p == '\0') break; else if (isdigit(*p)) port = port * 10 + *p - '0'; else syslog_and_die ("non-digit in port number: %c", *p); } if (do_kerberos == 0 && !is_reserved(htons(port))) fatal(s, NULL, "Permission denied."); if (port) { int priv_port = IPPORT_RESERVED - 1; /* * There's no reason to require a ``privileged'' port number * here, but for some reason the brain dead rsh clients * do... :-( */ erraddr->sa_family = thataddr->sa_family; socket_set_address_and_port (erraddr, socket_get_address (thataddr), htons(port)); /* * we only do reserved port for IPv4 */ if (erraddr->sa_family == AF_INET) errsock = rresvport (&priv_port); else errsock = socket (erraddr->sa_family, SOCK_STREAM, 0); if (errsock < 0) syslog_and_die ("socket: %s", strerror(errno)); if (connect (errsock, erraddr, socket_sockaddr_size (erraddr)) < 0) { syslog (LOG_WARNING, "connect: %s", strerror(errno)); close (errsock); } } if(do_kerberos) { if (net_read (s, buf, 4) != 4) syslog_and_die ("reading auth info: %s", strerror(errno)); #ifdef KRB5 if((do_kerberos & DO_KRB5) && recv_krb5_auth (s, buf, thisaddr, thataddr, &client_user, &server_user, &cmd) == 0) auth_method = AUTH_KRB5; else #endif /* KRB5 */ syslog_and_die ("unrecognized auth protocol: %x %x %x %x", buf[0], buf[1], buf[2], buf[3]); } else { if(recv_bsd_auth (s, buf, (struct sockaddr_in *)thisaddr, (struct sockaddr_in *)thataddr, &client_user, &server_user, &cmd) == 0) { auth_method = AUTH_BROKEN; if(do_vacuous) { printf("Remote host requires Kerberos authentication\n"); exit(0); } } else syslog_and_die("recv_bsd_auth failed"); } if (client_user == NULL || server_user == NULL || cmd == NULL) syslog_and_die("mising client/server/cmd"); pwd = getpwnam (server_user); if (pwd == NULL) fatal (s, NULL, "Login incorrect."); if (*pwd->pw_shell == '\0') pwd->pw_shell = _PATH_BSHELL; if (pwd->pw_uid != 0 && access (_PATH_NOLOGIN, F_OK) == 0) fatal (s, NULL, "Login disabled."); ret = getnameinfo_verified (thataddr, thataddr_len, that_host, sizeof(that_host), NULL, 0, 0); if (ret) fatal (s, NULL, "getnameinfo: %s", gai_strerror(ret)); if (login_access(pwd, that_host) == 0) { syslog(LOG_NOTICE, "Kerberos rsh denied to %s from %s", server_user, that_host); fatal(s, NULL, "Permission denied."); } #ifdef HAVE_GETSPNAM { struct spwd *sp; long today; sp = getspnam(server_user); if (sp != NULL) { today = time(0)/(24L * 60 * 60); if (sp->sp_expire > 0) if (today > sp->sp_expire) fatal(s, NULL, "Account has expired."); } } #endif #ifdef HAVE_SETLOGIN if (setlogin(pwd->pw_name) < 0) syslog(LOG_ERR, "setlogin() failed: %s", strerror(errno)); #endif #ifdef HAVE_SETPCRED if (setpcred (pwd->pw_name, NULL) == -1) syslog(LOG_ERR, "setpcred() failure: %s", strerror(errno)); #endif /* HAVE_SETPCRED */ /* Apply limits if not root */ if(pwd->pw_uid != 0) { const char *file = _PATH_LIMITS_CONF; read_limits_conf(file, pwd); } if (initgroups (pwd->pw_name, pwd->pw_gid) < 0) fatal (s, "initgroups", "Login incorrect."); if (setgid(pwd->pw_gid) < 0) fatal (s, "setgid", "Login incorrect."); if (setuid (pwd->pw_uid) < 0) fatal (s, "setuid", "Login incorrect."); if (chdir (pwd->pw_dir) < 0) fatal (s, "chdir", "Remote directory."); if (errsock >= 0) { if (dup2 (errsock, STDERR_FILENO) < 0) fatal (s, "dup2", "Cannot dup stderr."); close (errsock); } else { if (dup2 (STDOUT_FILENO, STDERR_FILENO) < 0) fatal (s, "dup2", "Cannot dup stderr."); } #ifdef KRB5 { int fd; if (!do_unique_tkfile) snprintf(tkfile,sizeof(tkfile),"FILE:/tmp/krb5cc_%lu", (unsigned long)pwd->pw_uid); else if (*tkfile=='\0') { snprintf(tkfile,sizeof(tkfile),"FILE:/tmp/krb5cc_XXXXXX"); fd = mkstemp(tkfile+5); close(fd); unlink(tkfile+5); } if (kerberos_status) krb5_start_session(); } #endif setup_environment (&env, pwd); if (do_encrypt) { setup_copier (errsock >= 0); } else { if (net_write (s, "", 1) != 1) fatal (s, "net_write", "write failed"); } #if defined(KRB5) if(k_hasafs()) { char cell[64]; if(do_newpag) k_setpag(); /* XXX */ if (kerberos_status) { krb5_ccache ccache; krb5_error_code status; status = krb5_cc_resolve (context, tkfile, &ccache); if (!status) { if (k_afs_cell_of_file (pwd->pw_dir, cell, sizeof(cell)) == 0) krb5_afslog_uid_home(context, ccache, cell, NULL, pwd->pw_uid, pwd->pw_dir); krb5_afslog_uid_home(context, ccache, NULL, NULL, pwd->pw_uid, pwd->pw_dir); krb5_cc_close (context, ccache); } } } #endif /* KRB5 */ execle (pwd->pw_shell, pwd->pw_shell, "-c", cmd, NULL, env); err(1, "exec %s", pwd->pw_shell); }
int su_main ( int argc, char **argv ) { unsigned long flags; char *opt_shell = 0; char *opt_command = 0; char *opt_username = DEFAULT_USER; char **opt_args = 0; struct passwd *pw; uid_t cur_uid = getuid(); #if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE ) const char *tty; const char *old_user; #endif flags = bb_getopt_ulflags(argc, argv, "mplc:s:", &opt_command, &opt_shell); #define SU_OPT_m (3) #define SU_OPT_p (3) #define SU_OPT_l (4) if (optind < argc && argv[optind][0] == '-' && argv[optind][1] == 0) { flags |= SU_OPT_l; ++optind; } /* get user if specified */ if ( optind < argc ) opt_username = argv [optind++]; if ( optind < argc ) opt_args = argv + optind; #if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE ) #ifdef CONFIG_FEATURE_UTMP /* The utmp entry (via getlogin) is probably the best way to identify the user, especially if someone su's from a su-shell. */ old_user = getlogin ( ); if ( !old_user ) #endif { /* getlogin can fail -- usually due to lack of utmp entry. Resort to getpwuid. */ pw = getpwuid ( cur_uid ); old_user = ( pw ? pw->pw_name : "" ); } tty = ttyname ( 2 ); if(!tty) tty = "none"; openlog ( bb_applet_name, 0, LOG_AUTH ); #endif pw = getpwnam ( opt_username ); if ( !pw ) bb_error_msg_and_die ( "user %s does not exist", opt_username ); /* Make sure pw->pw_shell is non-NULL. It may be NULL when NEW_USER is a username that is retrieved via NIS (YP), but that doesn't have a default shell listed. */ if ( !pw->pw_shell || !pw->pw_shell [0] ) pw->pw_shell = (char *) DEFAULT_SHELL; if ((( cur_uid == 0 ) || correct_password ( pw ))) { log_su_successful(pw->pw_uid, old_user, tty ); } else { log_su_failure (pw->pw_uid, old_user, tty ); bb_error_msg_and_die ( "incorrect password" ); } #if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE ) closelog(); #endif if ( !opt_shell && (flags & SU_OPT_p)) opt_shell = getenv ( "SHELL" ); if ( opt_shell && cur_uid && restricted_shell ( pw->pw_shell )) { /* The user being su'd to has a nonstandard shell, and so is probably a uucp account or has restricted access. Don't compromise the account by allowing access with a standard shell. */ fputs ( "using restricted shell\n", stderr ); opt_shell = 0; } if ( !opt_shell ) opt_shell = pw->pw_shell; change_identity ( pw ); setup_environment(opt_shell, flags & SU_OPT_l, !(flags & SU_OPT_p), pw); #if ENABLE_SELINUX set_current_security_context(NULL); #endif run_shell(opt_shell, flags & SU_OPT_l, opt_command, (const char**)opt_args); return EXIT_FAILURE; }
static void initialize (int argc, char **argv) { gboolean disable_tcp = FALSE; GdkDisplay *dpy; XfceRc *rc; for (++argv; --argc > 0; ++argv) { if (strcmp (*argv, "--version") == 0) { printf ("%s (Xfce %s)\n\n" "Copyright (c) 2003-2006\n" " The Xfce development team. All rights reserved.\n\n" "Written for Xfce by Benedikt Meurer <*****@*****.**>.\n\n" "Built with Gtk+-%d.%d.%d, running with Gtk+-%d.%d.%d.\n\n" "Please report bugs to <%s>.\n", PACKAGE_STRING, xfce_version_string (), GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION, gtk_major_version, gtk_minor_version, gtk_micro_version, PACKAGE_BUGREPORT); exit (EXIT_SUCCESS); } else if (strcmp (*argv, "--disable-tcp") == 0) { disable_tcp = TRUE; } else { usage (strcmp (*argv, "--help") == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } } setup_environment (); rc = xfsm_open_config (TRUE); dpy = gdk_display_get_default (); init_display (dpy, rc, disable_tcp); /* verify that the DNS settings are ok */ xfsm_splash_screen_next (splash_screen, _("Verifying DNS settings")); xfsm_dns_check (); xfsm_splash_screen_next (splash_screen, _("Loading session data")); xfce_rc_set_group (rc, "Compatibility"); compat_gnome = xfce_rc_read_bool_entry (rc, "LaunchGnome", FALSE); compat_kde = xfce_rc_read_bool_entry (rc, "LaunchKDE", FALSE); xfce_rc_set_group (rc, "General"); xfsm_startup_init (rc); xfsm_manager_init (rc); /* cleanup obsolete entries */ xfce_rc_set_group (rc, "General"); if (xfce_rc_has_entry (rc, "ConfirmLogout")) xfce_rc_delete_entry (rc, "ConfirmLogout", FALSE); if (xfce_rc_has_entry (rc, "AlwaysDisplayChooser")) xfce_rc_delete_entry (rc, "AlwaysDisplayChooser", FALSE); xfce_rc_delete_group (rc, "Splash Theme", FALSE); xfce_rc_close (rc); }
int main(int argc, Char *argv[]) { boolean canbeplotted; boolean wasplotted = false; #ifdef MAC OSErr retcode; FInfo fndrinfo; #ifdef OSX_CARBON FSRef fileRef; FSSpec fileSpec; #endif #ifdef __MWERKS__ SIOUXSetTitle("\pPHYLIP: Drawtree"); #endif argv[0] = "Drawgram"; #endif grbg = NULL; progname = argv[0]; #ifndef X_DISPLAY_MISSING nargc=1; nargv=argv; #endif init(argc, argv); emboss_getoptions("fdrawgram",argc,argv); setup_environment(argv, &canbeplotted); user_loop(&canbeplotted); if (!((previewer == winpreview || previewer == xpreview || previewer == mac) && (winaction == quitnow))) { previewing = false; initplotter(spp,fontname); numlines = dotmatrix ? ((long)floor(yunitspercm * ysize + 0.5)/strpdeep) : 1; if (plotter != ibm) printf("\nWriting plot file ...\n"); drawit(fontname,&xoffset,&yoffset,numlines,root); finishplotter(); FClose(plotfile); wasplotted = true; printf("\nPlot written to file \"%s\"\n\n", pltfilename); } FClose(intree); #ifdef MAC if (plotter == pict && wasplotted){ #ifdef OSX_CARBON FSPathMakeRef((unsigned char *)pltfilename, &fileRef, NULL); FSGetCatalogInfo(&fileRef, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL); FSpGetFInfo(&fileSpec, &fndrinfo); fndrinfo.fdType='PICT'; fndrinfo.fdCreator='MDRW'; FSpSetFInfo(&fileSpec, &fndrinfo); #else retcode=GetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo); fndrinfo.fdType='PICT'; fndrinfo.fdCreator='MDRW'; retcode=SetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo); #endif } if (plotter == lw && wasplotted){ #ifdef OSX_CARBON FSPathMakeRef((unsigned char *)pltfilename, &fileRef, NULL); FSGetCatalogInfo(&fileRef, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL); FSpGetFInfo(&fileSpec, &fndrinfo); fndrinfo.fdType='TEXT'; FSpSetFInfo(&fileSpec, &fndrinfo); #else retcode=GetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo); fndrinfo.fdType='TEXT'; retcode=SetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo); #endif } #endif printf("Done.\n\n"); #ifdef WIN32 phyRestoreConsoleAttributes(); #endif embExit(); return 0; }
void CPCD::Process::do_exec() { unsigned i; #ifdef _WIN32 Vector<BaseString> saved; char *cwd = 0; save_environment(m_env.c_str(), saved); #endif setup_environment(m_env.c_str()); char **argv = BaseString::argify(m_path.c_str(), m_args.c_str()); if(strlen(m_cwd.c_str()) > 0) { #ifdef _WIN32 cwd = getcwd(0, 0); if(!cwd) { logger.critical("Couldn't getcwd before spawn"); } #endif int err = chdir(m_cwd.c_str()); if(err == -1) { BaseString err; logger.error("%s: %s\n", m_cwd.c_str(), strerror(errno)); _exit(1); } } #ifndef _WIN32 Vector<BaseString> ulimit; m_ulimit.split(ulimit); for(i = 0; i<ulimit.size(); i++){ if(ulimit[i].trim().length() > 0 && set_ulimit(ulimit[i]) != 0){ _exit(1); } } #endif const char *nul = IF_WIN("nul:", "/dev/null"); int fdnull = open(nul, O_RDWR, 0); if(fdnull == -1) { logger.error("Cannot open `%s': %s\n", nul, strerror(errno)); _exit(1); } BaseString * redirects[] = { &m_stdin, &m_stdout, &m_stderr }; int fds[3]; #ifdef _WIN32 int std_dups[3]; #endif for (i = 0; i < 3; i++) { #ifdef _WIN32 std_dups[i] = dup(i); #endif if (redirects[i]->empty()) { #ifndef DEBUG dup2(fdnull, i); #endif continue; } if((* redirects[i]) == "2>&1" && i == 2){ dup2(fds[1], 2); continue; } /** * Make file */ int flags = 0; int mode = S_IRUSR | S_IWUSR ; if(i == 0){ flags |= O_RDONLY; } else { flags |= O_WRONLY | O_CREAT | O_APPEND; } int f = fds[i]= open(redirects[i]->c_str(), flags, mode); if(f == -1){ logger.error("Cannot redirect %u to/from '%s' : %s\n", i, redirects[i]->c_str(), strerror(errno)); _exit(1); } dup2(f, i); #ifdef _WIN32 close(f); #endif } #ifndef _WIN32 /* Close all filedescriptors */ for(i = STDERR_FILENO+1; (int)i < getdtablesize(); i++) close(i); execv(m_path.c_str(), argv); /* XXX If we reach this point, an error has occurred, but it's kind of hard * to report it, because we've closed all files... So we should probably * create a new logger here */ logger.error("Exec failed: %s\n", strerror(errno)); /* NOTREACHED */ #else // Get full path to cygwins shell FILE *fpipe = _popen("sh -c 'cygpath -w `which sh`'", "rt"); char buf[MAX_PATH]; require(fgets(buf, MAX_PATH - 1, fpipe)); fclose(fpipe); BaseString sh; sh.assign(buf); sh.trim("\n"); sh.append(".exe"); BaseString shcmd; shcmd.assfmt("%s -c '%s %s'", sh.c_str(), m_path.c_str(), m_args.c_str()); PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {sizeof(STARTUPINFO), 0}; si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = (HANDLE)_get_osfhandle(0); si.hStdOutput = (HANDLE)_get_osfhandle(1); si.hStdError = (HANDLE)_get_osfhandle(2); if(!CreateProcessA(sh.c_str(), (LPSTR)shcmd.c_str(), NULL, NULL, TRUE, CREATE_SUSPENDED, // Resumed after assigned to Job NULL, NULL, &si, &pi)) { char* message; DWORD err = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&message, 0, NULL ); logger.error("CreateProcess failed, error: %d, message: '%s'", err, message); LocalFree(message); } HANDLE proc = pi.hProcess; require(proc); // Job control require(m_job = CreateJobObject(0, 0)); require(AssignProcessToJobObject(m_job, proc)); // Resum process after it has been added to Job ResumeThread(pi.hThread); CloseHandle(pi.hThread); // go back up to original cwd if(chdir(cwd)) { logger.critical("Couldn't go back to saved cwd after spawn()"); logger.critical("errno: %d, strerror: %s", errno, strerror(errno)); } free(cwd); // get back to original std i/o for(i = 0; i < 3; i++) { dup2(std_dups[i], i); close(std_dups[i]); } for (i = 0; i < saved.size(); i++) { putenv(saved[i].c_str()); } logger.debug("'%s' has been started", shcmd.c_str()); DWORD exitcode; BOOL result = GetExitCodeProcess(proc, &exitcode); //maybe a short running process if (result && exitcode != 259) { m_status = STOPPED; logger.warning("Process terminated early"); } int pid = GetProcessId(proc); if (!pid) logger.critical("GetProcessId failed, error: %d!", GetLastError()); logger.debug("new pid %d", pid); CloseHandle(proc); m_status = RUNNING; writePid(pid); #endif close(fdnull); }
object *null_environment_proc(object *arguments) { return setup_environment(); }
extern int login_main(int argc, char **argv) { char tty[BUFSIZ]; char full_tty[200]; char fromhost[512]; char username[USERNAME_SIZE]; const char *tmp; int amroot; int flag; int failed; int count=0; struct passwd *pw, pw_copy; #ifdef CONFIG_WHEEL_GROUP struct group *grp; #endif int opt_preserve = 0; int opt_fflag = 0; char *opt_host = 0; int alarmstarted = 0; #ifdef CONFIG_SELINUX int flask_enabled = is_flask_enabled(); security_id_t sid = 0, old_tty_sid, new_tty_sid; #endif username[0]=0; amroot = ( getuid ( ) == 0 ); signal ( SIGALRM, alarm_handler ); alarm ( TIMEOUT ); alarmstarted = 1; while (( flag = getopt(argc, argv, "f:h:p")) != EOF ) { switch ( flag ) { case 'p': opt_preserve = 1; break; case 'f': /* * username must be a separate token * (-f root, *NOT* -froot). --marekm */ if ( optarg != argv[optind-1] ) bb_show_usage( ); if ( !amroot ) /* Auth bypass only if real UID is zero */ bb_error_msg_and_die ( "-f permission denied" ); safe_strncpy(username, optarg, USERNAME_SIZE); opt_fflag = 1; break; case 'h': opt_host = optarg; break; default: bb_show_usage( ); } } if (optind < argc) // user from command line (getty) safe_strncpy(username, argv[optind], USERNAME_SIZE); if ( !isatty ( 0 ) || !isatty ( 1 ) || !isatty ( 2 )) return EXIT_FAILURE; /* Must be a terminal */ #ifdef CONFIG_FEATURE_U_W_TMP checkutmp ( !amroot ); #endif tmp = ttyname ( 0 ); if ( tmp && ( strncmp ( tmp, "/dev/", 5 ) == 0 )) safe_strncpy ( tty, tmp + 5, sizeof( tty )); else if ( tmp && *tmp == '/' ) safe_strncpy ( tty, tmp, sizeof( tty )); else safe_strncpy ( tty, "UNKNOWN", sizeof( tty )); #ifdef CONFIG_FEATURE_U_W_TMP if ( amroot ) memset ( utent.ut_host, 0, sizeof utent.ut_host ); #endif if ( opt_host ) { #ifdef CONFIG_FEATURE_U_W_TMP safe_strncpy ( utent.ut_host, opt_host, sizeof( utent. ut_host )); #endif snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s' from `%.200s'", tty, opt_host ); } else snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s'", tty ); setpgrp(); openlog ( "login", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH ); while ( 1 ) { failed = 0; if ( !username[0] ) if(!login_prompt ( username )) return EXIT_FAILURE; if ( !alarmstarted && ( TIMEOUT > 0 )) { alarm ( TIMEOUT ); alarmstarted = 1; } if (!( pw = getpwnam ( username ))) { pw_copy.pw_name = "UNKNOWN"; pw_copy.pw_passwd = "!"; opt_fflag = 0; failed = 1; } else pw_copy = *pw; pw = &pw_copy; if (( pw-> pw_passwd [0] == '!' ) || ( pw-> pw_passwd[0] == '*' )) failed = 1; if ( opt_fflag ) { opt_fflag = 0; goto auth_ok; } if (!failed && ( pw-> pw_uid == 0 ) && ( !check_tty ( tty ))) failed = 1; /* Don't check the password if password entry is empty (!) */ if ( !pw-> pw_passwd[0] ) goto auth_ok; /* authorization takes place here */ if ( correct_password ( pw )) goto auth_ok; failed = 1; auth_ok: if ( !failed) break; { // delay next try time_t start, now; time ( &start ); now = start; while ( difftime ( now, start ) < FAIL_DELAY) { sleep ( FAIL_DELAY ); time ( &now ); } } puts("Login incorrect"); username[0] = 0; if ( ++count == 3 ) { syslog ( LOG_WARNING, "invalid password for `%s'%s\n", pw->pw_name, fromhost); return EXIT_FAILURE; } } alarm ( 0 ); if ( check_nologin ( pw-> pw_uid == 0 )) return EXIT_FAILURE; #ifdef CONFIG_FEATURE_U_W_TMP setutmp ( username, tty ); #endif #ifdef CONFIG_SELINUX if (flask_enabled) { struct stat st; if (get_default_sid(username, 0, &sid)) { fprintf(stderr, "Unable to get SID for %s\n", username); exit(1); } if (stat_secure(tty, &st, &old_tty_sid)) { fprintf(stderr, "stat_secure(%.100s) failed: %.100s\n", tty, strerror(errno)); return EXIT_FAILURE; } if (security_change_sid (sid, old_tty_sid, SECCLASS_CHR_FILE, &new_tty_sid) != 0) { fprintf(stderr, "security_change_sid(%.100s) failed: %.100s\n", tty, strerror(errno)); return EXIT_FAILURE; } if(chsid(tty, new_tty_sid) != 0) { fprintf(stderr, "chsid(%.100s, %d) failed: %.100s\n", tty, new_tty_sid, strerror(errno)); return EXIT_FAILURE; } } else sid = 0; #endif if ( *tty != '/' ) snprintf ( full_tty, sizeof( full_tty ) - 1, "/dev/%s", tty); else safe_strncpy ( full_tty, tty, sizeof( full_tty ) - 1 ); if ( !is_my_tty ( full_tty )) syslog ( LOG_ERR, "unable to determine TTY name, got %s\n", full_tty ); /* Try these, but don't complain if they fail * (for example when the root fs is read only) */ chown ( full_tty, pw-> pw_uid, pw-> pw_gid ); chmod ( full_tty, 0600 ); change_identity ( pw ); tmp = pw-> pw_shell; if(!tmp || !*tmp) tmp = DEFAULT_SHELL; setup_environment ( tmp, 1, !opt_preserve, pw ); motd ( ); signal ( SIGALRM, SIG_DFL ); /* default alarm signal */ if ( pw-> pw_uid == 0 ) syslog ( LOG_INFO, "root login %s\n", fromhost ); run_shell ( tmp, 1, 0, 0 #ifdef CONFIG_SELINUX , sid #endif ); /* exec the shell finally. */ return EXIT_FAILURE; }
/* Run a command and redirect its input and output handles to a pair of anonymous pipes. The process handle and pipe handles are returned in the info struct. Returns the PID of the new process, or -1 on error. */ static int run_command_redirected(char *cmdexec, struct subprocess_info *info) { /* Each named pipe we create has to have a unique name. */ static int pipe_serial_no = 0; char pipe_name[32]; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; setup_environment(&info->fdn); /* Make the pipe handles inheritable. */ sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; /* The child's input pipe is an ordinary blocking pipe. */ if (CreatePipe(&info->child_in_r, &info->child_in_w, &sa, 0) == 0) { if (o.verbose) logdebug("Error in CreatePipe: %d\n", GetLastError()); return -1; } /* Pipe names must have this special form. */ Snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ncat-%d-%d", GetCurrentProcessId(), pipe_serial_no); if (o.debug > 1) logdebug("Creating named pipe \"%s\"\n", pipe_name); /* The output pipe has to be nonblocking, which requires this complicated setup. */ info->child_out_r = CreateNamedPipe(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 4096, 4096, 1000, &sa); if (info->child_out_r == 0) { if (o.verbose) logdebug("Error in CreateNamedPipe: %d\n", GetLastError()); CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); return -1; } info->child_out_w = CreateFile(pipe_name, GENERIC_WRITE, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if (info->child_out_w == 0) { CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); CloseHandle(info->child_out_r); return -1; } pipe_serial_no++; /* Don't inherit our end of the pipes. */ SetHandleInformation(info->child_in_w, HANDLE_FLAG_INHERIT, 0); SetHandleInformation(info->child_out_r, HANDLE_FLAG_INHERIT, 0); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.hStdInput = info->child_in_r; si.hStdOutput = info->child_out_w; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.dwFlags |= STARTF_USESTDHANDLES; memset(&pi, 0, sizeof(pi)); if (CreateProcess(NULL, cmdexec, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) == 0) { if (o.verbose) logdebug("Error in CreateProcess: %d\n", GetLastError()); CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); CloseHandle(info->child_out_r); CloseHandle(info->child_out_w); return -1; } /* Close hThread here because we have no use for it. hProcess is closed in subprocess_info_close. */ CloseHandle(pi.hThread); info->proc = pi.hProcess; return pi.dwProcessId; }