int main(int ac, char **av) { int lc; const char *msg; void check_functionality(void); int r_val; if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); setup(); /* global setup */ for (lc = 0; TEST_LOOPING(lc); lc++) { tst_count = 0; /* get the name of the test dirctory */ if ((temp_dir = (getcwd(temp_dir, 0))) == NULL) tst_brkm(TBROK, cleanup, "getcwd failed"); /* * create a new directory and open it */ if ((r_val = mkdir(TEST_DIR, MODES)) == -1) tst_brkm(TBROK, cleanup, "mkdir failed"); if ((fd = open(TEST_DIR, O_RDONLY)) == -1) tst_brkm(TBROK, cleanup, "open of directory failed"); TEST(fchdir(fd)); if (TEST_RETURN == -1) { tst_brkm(TFAIL | TTERRNO, cleanup, "fchdir call failed"); } else { check_functionality(); } /* * clean up things in case we are looping */ /* * NOTE: in case of failure here, we need to use "tst_resm()" * and not "tst_brkm()". This is because if we get to this * point, we have already set a PASS or FAIL for the test * and "tst_brkm()" won't report as we might expect. */ /* chdir back to our temporary work directory */ if ((r_val = chdir("..")) == -1) tst_resm(TBROK | TERRNO, "chdir failed"); if ((r_val = rmdir(TEST_DIR)) == -1) tst_resm(TBROK | TERRNO, "rmdir failed"); free(temp_dir); temp_dir = NULL; } cleanup(); tst_exit(); }
int main(void){ int pid; //int ffd; int fd[2]; //int pfd; pipe(fd); pid = fork(); if(pid > 0){ char buff[1024]; struct pollfd fds[3]; getcwd(buff,1024); strcat(buff,"/fifo"); mkfifo(buff,0666); fds[0].fd = 0; fds[0].events = POLLIN; fds[1].fd = open(buff,1024,O_RDWR); fds[1].events = POLLIN; fds[2].fd = fd[1]; fds[2].events = POLLIN; //FILE *f1 = popen("./p1",'r'); while(1){ poll(fds,3,-1); if(fds[0].revents & POLLIN){ close(fd[1]); //open(fds[0].fd,O_RDONLY); read(fds[0].fd,buff,1024); printf("%s\n",buff); } if(fds[1].revents & POLLIN){ read(fds[1].fd,buff,1024); printf("%s\n",buff); } if(fds[2].revents & POLLIN){ read(fds[2].fd,buff,1024); printf("%s\n",buff); } } } if(pid >0){ char buff[1024]; close(fd[0]); //open(fd[1],O_WRONLY); while(1){ read(fd[1],buff,1024); printf("%s\n",buff); } } }
int main (int argc, char **argv) { static char domainname[] = "gt_01"; static char path[MAXPATHLEN]; const char *tzone = "EST"; const char *lang = "pig_latin"; argc = xo_parse_args(argc, argv); if (argc < 0) return 1; for (argc = 1; argv[argc]; argc++) { if (strcmp(argv[argc], "tz") == 0) tzone = argv[++argc]; else if (strcmp(argv[argc], "lang") == 0) lang = argv[++argc]; else if (strcmp(argv[argc], "po") == 0) strlcpy(path, argv[++argc], sizeof(path)); } setenv("LANG", lang, 1); setenv("TZ", tzone, 1); if (path[0] == 0) { getcwd(path, sizeof(path)); strlcat(path, "/po", sizeof(path)); } setlocale(LC_ALL, ""); bindtextdomain(domainname, path); bindtextdomain("ldns", path); bindtextdomain("strerror", path); textdomain(domainname); tzset(); xo_open_container("top"); xo_emit("{G:}Your {qg:adjective} {g:noun} is {g:verb} {qg:owner} {g:target}\n", "flaming", "sword", "burning", "my", "couch"); xo_emit("{G:}The {qg:adjective} {g:noun} was {g:verb} {qg:owner} {g:target}\n", "flaming", "sword", "burning", "my", "couch"); int i; for (i = 0; i < 5; i++) xo_emit("{lw:bytes/%d}{Ngp:byte,bytes}\n", i); xo_emit("{G:}{L:total} {:total/%u}\n", 1234); xo_emit("{G:ldns}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", (size_t) 1234, "foop", 4321, 32); xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", (size_t) 1234, "foop", 4321, 32); xo_emit("{G:/%s}Received {:received/%zu} {Ngp:byte,bytes} " "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", "ldns", (size_t) 1234, "foop", 4321, 32); struct timeval tv; tv.tv_sec = 1435085229; tv.tv_usec = 123456; struct tm tm; (void) gmtime_r(&tv.tv_sec, &tm); char date[64]; strftime(date, sizeof(date), "%+", &tm); xo_emit("{G:}Only {:marzlevanes/%d} {Ngp:marzlevane,marzlevanes} " "are functioning correctly\n", 3); xo_emit("{G:}Version {:version} {:date}\n", "1.2.3", date); errno = EACCES; xo_emit_warn("{G:}Unable to {g:verb/objectulate} forward velociping"); xo_emit_warn("{G:}{g:style/automatic} synchronization of {g:type/cardinal} " "{g:target/grammeters} failed"); xo_emit("{G:}{Lwcg:hydrocoptic marzlevanes}{:marzlevanes/%d}\n", 6); xo_emit("{G:}{Lwcg:Windings}{g:windings}\n", "lotus-o-delta"); xo_close_container("top"); xo_finish(); return 0; }
/* paths_setup ** Modify the lua path and cpath, prepending standard directories ** relative to this executable. */ static void paths_setup(lua_State *L, char *app) { char *temp, *binpath, *path; temp = malloc(PATH_MAX+1); if (!temp) { l_message("Error", "malloc failure for temp"); exit(-1); } binpath = malloc(PATH_MAX+1); if (!binpath) { l_message("Error", "malloc failure for binpath"); exit(-1); } path = malloc(PATH_MAX+1); if (!path) { l_message("Error", "malloc failure for path"); exit(-1); } // full path to jive binary if (app[0] == '/') { // we were called with a full path strcpy(path, app); } else { // add working dir + app and resolve getcwd(temp, PATH_MAX+1); strcat(temp, "/"); strcat(temp, app); realpath(temp, path); } // directory containing jive strcpy(binpath, dirname(path)); // set paths in lua (package.path & package cpath) lua_getglobal(L, "package"); if (lua_istable(L, -1)) { luaL_Buffer b; luaL_buffinit(L, &b); // default lua path lua_getfield(L, -1, "path"); luaL_addvalue(&b); luaL_addstring(&b, ";"); // lua path relative to executable #if !defined(WIN32) strcpy(temp, binpath); strcat(temp, "/../share/lua/5.1"); realpath(temp, path); #endif luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?.lua;"); luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?" DIR_SEPARATOR_STR "?.lua;"); // script path relative to executale strcpy(temp, binpath); strcat(temp, "/" LUA_DEFAULT_PATH); realpath(temp, path); luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?.lua;"); // set lua path luaL_pushresult(&b); lua_setfield(L, -2, "path"); luaL_buffinit(L, &b); // default lua cpath lua_getfield(L, -1, "cpath"); luaL_addvalue(&b); luaL_addstring(&b, ";"); // lua cpath #if !defined(WIN32) strcpy(temp, binpath); strcat(temp, "/../lib/lua/5.1"); realpath(temp, path); #endif luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?." LIBRARY_EXT ";"); luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?" DIR_SEPARATOR_STR "core." LIBRARY_EXT ";"); // cpath relative to executable strcpy(temp, binpath); strcat(temp, "/" LUA_DEFAULT_PATH); realpath(temp, path); luaL_addstring(&b, path); luaL_addstring(&b, DIR_SEPARATOR_STR "?." LIBRARY_EXT ";"); // set lua cpath luaL_pushresult(&b); lua_setfield(L, -2, "cpath"); } else { l_message("Error", "'package' is not a table"); } // pop package table off the stack lua_pop(L, 1); free(temp); free(binpath); free(path); }
int main(int argc, char** argv) { int c, i; int hFlg = 0; int errFlg = 0; extern int optind, opterr; opterr = 1; while((c = getopt(argc, argv, "h")) != -1) { switch(c) { case 'h': { if(hFlg) { errFlg ++; break; } hFlg ++; break; } default: { errFlg ++; } } } if(errFlg) { usage(); exit(-1); } if(hFlg) { usage(); } // Get file names. int fileCnt = argc - optind; if(!fileCnt) { printf("dv: missing file name\n"); exit(-1); } char* files[fileCnt]; for(i = 0; i < fileCnt; i ++) { files[i] = argv[i + optind]; } // Get DUMPSTER environment variable. char* dumpPath = NULL; dumpPath = getenv("DUMPSTER"); if(!dumpPath) { printf("No match for DUMPSTER in environment\n"); exit(-1); } // Get stat for dumpster. struct stat dumpStat; int sRtn = stat(dumpPath, &dumpStat); if(sRtn) { perror("stat() call failed"); exit(sRtn); } // Get information for current directory. char currDir[1024]; char* gRtn = getcwd(currDir, 1024); if(!gRtn) { perror("getcwd() call failed"); exit(-1); } // printf("Current working directory is %s\n", currDir); // Get stat for current working directory. struct stat currDirStat; sRtn = stat(currDir, &currDirStat); if(sRtn) { perror("stat() call failed"); exit(sRtn); } // Move file from dumpster to current directory. // Check for partition. // printf("On same partition\n"); for(i = 0; i < fileCnt; i++) { char* file = files[i]; // Check for file existance. int aRtn = access(file, F_OK); if(aRtn == 0) { printf("File or folder %s already exists in current directory!\n", file); exit(-1); } // Free this! // Get the file in dumpster. char* srcPath; getSrcFilePath(file, dumpPath, &srcPath); // TODO: May have to report error when input is "/..." // Get the file name of the actual file. char* dupFile = strdup(file); char* tarFile; char* token; while((token = strsep(&dupFile, "/"))){ // printf("%s\n", token); tarFile = strdup(token); } // printf("Final token is %s\n", tarFile); // int k = 0; // for(k = 0; k < j; k ++){ // printf("%s\n", tokens[j]); // } // Use access to check whether fiel exists. if(access(srcPath, F_OK) == -1){ printf("File or folder %s does not exits\n", srcPath); continue; } struct stat srcFileStat; int sRtn = stat(srcPath, &srcFileStat); if(sRtn) { perror("stat() call failed"); exit(sRtn); } // Check partition here! // Check file or folder. // If same partition. if(dumpStat.st_dev == currDirStat.st_dev) { // If it ia s file. if(S_ISREG(srcFileStat.st_mode)) { // printf("It is a file!\n"); int rRtn = rename(srcPath, tarFile); if(rRtn) { perror("rename() call failed"); exit(rRtn); } int cRtn = chmod(tarFile, srcFileStat.st_mode); // printf("cRtn is %d\n", cRtn); if(cRtn) { perror("chmod() call failed"); exit(cRtn); } } else if(S_ISDIR(srcFileStat.st_mode)) { // Recursively add new folder back to current directory. removeFolder(srcPath, tarFile, 1); int rRtn = rmdir(srcPath); if(rRtn) { perror("rmdir() call failed"); exit(rRtn); } } } else { if(S_ISREG(srcFileStat.st_mode)) { copyToTar(srcPath, tarFile, srcFileStat); int uRtn = unlink(srcPath); if(uRtn) { perror("unlink() call failed"); exit(uRtn); } } else if(S_ISDIR(srcFileStat.st_mode)) { removeFolder(srcPath, tarFile, 0); int rRtn = rmdir(srcPath); if(rRtn) { perror("rmdir() call failed"); exit(rRtn); } } } } }
char *get_pwd () { //return getcwd (NULL, 0); return getcwd (dir, 255); }
bool WalkDir_TwoPass(char *StartPath,bool RecurseFlag,bool DoDirs, FileFuncType FileFunc,DirStartFuncType DirStartFunc,DirDoneFuncType DirDoneFunc) { struct WalkState *CurState,*GotState; DIR * DFD; bool Ok = 1; char WasInDir[1024]; bool KeepGoing=1; if ( !getcwd(WasInDir,1024) ) return(0); if ( ! HaveExitTrap ) if ( atexit(WalkerExit) == 0 ) HaveExitTrap = 1; ExitResetDir = WasInDir; if ( (CurState = malloc(sizeof(struct WalkState))) == NULL ) return(0); CurState->Next = NULL; CurState->NestLevel = 0; CurState->WalkerFlag = 0; if ( !StartPath ) { strcpy(CurState->Path,WasInDir); } else { chdir(StartPath); if ( !getcwd(CurState->Path,1024) ) { free(CurState); return(0); } } while( CurState ) { GotState = CurState; CurState = CurState->Next; /** pass 1 : do FileFuncs **/ if ( KeepGoing ) { if ( DFD = opendir(GotState->Path) ) { if ( chdir(GotState->Path) == 0 ) { if ( DirStartFunc && KeepGoing ) KeepGoing = (*DirStartFunc)(GotState->Path,GotState->NestLevel); if ( KeepGoing ) KeepGoing = WalkCurDir(DFD,GotState->Path,GotState->NestLevel, 0,DoDirs,FileFunc,&CurState); if ( KeepGoing && DirDoneFunc ) KeepGoing = (*DirDoneFunc)(GotState->Path,GotState->NestLevel); closedir(DFD); DFD = NULL; } else Ok = 0; if ( DFD) closedir(DFD); } else { if ( chdir(GotState->Path) == 0 ) { if ( DirStartFunc && KeepGoing ) KeepGoing = (*DirStartFunc)(GotState->Path,GotState->NestLevel); if ( KeepGoing && DirDoneFunc ) KeepGoing = (*DirDoneFunc)(GotState->Path,GotState->NestLevel); } } } /** pass 2 : build recurse info **/ if ( KeepGoing && RecurseFlag ) { if ( DFD = opendir(GotState->Path) ) { KeepGoing = WalkCurDir(DFD,GotState->Path,GotState->NestLevel, 1,0,NULL,&CurState); closedir(DFD); } } free(GotState); } chdir(WasInDir); ExitResetDir = NULL; return(Ok); }
void get_my_path(char *path) { getcwd(path, PATH_MAX - 1); }
//Start program int main (int argc, char ** argv) { //define buffers for input //user input char line[MAX_LENGTH]; //the command the user wanted char *cmd; //current working directory char cwd[1024]; //the argument needed for two part commands char *arg; //true false to determine if using a file or not char fn = '1'; //the batch file to be read FILE *batch; //a duplicate of the original path needed when executing readme char cwd_dup[1024]; //getting the original path for readme getcwd(cwd_dup, sizeof(cwd_dup)); //define pointers //Set environment variable "shell" if (setenv("SHELL",cwd_dup,1)){ printf("Failed to set environment!\n"); } //If the argument ocunter is 2 when the program starts //open the file if (argc == 2) { //determines if the file can be opened //if it can, run the program from the file //file path is argv[1] batch = fopen(argv[1], "r"); if (batch == NULL){ printf("Error opening file!\n"); }else{ fn = '0'; } } //print working directory //read command input from console in a loop //Keep reading input line until "quit" command, or eof of redirect input like "Ctrl+C", or eof of the file while(1){ //get the current directory getcwd(cwd, sizeof(cwd)); //if it is from console, fn is 1 //otherwise 0 is fro file //if it is form console, display the current directory and gets the line from the user if(fn == '1'){ printf("%s: ", cwd); fgets(line, MAX_LENGTH, stdin); }else if(fn == '0'){ if(feof(batch) == 0) { fgets(line, MAX_LENGTH, batch); }else{ fn = '1'; fclose(batch); continue; //exit(0); } } //Tokenize the input args array cmd = strtok(line, DELIMS); //Check for supported internal commands if (!cmd){ //Do nothing with no command }else if (strcmp(cmd, "cd") == 0) { //store the command name and any arguments //pass command to OS through calling "system()", or call related functions //change environment variables if need it //display result if need it arg = strtok(0, DELIMS); //cd must have an argument to attempt path change if (!arg) { fprintf(stderr, "cd missing argument.\n"); } else { //If the path change fails, tell the user if(chdir(arg) == -1){ printf("Directory change failed!\n"); } } //clears the screen }else if(strcmp(cmd, "clr") == 0) { clr(); //look at the specified directory by the user }else if(strcmp(cmd, "dir") == 0) { pid_t pid; pid = fork(); if(pid == -1) printf("Error Creating child\n"); else if ( pid == 0) { //if no argument after dir is put, it shows the current Directory DIR *dp; struct dirent *ep; arg = strtok(0, DELIMS); if(arg == NULL){ dp = opendir (cwd); }else{ dp = opendir (arg); } //if it cannot open the directory to show, tell the user if (dp != NULL) { //otherwise it reads each object in the directory while (ep = readdir (dp)) { puts (ep->d_name); } //closes the directory read when it is done (void) closedir (dp); }else{ perror ("Couldn't open the directory\n"); } exit(0); }else if ( pid != 0) { wait(NULL); } //displays the enviroment and all its variables }else if(strcmp(cmd, "environ") == 0) { pid_t pid; pid = fork(); if(pid == -1) printf("Error Creating child\n"); else if ( pid == 0) { //creates an external pointer to the enviroment extern char **environ; //finds the amount in environment and display it char **current; for(current = environ; *current; current++) { //new line for each element in environment printf("%s\n",*current); } exit(0); }else if ( pid != 0) { wait(NULL); } //redisplay what the user wrote after echo }else if(strcmp(cmd, "echo") == 0) { pid_t pid; pid = fork(); if(pid == -1) printf("Error Creating child\n"); else if ( pid == 0) { //take out the command and display the rest as original text arg = strtok(0,""); printf("%s", arg); exit(0); }else if ( pid != 0) { wait(NULL); } //show help }else if(strcmp(cmd, "help") == 0) { help(cwd_dup); //pauses the program }else if(strcmp(cmd, "pause") == 0) { pause(); //quits the program //tells the user the program has terminated and then quits }else if(strcmp(cmd, "quit") == 0) { printf("Terminated\n"); exit(0); //otherwise it tries to run an external }else{ externPro(cmd, cwd); } } }
int main(int argc, char* argv[]) { CefMainArgs main_args(argc, argv); g_appStartupTime = time(NULL); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get()); if (exit_code >= 0) return exit_code; //Retrieve the current working directory if (!getcwd(szWorkingDir, sizeof (szWorkingDir))) return -1; GtkWidget* window; gtk_init(&argc, &argv); // Parse command line arguments. AppInitCommandLine(argc, argv); CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); // Check cache_path setting if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/dev/src/index.html"); if (!FileExists(szInitialUrl)) { szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/www/index.html"); if (!FileExists(szInitialUrl)) { if (GetInitialUrl() < 0) return 0; } } // Initialize CEF. CefInitialize(main_args, settings, app.get()); // Set window icon std::vector<std::string> icons(APPICONS, APPICONS + sizeof(APPICONS) / sizeof(APPICONS[0]) ); GList *list = NULL; for (int i = 0; i < icons.size(); ++i) { std::string path = icons[i]; GdkPixbuf *icon = gdk_pixbuf_new_from_file(path.c_str(), NULL); if (!icon) continue; list = g_list_append(list, icon); } window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_window_set_icon_list(GTK_WINDOW(window), list); // Free icon list g_list_foreach(list, (GFunc) g_object_unref, NULL); g_list_free(list); GtkWidget* vbox = gtk_vbox_new(FALSE, 0); GtkWidget* menuBar = gtk_menu_bar_new(); // GtkWidget* debug_menu = CreateMenu(menuBar, "Tests"); // AddMenuEntry(debug_menu, "Hello World Menu", // G_CALLBACK(GetSourceActivated)); gtk_box_pack_start(GTK_BOX(vbox), menuBar, FALSE, FALSE, 0); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(HandleQuit), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_widget_destroyed), &window); add_handler_id = g_signal_connect(G_OBJECT(window), "add", G_CALLBACK(HandleAdd), NULL); // g_signal_connect(G_OBJECT(window), "destroy", // G_CALLBACK(destroy), NULL); // Create the handler. g_handler = new ClientHandler(); g_handler->SetMainHwnd(vbox); // Create the browser view. CefWindowInfo window_info; CefBrowserSettings browserSettings; browserSettings.web_security = STATE_DISABLED; window_info.SetAsChild(vbox); CefBrowserHost::CreateBrowser( window_info, static_cast<CefRefPtr<CefClient> >(g_handler), "file://"+szInitialUrl, browserSettings); gtk_container_add(GTK_CONTAINER(window), vbox); gtk_widget_show_all(GTK_WIDGET(window)); // Install an signal handler so we clean up after ourselves. signal(SIGINT, TerminationSignalHandler); signal(SIGTERM, TerminationSignalHandler); // Start the node server process startNodeProcess(); CefRunMessageLoop(); CefShutdown(); return 0; }
int main( int argc , char *argv[] , char *envp[]) { int i; int maxfd; int listenfd; int connfd; // File Descriptors int sockfd; int nready; char *token; //int client[MAX_CLIENTS]; // max size of a fd set for select int nclients; fd_set rset; fd_set allset; char buf[MAXLINE]; //char resp[PATH_MAX]; ssize_t nbytes; socklen_t clilen; struct sockaddr_in cliaddr; struct sockaddr_in servaddr; //struct timeval timeout; // Before Anything get the "Virtual" Server Home Directory getcwd(serverHome,PATH_MAX); perror("Server Home getcwd: "); fprintf(stderr,"Virtual Server Home is set to\n\t%s\n",serverHome); //Set all mclients as available for(i=0; i<= MAX_CLIENTS; i++){ mclients[i].avail = 0; // 0 means available -1 means not available getcwd(mclients[i].pwd,PATH_MAX); // Set Inital home path } listenfd = socket(AF_INET, SOCK_STREAM, 0); // Make sure everything is nice and clean. memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(atol(argv[1])); if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) != 0) { perror("cannot bind address"); exit(EXIT_FAILURE); } if (listen(listenfd, LISTENQ) != 0) { perror("cannot listen on port address"); exit(EXIT_FAILURE); } printf("server listening on %s\n", argv[1]); // For now, this is out highest numbered file desc that // we will check. maxfd = listenfd; // initialize nclients = 0; // Go through the entire array and initialize the entries // to a "not used" state. We know that all file descriptors // are a non-negative value, so using -1 indicates it is // unused. for (i = 0 ; i < MAX_CLIENTS ; i++) { mclients[i].clientfd = NOT_IN_USE; // A value of -1 indicates available entry } // Clean out the set of all file descriptors. FD_ZERO(&allset); // Add the listen file desc into the list of all descriptors. FD_SET(listenfd, &allset); //timeout.tv_sec = 5; // 5 seconds for ( ; ; ) { rset = allset; printf("sever: calling select with %d clients\n>> ", nclients); fflush(stdout); // In this case, we are only looking at the readfds. // We are looking at either the writefds or the exceptfds. // We are not specifying a time out value. // // Select will return the total number of fds that have // become ready for i/o. // // A file descriptor is considered ready if it is possible // to perform the corresponding I/O operation without blocking. // nready = select(maxfd + 1, &rset, NULL, NULL, NULL); //timeout.tv_sec = 5; // 5 seconds //nready = select(maxfd + 1, &rset, NULL, NULL, &timeout); printf("\n"); // if (nready == 0) { // printf(" server: timeout occured\n"); // continue; // } printf(" server: select found %d ready fds\n", nready); if (nready == -1) { perror("select returned failure"); exit(EXIT_FAILURE); } // Check the listenfd first. If it is ready, then it is // a new client connection request. if (FD_ISSET(listenfd, &rset)) { // A new client connection... Woooo Whoooo!!! nclients ++; printf(" server: a new client connection request\n"); clilen = sizeof(cliaddr); // Get the new connection file desc. connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen); // Find a place to save the new file descriptor in // our set of file descriptors. for (i = 0 ; i < MAX_CLIENTS ; i++) { if (mclients[i].clientfd < 0) { mclients[i].avail = -1; // Make not availble mclients[i].clientfd = connfd; // save descriptor break; // not need to keep looking } } if (i == MAX_CLIENTS) { printf("!!! TOO MANY CLIENTS !!!!\n"); // This might not be the best way to handle this condition, // but it is a good demonstration. //close(connfd); exit(EXIT_FAILURE); } FD_SET(connfd, &allset); // add new descriptor to the all set // Make sure that we keep track of the highest numbered // file descriptor. We need it for the select() call. if (connfd > maxfd) { maxfd = connfd; } // Decrement the number of processed file desc left // to handle. if (--nready <= 0) { continue; // no more readable descriptors } } // Check file desc to see if there is ready data. for (i = 0 ; i <= MAX_CLIENTS ; i++) { sockfd = mclients[i].clientfd; if (sockfd < 0) { // not a spot in use, keep looking continue; } // This checks to see if this file desc is one of the // ready ones. if (FD_ISSET(sockfd, &rset)) { printf(" server: received communication from client\n"); // Make sure this is nice and clean. memset(buf, 0, sizeof(buf)); // Received data on this file desc, read and echo it. if ((nbytes = read(sockfd, buf, sizeof(buf))) == 0) { // The connection was closed by the client, because // we received a zero bytes on the the read. // Close the socket fd, remove it from the list to check, // and set its spot to available. close(sockfd); FD_CLR(sockfd, &allset); mclients[i].clientfd = NOT_IN_USE; mclients[i].avail = 0; printf(" server: client closed connection\n"); nclients --; }else if(strncmp(CMD_REMOTE_PWD,buf,(ssize_t)3) == 0){ fprintf(stderr,"***nbytes: %ld***\n",nbytes); fprintf(stderr,"PWD request by client (%d)\n",i); fprintf(stderr,"Response: %s\n",mclients[i].pwd); write(sockfd, mclients[i].pwd, MAXLINE); perror("pwd write: "); //memset(buf,0,sizeof(buf)); }else if(strncmp(CMD_REMOTE_DIR,buf,(ssize_t)3) == 0){ fprintf(stderr,"DIR request by client (%d)\n",i); // You must cd into client dir first chdir(mclients[i].pwd); perror("chdir dir command (client pwd):"); fprintf(stderr, "Virtual Server temporarily in:\n\t ***%s***\n", mclients[i].pwd); // Run Dir Function dirFunction(mclients, sockfd); // cd back into Home Server Dir chdir(serverHome); perror("chdir dir command (serverHome): "); fprintf(stderr, "Virtual Server back in:\n\t ***%s***\n", serverHome); // Memset memset(buf,0,sizeof(buf)); }else if (strncmp(CMD_REMOTE_CHDIR,buf,(ssize_t)2) == 0){ token = strtok(buf," "); token = strtok(NULL," "); fprintf(stderr,"Client(%d) request change directory to:\n\t %s\n", i, token); // Change Dir Function changeDirFunction(mclients, i, sockfd, token); // Send Response write(sockfd, mclients[i].pwd, MAXLINE); perror("Write ch dir: "); fprintf(stderr, "Sending new Client PWD ***%s***\n", mclients[i].pwd); fprintf(stderr,"Client(%d) changed Server Directory (%s)\n",i, token); memset(buf,0,sizeof(buf)); }else if (strncmp(CMD_REMOTE_HOME,buf,(ssize_t)4) == 0){ char * homeBuff; token = strtok(buf," "); token = strtok(NULL," "); fprintf(stderr,"Client(%d) request change directory to:\n\t %s\n", i, token); //Get the Home Dir for User homeBuff = getenv("HOME"); // Change Dir Function changeDirFunction(mclients, i, sockfd, homeBuff); // Send Response write(sockfd, mclients[i].pwd, MAXLINE); perror("Write ch dir: "); fprintf(stderr, "Sending new Client PWD ***%s***\n", mclients[i].pwd); fprintf(stderr,"Client(%d) changed Server Directory (%s)\n",i, token); memset(buf,0,sizeof(buf)); }else if(strstr(buf,CMD_GET_FROM_SERVER) != NULL){ int k, z; printf("Received from client <%d>: \"%s\"\n", i , buf); /* * Parse for filename */ token = strtok(buf," "); token = strtok(NULL," "); printf("This is the token representing gets filename (Start): <%s>\n",token); memset((buf),0,strlen((buf))); printf("This is the token representing gets filename (after first memset): <%s>\n",token); if((k = getFunction(token, sockfd, mclients, i)) == 0){ char tempBuff[MAXLINE]; memset(tempBuff, 0, MAXLINE); strncpy(tempBuff, STR(EOT_CHAR), MAXLINE); //For Synching sleep(1); // SEND EOF z = write(sockfd, tempBuff, MAXLINE); fprintf(stderr, "Final write size %d\n",z); fprintf(stderr, "*** Final resp ***\n\t<%s>\n",tempBuff); printf("getFunction returned (%d) :\n",k); }else{ char tempBuff[MAXLINE]; memset(tempBuff, 0, MAXLINE); strncpy(tempBuff, STR(EOT_CHAR), MAXLINE); printf("getFunction returned (%d) :\n",k); //For Synching sleep(1); // SEND EOF z = write(sockfd, tempBuff, MAXLINE); fprintf(stderr, "Final write size %d\n",z); fprintf(stderr, "*** Final resp ***\n\t<%s>\n",tempBuff); } }else { fprintf(stderr,"***nbytes: %ld***\n",nbytes); fprintf(stderr,"UNKNOWN ***REQUEST*** from client (%d)\n",i); printf(" server: echo data back to client <%s>\n", buf); // Echo back to the client the received data. Of course // we SHOULD check the return value from the write(). write(sockfd, buf, MAXLINE); perror("Unknown request write: "); memset(buf,0,sizeof(buf)); } if (--nready <= 0) { // All the changed file desc have been checked. // can exit the for loop. break; } } } } }
/* * create the internal menu for the files */ static void wdg_file_menu_create(struct wdg_object *wo) { WDG_WO_EXT(struct wdg_file_handle, ww); int mrows, mcols; int i; size_t c = wdg_get_ncols(wo); size_t x = wdg_get_begin_x(wo); size_t y = wdg_get_begin_y(wo); struct stat buf; /* the menu is already posted */ if (ww->nitems) return; WDG_DEBUG_MSG("wdg_file_menu_create"); /* get the working directory */ getcwd(ww->curpath, PATH_MAX); /* scan the directory */ ww->nlist = scandir(".", &ww->namelist, 0, alphasort); /* on error display the message in the box */ if (ww->nlist <= 0) { ww->nitems = 2; WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *)); ww->items[ww->nitems - 2] = new_item("/", "root"); ww->items[ww->nitems - 1] = new_item("Cannot open the directory", ""); item_opts_off(ww->items[ww->nitems - 1], O_SELECTABLE); } else { /* for each directory in the directory */ for (i = 0; i < ww->nlist; i++) { /* * transform the current dir into the root. * useful to exit from a path whose parent is not readable */ if (!strcmp(ww->namelist[i]->d_name, ".")) { strncpy(ww->namelist[i]->d_name, "/", 1); ww->nitems++; WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *)); ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, "root"); continue; } /* get the file properties */ stat(ww->namelist[i]->d_name, &buf); if (S_ISDIR(buf.st_mode)) { ww->nitems++; WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *)); ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, "[...]"); } // if not readable //item_opts_off(ww->items[ww->nitems - 1], O_SELECTABLE); } /* and now add the files */ for (i = 0; i < ww->nlist; i++) { /* get the file properties */ stat(ww->namelist[i]->d_name, &buf); if (!S_ISDIR(buf.st_mode)) { ww->nitems++; WDG_SAFE_REALLOC(ww->items, ww->nitems * sizeof(ITEM *)); ww->items[ww->nitems - 1] = new_item(ww->namelist[i]->d_name, ""); } } } /* null terminate the array */ WDG_SAFE_REALLOC(ww->items, (ww->nitems + 1) * sizeof(ITEM *)); ww->items[ww->nitems] = NULL; /* create the menu */ ww->m = new_menu(ww->items); /* set the dimensions */ set_menu_format(ww->m, ww->y - 2, 1); set_menu_spacing(ww->m, 2, 0, 0); /* get the geometry to make a window */ scale_menu(ww->m, &mrows, &mcols); /* * if the menu is larger than the main window * adapt to the new dimensions */ if (mcols > (int)c - 4) { ww->x = mcols + 4; wdg_file_redraw(wo); return; } /* create the window for the menu */ ww->mwin = newwin(mrows, MAX(mcols, (int)c - 4), y + 1, x + 2); /* set the color */ wbkgd(ww->mwin, COLOR_PAIR(wo->window_color)); keypad(ww->mwin, TRUE); /* associate with the menu */ set_menu_win(ww->m, ww->mwin); /* the subwin for the menu */ set_menu_sub(ww->m, derwin(ww->mwin, mrows + 1, mcols, 1, 1)); /* menu attributes */ set_menu_mark(ww->m, ""); set_menu_grey(ww->m, COLOR_PAIR(wo->window_color)); set_menu_back(ww->m, COLOR_PAIR(wo->window_color)); set_menu_fore(ww->m, COLOR_PAIR(wo->window_color) | A_REVERSE | A_BOLD); /* display the menu */ post_menu(ww->m); wnoutrefresh(ww->mwin); }
/* * get_sock_dir * * Identify the socket directory to use for this cluster. If we're doing * a live check (old cluster only), we need to find out where the postmaster * is listening. Otherwise, we're going to put the socket into the current * directory. */ void get_sock_dir(ClusterInfo *cluster, bool live_check) { #ifdef HAVE_UNIX_SOCKETS /* * sockdir and port were added to postmaster.pid in PG 9.1. Pre-9.1 cannot * process pg_ctl -w for sockets in non-default locations. */ if (GET_MAJOR_VERSION(cluster->major_version) >= 901) { if (!live_check) { /* Use the current directory for the socket */ cluster->sockdir = pg_malloc(MAXPGPATH); if (!getcwd(cluster->sockdir, MAXPGPATH)) pg_fatal("cannot find current directory\n"); } else { /* * If we are doing a live check, we will use the old cluster's * Unix domain socket directory so we can connect to the live * server. */ unsigned short orig_port = cluster->port; char filename[MAXPGPATH], line[MAXPGPATH]; FILE *fp; int lineno; snprintf(filename, sizeof(filename), "%s/postmaster.pid", cluster->pgdata); if ((fp = fopen(filename, "r")) == NULL) pg_fatal("Cannot open file %s: %m\n", filename); for (lineno = 1; lineno <= Max(LOCK_FILE_LINE_PORT, LOCK_FILE_LINE_SOCKET_DIR); lineno++) { if (fgets(line, sizeof(line), fp) == NULL) pg_fatal("Cannot read line %d from %s: %m\n", lineno, filename); /* potentially overwrite user-supplied value */ if (lineno == LOCK_FILE_LINE_PORT) sscanf(line, "%hu", &old_cluster.port); if (lineno == LOCK_FILE_LINE_SOCKET_DIR) { cluster->sockdir = pg_strdup(line); /* strip off newline */ if (strchr(cluster->sockdir, '\n') != NULL) *strchr(cluster->sockdir, '\n') = '\0'; } } fclose(fp); /* warn of port number correction */ if (orig_port != DEF_PGUPORT && old_cluster.port != orig_port) pg_log(PG_WARNING, "User-supplied old port number %hu corrected to %hu\n", orig_port, cluster->port); } } else /* * Can't get sockdir and pg_ctl -w can't use a non-default, use * default */ cluster->sockdir = NULL; #else /* !HAVE_UNIX_SOCKETS */ cluster->sockdir = NULL; #endif }
/* Make a canonical pathname from PATH. Returns a freshly malloced string. It is up the *caller* to ensure that the PATH is sensible. i.e. canonicalize ("/dev/fd0/.") returns "/dev/fd0" even though ``/dev/fd0/.'' is not a legal pathname for ``/dev/fd0.'' */ char * canonicalize (const char *path) { char *canonical = xmalloc (PATH_MAX + 1); char *p = canonical; if (path == NULL) return NULL; if (strcmp(path, "none") == 0) { strcpy(canonical, path); return canonical; } if (strchr(path, ':') != NULL) { strcpy(canonical, path); return canonical; } if (*path == '/') { /* We've already got an absolute path in PATH, but we need at least one char in canonical[] on entry to the loop below. */ *p = *path++; } else { getcwd (canonical, PATH_MAX); p = canonical + strlen (canonical) - 1; if (*p != '/') *++p = '/'; } /* There is at least one character in canonical[], and the last char in canonical[], *p, is '/'. */ while ((*path != '\0') && (p < canonical + PATH_MAX)) if (*p != '/') { *++p = *path++; } else { if (path[0] == '/') { path++; /* eliminate duplicate slashes (``//'') */ } else if ((path[0] == '.') && ((path[1] == '\0') || (path[1] == '/'))) { path++; /* eliminate ``/.'' */ } else if ((path[0] == '.') && (path[1] == '.') && ((path[2] == '\0') || (path[2] == '/'))) { while ((p > canonical) && (*--p != '/')) /* ascend on ``/../'' */ ; path += 2; } else { *++p = *path++; /* not a special case, just copy char */ } } if (p >= (canonical + PATH_MAX)) die (2, "mount: path too long"); if (*p == '/') --p; /* eliminate trailing slash */ *++p = '\0'; return canonical; }
static void crash_handler(const char *logfile) { const char *sigdesc = ""; int i; if(fread(&crash_info, sizeof(crash_info), 1, stdin) != 1) { fprintf(stderr, "!!! Failed to retrieve info from crashed process\n"); exit(1); } /* Get the signal description */ for(i = 0;signals[i].name;++i) { if(signals[i].signum == crash_info.signum) { sigdesc = signals[i].name; break; } } if(crash_info.has_siginfo) { switch(crash_info.signum) { case SIGSEGV: for(i = 0;sigsegv_codes[i].name;++i) { if(sigsegv_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigsegv_codes[i].name; break; } } break; case SIGFPE: for(i = 0;sigfpe_codes[i].name;++i) { if(sigfpe_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigfpe_codes[i].name; break; } } break; case SIGILL: for(i = 0;sigill_codes[i].name;++i) { if(sigill_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigill_codes[i].name; break; } } break; case SIGBUS: for(i = 0;sigbus_codes[i].name;++i) { if(sigbus_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigbus_codes[i].name; break; } } break; } } fprintf(stderr, "%s (signal %i)\n", sigdesc, crash_info.signum); if(crash_info.has_siginfo) fprintf(stderr, "Address: %p\n", crash_info.siginfo.si_addr); fputc('\n', stderr); if(logfile) { /* Create crash log file and redirect shell output to it */ if(freopen(logfile, "wa", stdout) != stdout) { fprintf(stderr, "!!! Could not create %s following signal\n", logfile); exit(1); } fprintf(stderr, "Generating %s and killing process %d, please wait... ", logfile, crash_info.pid); printf("*** Fatal Error ***\n" "%s (signal %i)\n", sigdesc, crash_info.signum); if(crash_info.has_siginfo) printf("Address: %p\n", crash_info.siginfo.si_addr); fputc('\n', stdout); fflush(stdout); } sys_info(); crash_info.buf[sizeof(crash_info.buf)-1] = '\0'; printf("%s\n", crash_info.buf); fflush(stdout); if(crash_info.pid > 0) { gdb_info(crash_info.pid); kill(crash_info.pid, SIGKILL); } if(logfile) { char cwd[MAXPATHLEN]; getcwd(cwd, MAXPATHLEN); std::string message = "OpenMW has encountered a fatal error.\nCrash log saved to '" + std::string(cwd) + "/" + std::string(logfile) + "'.\n Please report this to https://bugs.openmw.org !"; SDL_ShowSimpleMessageBox(0, "Fatal Error", message.c_str(), NULL); } exit(0); }
static char *myrealpath(const char *path, char *resolved_path, int maxreslth) { int readlinks = 0; char *npath; char link_path[PATH_MAX+1]; int n; char *buf = NULL; npath = resolved_path; /* If it's a relative pathname use getcwd for starters. */ if (*path != '/') { if (!getcwd(npath, maxreslth-2)) return NULL; npath += strlen(npath); if (npath[-1] != '/') *npath++ = '/'; } else { *npath++ = '/'; path++; } /* Expand each slash-separated pathname component. */ while (*path != '\0') { /* Ignore stray "/" */ if (*path == '/') { path++; continue; } if (*path == '.' && (path[1] == '\0' || path[1] == '/')) { /* Ignore "." */ path++; continue; } if (*path == '.' && path[1] == '.' && (path[2] == '\0' || path[2] == '/')) { /* Backup for ".." */ path += 2; while (npath > resolved_path+1 && (--npath)[-1] != '/') ; continue; } /* Safely copy the next pathname component. */ while (*path != '\0' && *path != '/') { if (npath-resolved_path > maxreslth-2) { errno = ENAMETOOLONG; goto err; } *npath++ = *path++; } /* Protect against infinite loops. */ if (readlinks++ > MAXSYMLINKS) { errno = ELOOP; goto err; } /* See if last pathname component is a symlink. */ *npath = '\0'; n = readlink(resolved_path, link_path, PATH_MAX); if (n < 0) { /* EINVAL means the file exists but isn't a symlink. */ if (errno != EINVAL) goto err; } else { int m; char *newbuf; /* Note: readlink doesn't add the null byte. */ link_path[n] = '\0'; if (*link_path == '/') /* Start over for an absolute symlink. */ npath = resolved_path; else /* Otherwise back up over this component. */ while (*(--npath) != '/') ; /* Insert symlink contents into path. */ m = strlen(path); newbuf = malloc(m + n + 1); if (!newbuf) goto err; memcpy(newbuf, link_path, n); memcpy(newbuf + n, path, m + 1); free(buf); path = buf = newbuf; } *npath++ = '/'; } /* Delete trailing slash but don't whomp a lone slash. */ if (npath != resolved_path+1 && npath[-1] == '/') npath--; /* Make sure it's null terminated. */ *npath = '\0'; free(buf); return resolved_path; err: free(buf); return NULL; }
int main(int argc, char *argv[]) { const char *filename; int ret = 0; char diagnosis[DRMAA_ERROR_STRING_BUFFER]; char jobwd[1024*4]; char jobid[1024]; char line[2*1024]; int drmaa_errno; drmaa_job_template_t *jt = NULL; int stat; int aborted, exited, exit_status, signaled; int j, njobs = 0; FILE *fp; struct sigaction sa; /* clear job info structure */ clear_all_job_info(); /* setup a signal handler for shutdown */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = my_compile_signal_handler; /* one handler for all signals */ sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGPIPE, &sa, NULL); /* we can override use of a compile.conf in cwd by environment */ filename = getenv("RAIMK_COMPILE_CONF"); if (filename == NULL) { filename = "compile.conf"; } /* we'll start the job in the cwd */ if (!getcwd(jobwd, sizeof(jobwd)-1)) { fprintf(stderr, "getcwd() failed: %s\n", strerror(errno)); ret = 2; goto Finish; } /* try to open config file */ if (!(fp = fopen(filename, "r"))) { fprintf(stderr, "fopen(\"compile.conf\") failed: %s\n", strerror(errno)); ret = 2; goto Finish; } /* initialize a drmaa session */ if (drmaa_init(NULL, diagnosis, sizeof(diagnosis)-1) != DRMAA_ERRNO_SUCCESS) { fprintf(stderr, "drmaa_init() failed: %s\n", diagnosis); fclose(fp); return 2; } printf("--- start cluster session --------------------------------\n"); /* parse the config file and start a job for every architecture */ while (fscanf(fp, "%[^\n]\n", line) == 1) { char nat_spec[1024]; char arch[1024]; char name[1024]; char ns[1024]; char output_file[1024]; char dummy[1024]; /* skip comment lines */ if (line[0] == '#') continue; if (sscanf(line, "%[^\t ]%[\t ]%[^\n]\n", arch, dummy, ns) != 3) { fprintf(stderr, "parsing error in compile.conf\n"); continue; } sprintf(name, "build %s", arch); /* build job template */ if (drmaa_allocate_job_template(&jt, NULL, 0)!=DRMAA_ERRNO_SUCCESS) { fprintf(stderr, "drmaa_run_job() failed: %s\n", diagnosis); ret = 2; goto Finish; } drmaa_set_attribute(jt, DRMAA_WD, jobwd, NULL, 0); drmaa_set_attribute(jt, DRMAA_REMOTE_COMMAND, argv[1], NULL, 0); drmaa_set_attribute(jt, DRMAA_JOIN_FILES, "y", NULL, 0); drmaa_set_attribute(jt, DRMAA_JOB_NAME, name, NULL, 0); sprintf(nat_spec, "-b no -S /bin/sh %s", ns); drmaa_set_attribute(jt, DRMAA_NATIVE_SPECIFICATION, nat_spec, NULL, 0); sprintf(output_file, ":%s/build_%s.log", jobwd, arch); drmaa_set_attribute(jt, DRMAA_OUTPUT_PATH, output_file, NULL, 0); drmaa_set_vector_attribute(jt, DRMAA_V_ARGV, (const char **)&argv[2], NULL, 0); /* submit job */ if ((drmaa_errno=drmaa_run_job(jobid, sizeof(jobid)-1, jt, diagnosis, sizeof(diagnosis)-1)) != DRMAA_ERRNO_SUCCESS) { drmaa_delete_job_template(jt, NULL, 0); if (drmaa_errno == DRMAA_ERRNO_DENIED_BY_DRM) { printf("--- job \"%s\" using \"%s\" wasn't accepted: %s\n", name, ns, diagnosis); continue; } fprintf(stderr, "drmaa_run_job() failed: %s\n", diagnosis); ret = 2; goto Finish; } /* remember job information */ job[njobs].jid = strdup(jobid); job[njobs].name = strdup(name); job[njobs].ns = strdup(ns); job[njobs].output_file = strdup(output_file); njobs++; drmaa_delete_job_template(jt, NULL, 0); printf(" submitted job \"%s\" as job %s\n", name, jobid); } fclose(fp); /* monitor jobs, until all have finished */ while (number_of_jobs() > 0) { /* We wait with timeout to be able to react on events like CTRL-C */ drmaa_errno = drmaa_wait(DRMAA_JOB_IDS_SESSION_ANY, jobid, sizeof(jobid)-1, &stat, 1, NULL, diagnosis, sizeof(diagnosis)-1); /* error */ if (drmaa_errno != DRMAA_ERRNO_SUCCESS && drmaa_errno != DRMAA_ERRNO_EXIT_TIMEOUT) { fprintf(stderr, "drmaa_wait() failed: %s\n", diagnosis); ret = 2; goto Finish; } /* user pressed CTRL-C: delete all jobs */ if (terminate_session) { printf("--- shutdown requested --------------------------------\n"); delete_all_jobs(); } /* if user pressed CTRL-C multiple times, exit */ if (terminate_program) { printf("--- forced shutdown -----------------------------------\n"); goto Finish; } /* * a job terminated - evaluate return codes and deregister job from * our internal bookkeeping */ if (drmaa_errno == DRMAA_ERRNO_SUCCESS) { j = search_job(jobid); if (j < 0) { fprintf(stderr, "drmaa_wait() returns unknown job ... ?\n"); } /* report how job finished */ drmaa_wifaborted(&aborted, stat, NULL, 0); if (aborted) { printf("--- run \"%s\" stopped or never started\n", job[j].name); } else { int failed = 1; char *path = job[j].output_file + 1; drmaa_wifexited(&exited, stat, NULL, 0); if (exited) { drmaa_wexitstatus(&exit_status, stat, NULL, 0); if (exit_status == 0) { printf("+++ run \"%s\" was successful\n", job[j].name); failed = 0; } else { printf("### run \"%s\" broken ##################################\n", job[j].name); ret = 1; } } else { drmaa_wifsignaled(&signaled, stat, NULL, 0); if (signaled) { char termsig[DRMAA_SIGNAL_BUFFER+1]; drmaa_wtermsig(termsig, DRMAA_SIGNAL_BUFFER, stat, NULL, 0); printf("job \"%s\" finished due to signal %s\n", job[j].name, termsig); } else { printf("job \"%s\" finished with unclear conditions\n", job[j].name); } } /* * If a job succeeded, we delete its output file. * If it failed, we show the end of the output file. */ if (failed) { char tail_cmd[1024]; sprintf(tail_cmd, "tail -15 %s", path); ret = system(tail_cmd); } else { if (unlink(path) != 0) { fprintf(stderr, "couldn't unlink \"%s\" job output file %s: %s\n", job[j].name, path, strerror(errno)); } } } /* clean the job struct */ clear_job_info(j); } } printf("--- end cluster session --------------------------------\n"); Finish: if (drmaa_exit(diagnosis, sizeof(diagnosis)-1) != DRMAA_ERRNO_SUCCESS) { fprintf(stderr, "drmaa_exit() failed: %s\n", diagnosis); return 1; } return ret; }
int main(int argc, char **argv) { char *me = argv[0], *data, **new_argv; char *exe_path, *lib_path, *dll_path; int start, prog_end, end, count, fd, v, en, x11; int argpos, inpos, collcount = 1; if (config[7] == '[') { write_str(2, argv[0]); write_str(2, ": this is an unconfigured starter\n"); return 1; } if (me[0] == '/') { /* Absolute path */ } else if (has_slash(me)) { /* Relative path with a directory: */ char *buf; long buflen = 4096; buf = (char *)malloc(buflen); me = path_append(getcwd(buf, buflen), me); } else { /* We have to find the executable by searching PATH: */ char *path = copy_string(getenv("PATH")), *p, *m; int more; if (!path) { path = ""; } while (1) { /* Try each element of path: */ for (p = path; *p && (*p != ':'); p++) { } if (*p) { *p = 0; more = 1; } else more = 0; if (!*path) break; m = path_append(path, me); if (executable_exists(m)) { if (m[0] != '/') m = path_append(getcwd(NULL, 0), m); me = m; break; } free(m); if (more) path = p + 1; else break; } } /* me is now an absolute path to the binary */ /* resolve soft links */ while (1) { int len, bufsize = 127; char *buf; buf = (char *)malloc(bufsize + 1); len = readlink(me, buf, bufsize); if (len < 0) { if (errno == ENAMETOOLONG) { /* Increase buffer size and try again: */ bufsize *= 2; buf = (char *)malloc(bufsize + 1); } else break; } else { /* Resolve buf relative to me: */ buf[len] = 0; buf = absolutize(buf, me); me = buf; buf = (char *)malloc(bufsize + 1); } } start = as_int(config + 8); prog_end = as_int(config + 12); end = as_int(config + 16); count = as_int(config + 20); x11 = as_int(config + 24); { int offset, len; offset = _coldir_offset; while (1) { len = strlen(_coldir + offset); offset += len + 1; if (!_coldir[offset]) break; collcount++; } } data = (char *)malloc(end - prog_end); new_argv = (char **)malloc((count + argc + (2 * collcount) + 8) * sizeof(char*)); fd = open(me, O_RDONLY, 0); lseek(fd, prog_end, SEEK_SET); { int expected_length = end - prog_end; if (expected_length != read(fd, data, expected_length)) { printf("read failed to read all %i bytes from file %s\n", expected_length, me); abort(); } } close(fd); exe_path = data; data = next_string(data); lib_path = data; data = next_string(data); exe_path = absolutize(exe_path, me); lib_path = absolutize(lib_path, me); # ifdef OS_X # define LD_LIB_PATH "DYLD_LIBRARY_PATH" # else # define LD_LIB_PATH "LD_LIBRARY_PATH" # endif if (*lib_path) { dll_path = getenv(LD_LIB_PATH); if (!dll_path) { dll_path = ""; } dll_path = string_append(dll_path, ":"); dll_path = string_append(lib_path, dll_path); dll_path = string_append(LD_LIB_PATH "=", dll_path); putenv(dll_path); } new_argv[0] = me; argpos = 1; inpos = 1; /* Keep all X11 flags to the front: */ if (x11) { int n; while (inpos < argc) { n = is_x_flag(argv[inpos]); if (!n) break; if (inpos + n > argc) { write_str(2, argv[0]); write_str(2, ": missing an argument for "); write_str(2, argv[inpos]); write_str(2, "\n"); return 1; } while (n--) { new_argv[argpos++] = argv[inpos++]; } } } /* Add -X and -S flags */ { int offset, len; offset = _coldir_offset; new_argv[argpos++] = "-X"; new_argv[argpos++] = absolutize(_coldir + offset, me); while (1) { len = strlen(_coldir + offset); offset += len + 1; if (!_coldir[offset]) break; new_argv[argpos++] = "-S"; new_argv[argpos++] = absolutize(_coldir + offset, me); } } /* Add built-in flags: */ while (count--) { new_argv[argpos++] = data; data = next_string(data); } /* Propagate new flags (after the X11 flags) */ while (inpos < argc) { new_argv[argpos++] = argv[inpos++]; } new_argv[argpos] = NULL; /* Execute the original binary: */ v = execv(exe_path, new_argv); en = errno; write_str(2, argv[0]); write_str(2, ": failed to start "); write_str(2, exe_path); write_str(2, " ("); write_str(2, strerror(en)); write_str(2, ")\n"); if (*lib_path) { write_str(2, " used library path "); write_str(2, lib_path); write_str(2, "\n"); } return v; }
bool WalkDir_DeepFirst(char *StartPath,bool RecurseFlag,bool DoDirs, FileFuncType FileFunc,DirStartFuncType DirStartFunc,DirDoneFuncType DirDoneFunc) { struct WalkState *CurState,*GotState; DIR * DFD; bool Ok = 1; char WasInDir[1024]; bool KeepGoing=1; if ( !getcwd(WasInDir,1024) ) return(0); if ( ! HaveExitTrap ) if ( atexit(WalkerExit) == 0 ) HaveExitTrap = 1; ExitResetDir = WasInDir; if ( (CurState = malloc(sizeof(struct WalkState))) == NULL ) return(0); CurState->Next = NULL; CurState->NestLevel = -1; CurState->WalkerFlag = 0; if ( !StartPath ) { strcpy(CurState->Path,WasInDir); } else { int err = chdir(StartPath); if ( err != 0 ) return 0; if ( !getcwd(CurState->Path,1024) ) { free(CurState); return(0); } } if ( RecurseFlag) { struct WalkState * ListHead = CurState; do { GotState = ListHead; while(GotState && GotState->WalkerFlag ) GotState = GotState->Next; if ( GotState ) { if ( KeepGoing ) { if ( DFD = opendir(GotState->Path) ) { if ( chdir(GotState->Path) == 0 ) { if ( KeepGoing ) KeepGoing = WalkCurDir(DFD,GotState->Path,GotState->NestLevel, 1,0,NULL,&ListHead); } else Ok = 0; closedir(DFD); } } GotState->WalkerFlag = 1; } } while ( GotState ); CurState = ListHead; } while( CurState ) { GotState = CurState; CurState = CurState->Next; if ( KeepGoing ) { if ( DFD = opendir(GotState->Path) ) { if ( chdir(GotState->Path) == 0 ) { if ( DirStartFunc && KeepGoing ) KeepGoing = (*DirStartFunc)(GotState->Path,GotState->NestLevel); CatPaths(GotState->Path,""); if ( KeepGoing ) KeepGoing = WalkCurDir(DFD,GotState->Path,GotState->NestLevel, RecurseFlag,DoDirs,FileFunc,&CurState); if ( KeepGoing && DirDoneFunc ) KeepGoing = (*DirDoneFunc)(GotState->Path,GotState->NestLevel); closedir(DFD); DFD = NULL; } else Ok = 0; if ( DFD) closedir(DFD); } else { if ( chdir(GotState->Path) == 0 ) { if ( DirStartFunc && KeepGoing ) KeepGoing = (*DirStartFunc)(GotState->Path,GotState->NestLevel); if ( KeepGoing && DirDoneFunc ) KeepGoing = (*DirDoneFunc)(GotState->Path,GotState->NestLevel); } } } free(GotState); } { int err = chdir(WasInDir); assert( err == 0 ); } ExitResetDir = NULL; return(Ok); }
int main(void) { signal(SIGTSTP,sig_handler);//call signal_handler pid_t spgid; int isinter,ret,shell=STDIN_FILENO; struct termios shell_tmodes; isinter=isatty(shell); if(isinter) { while(tcgetpgrp(shell)!=(spgid=getpgrp()))//if shell not in foreground process group send SIGINT signal to it kill(-spgid,SIGTTIN); signal(SIGINT,SIG_IGN);//reset behaviour of signals for interactive shell signal(SIGQUIT,SIG_IGN); signal(SIGTTIN,SIG_IGN); signal(SIGTTOU,SIG_IGN); spgid=getpid();//find pid of current process if(setpgid(spgid,spgid)<0)//put process in foregroung process group { perror("cant put shell in its process grp");//error if failed exit(1); } tcsetpgrp(shell,spgid);//set group attributes for shell tcgetattr(shell,&shell_tmodes);//store shell attributes in shell_tmodes } pid_t pid; int curpid,len,i,j,k,status,background=0; char c,home[100],cmd[1000],prompt[400],cwd[100],uname[100],hname[100]; getlogin_r(uname,100);//find username of currently logged in user gethostname(hname,100);//find system_name of the host prompt[0]='<';//construct prompt prompt[1]='\0'; strcat(prompt,uname);//append username prompt[strlen(prompt)+1]='\0'; prompt[strlen(prompt)]='@'; strcat(prompt,hname);//append sysname prompt[strlen(prompt)+1]='\0'; prompt[strlen(prompt)]=':'; len=strlen(prompt);//find length of prompt const char *homedir = getenv("HOME");//find the name of homedir chdir(homedir);//The directory from which the shell is invoked will be the home directory of the shell while(1) { check_status();//check the status of all background processes print if terminated background=0;//set variable bg to 0 if(getcwd(cwd,100)!=NULL)//find cwd { strcpy(home,cwd);//copy it to home home[strlen(homedir)]='\0'; char*q=cwd;//point q to cwd char*p=q+strlen(homedir);//point p to part of cwd after len(homedir) if(!strcmp(home,homedir))//compare if home and homedir are same { cwd[0]='~';//replace cwd by ~ cwd[1]='\0'; strcat(cwd,p);//and concatenate p after ~ to get remaining dir name } prompt[len]='\0'; strcat(prompt,cwd);//concatenate cwd to prompt } else perror("getcwd() error");//if getcwd = NULL error prompt[strlen(prompt)+1]='\0'; prompt[strlen(prompt)]='>';//add last char of prompt do//get a executable command { check_status();//check the status of all background processes print if terminated cmd[0]='\0';//set cmd to NULL fprintf(stdout,"%s",prompt);//print prompt scanf("%[^\n]",cmd);//get cmd getchar();//get the newline character for(i=0;i<100;i++)//set all argument to NULL initially arg[i]=NULL; i=0; res=strtok(cmd," \t");//tokenize the string i/p while(res!=NULL) { arg[i++]=res; res=strtok(NULL," \t"); } argc=i;//set no. of arguments }while(arg[0]==NULL);//keep taking commands until we get an executable(handles cases with only enters and tabs int flag=0,flag2=0; for(i=0;i<argc;i++)//check for redirection and pipe { if(!strcmp(arg[i],">")||!strcmp(arg[i],"<")||!strcmp(arg[i],">>"))//set flag to 1 if redirection present flag=1; else if(!strcmp(arg[i],"|"))//set flag2 to 1 if pipe present flag2=1; } if(flag2==1)//if pipe { char* cmd[100][100];//store commands separated by pipes for(i=0;i<100;i++)//allocate storage for each command for(j=0;j<100;j++) cmd[i][j]=(char*)malloc(sizeof(char)*100); j=k=0; for(i=0;i<argc;i++)//traverse the arguments { if(!strcmp(arg[i],"|"))//goto next command if pipe found { cmd[j][k]=NULL; j++; k=0; continue; } strcpy(cmd[j][k],arg[i]);//set cmd to args k++; } cmd[j][k]=NULL;//set last value to NULL int num_pipes=j;//store number of pipes int pip=num_pipes*2;//pip is number of pipeds to create int *pipes=malloc(sizeof(int)*pip);//allocate an array pipes for(i=0;i<num_pipes;i++)//create pipes if(pipe(pipes+2*i)<0) { perror("Couldn't Pipe");//if return value is -ve error _exit(1); } for(i=0;i<=num_pipes;i++)//loop through all commands(num_pipes+1) { if((pid=fork())<0)//fork a new process { perror("error forking"); exit(EXIT_FAILURE); } if(!pid)//in child process { int ip=0,op=0,fd,x,y,z,ff,j1,j2,j3; for(x=0;cmd[i][x]!=NULL;x++)//check redirection { if(!strcmp(cmd[i][x],"<"))//checkk if < { ip=1;//set ip to 1 as input source is already changed j1=x; fd=open(cmd[i][j1+1],O_RDONLY,0666);//open the file in read mode if(fd<0)//if file descriptor -ve error { perror("error opening file"); exit(EXIT_FAILURE); } dup2(fd,0);//set input for process to fd close(fd);//close fd cmd[i][x]=NULL;//change cmd to NULL break; } else if(!strcmp(cmd[i][x],">"))//checkk if > { j2=x; op=1;//set op to 1 as output source is already changed fd=open(cmd[i][j2+1],O_WRONLY|O_CREAT,0666);//open file in write or create mode if(fd<0)//if file descriptor -ve error { perror("error opening file"); exit(EXIT_FAILURE); } dup2(fd,1);//set output for process to fd close(fd);//close fd cmd[i][x]=NULL;//change cmd to NULL break; } else if(!strcmp(cmd[i][x],">>"))//check if >> { j3=x; fd=open(cmd[i][j3+1],O_WRONLY|O_APPEND|O_CREAT,0666);//open file in write/creat/append mode op=1;//set op to 1 as output source is already changed if(fd<0)//if file descriptor -ve error { perror("error opening file"); exit(EXIT_FAILURE); } dup2(fd,1);//set output for process to fd close(fd);//close fd cmd[i][x]=NULL;//change cmd to NULL break; } } if(i!=0&&!ip)//if not first command and ip not already changed { if(dup2(pipes[2*(i-1)],0)<0)//change input to the previous pipe { perror("dup2()");//error if failed exit(EXIT_FAILURE); } } if(i<num_pipes&&!op)//if not last command and output not already changed { if(dup2(pipes[2*i+1],1)<0)//change output to next pipe { perror("dup2()");//error if failed exit(EXIT_FAILURE); } } for(k=0;k<pip;k++)//close all pipes close(pipes[k]); if(execvp(cmd[i][0],cmd[i])<0)//execute the commmands { perror("error executing");//if return value < 0 error exit(EXIT_FAILURE); } } } for(i=0;i<pip;i++)//close all pipes close(pipes[i]); int stat; for(i=0;i<=num_pipes;i++)//wait for all child processes wait(&stat); continue; } if(!strcmp(arg[argc-1],"&"))//check if background process { arg[argc-1]=NULL; background=1; } else if(!strcmp(arg[0],"quit"))//if cmd is quit then stop the shell break; else if(!strcmp(arg[0],"cd"))//check if cd { if(arg[1]==NULL || strcmp(arg[1],"~")==0 ||strcmp(arg[1],"~/")==0|| strcmp(arg[1],"")==0)//check if change to home { if(chdir(getenv("HOME"))<0)//if chdir fails error { perror("error changing"); } } else { ret=chdir(arg[1]);//change dir to arg1 if(ret<0)//if chdir fails error perror("directory does not exist"); } continue; } else if(!strcmp(arg[0],"pinfo")&&arg[1]==NULL){//pinfo command int procid=getpid();//find pid of running process pinfo(procid);//call pinfo with that pid continue; } else if(!strcmp(arg[0],"pinfo")&&arg[1]!=NULL&&arg[2]==NULL){//pinfo command with given pid pinfo(atoi(arg[1]));//pass arg to pinfo by converting to integer the arg[1] continue; } else if(!strcmp(arg[0],"jobs"))//print all background processes { check_status();//check the status of all background processes int j=0,k,n=1,fd; if(arg[1]!=NULL&&!strcmp(arg[1],">")) { fd=open(arg[2],O_WRONLY|O_CREAT,0666);//open file in write or create mode if(fd<0)//if file descriptor -ve error { perror("error opening file"); exit(EXIT_FAILURE); } dup2(fd,1);//set output for process to fd close(fd);//close fd } for(j=0;j<parrptr;j++)//for all processes in parr { if(parr[j].stat)//check if status is running { fprintf(stdout,"[%d] ",n);//print job number for(k=0;k<parr[j].argcnt;k++)//print all arguments fprintf(stdout,"%s ",parr[j].cname[k]); fprintf(stdout,"[%d]\n",parr[j].pid);//print pid n++;//increment job number } } dup2(STDIN_FILENO,1);//reset output to stdin continue; } else if(!strcmp(arg[0],"kjob")&&arg[1]!=NULL&&arg[2]!=NULL&&arg[3]==NULL)//send signal in arg[2] to job in arg[1] { int r,id,i,a,b,n; a=atoi(arg[1]);//convert string to int b=atoi(arg[2]); n=0; for(i=0;n<a&&i<parrptr;i++)//find the job in the parr { if(parr[i].stat==1) n++; } if(a!=n)//if job not found error fprintf(stdout,"no such job\n"); else { id=parr[i-1].pid;//find pid of job r=kill(id,b);//send signal to job if(r==-1)//if return value -1 error perror("signal not sent"); else if(r==0)//else sent fprintf(stdout,"signal sent\n"); } continue; } else if(!strcmp(arg[0],"fg")&&arg[1]!=NULL&&arg[2]==NULL)//brinf job stored in arg[1] to foreground { int st,id,i,a,n; a=atoi(arg[1]);//convert str to int n=0; for(i=0;n<a&&i<parrptr;i++)//find the job in parr { if(parr[i].stat==1) n++; } if(a!=n)//if job not found error fprintf(stdout,"no such job\n"); else { id=parr[i-1].pid;//find pid of job if(parr[i-1].stop==2)//if job was stopped { curpid=id;//set curpid kill(id,SIGCONT);//send continue signal to the process parr[i-1].stop=0;//set stop to 1 } waitpid(id,&status,WUNTRACED);//wait for signal from process if(WIFSTOPPED(status))//if process stopped again { parr[i-1].stop=2;//set stop to 2 } } continue; } else if(!strcmp(arg[0],"overkill")&&arg[1]==NULL)//kill all background processes { int i; for(i=0;i<parrptr;i++) { if(parr[i].stat)//if process is running { kill(parr[i].pid,SIGKILL);//send SIGKILL signal } } continue; } if(flag==1)//if redirection { int ppid; if(ppid=fork())//create a child process { int pid; wait(&pid);//in parent wait for child process } else if(ppid<0) perror("fork()"); else//in child process { int f1,f2,f3,f4; int i,j1,j2,j3; int rt=0; int fd; char** arr=(char **)malloc(sizeof(char)*100);//stores the commands without the redirestion symbols for(i=0;i<100;i++)//allocate space to store commands arr[i]=(char *)malloc(sizeof(char)*100); f1=f2=f3=0;//set flags to 0 for(i=0;i<argc;i++)//check all arguments if >,< or >> { if(!strcmp(arg[i],"<"))//if < cmd { j1=i; f1=1; fd=open(arg[j1+1],O_RDONLY,0666);//open the file in next arg in read only mode if(fd<0)//if return value -ve error { perror("error opening file"); _exit(1); } dup2(fd,0);//change input to new file descriptor close(fd);//close file descriptor } else if(!strcmp(arg[i],">"))//if > cmd { j2=i; f2=1; fd=open(arg[j2+1],O_WRONLY|O_CREAT,0666);//open file in next arg in write only or create mode if(fd<0)//if return value -ve error { perror("error opening file"); _exit(1); } dup2(fd,1);//change output to new file descriptor close(fd);//close file descriptor } else if(!strcmp(arg[i],">>")) { j3=i; f3=1; fd=open(arg[j3+1],O_WRONLY|O_APPEND|O_CREAT,0666);//open file next arg in write only or create mode or append mode if(fd<0)//if return value -ve error { perror("error opening file"); _exit(1); } dup2(fd,1);//change output to new file descriptor close(fd);//close file descriptor } if(!f1&&!f2&&!f3)//if not redirection { strcpy(arr[rt],arg[i]);//copy arg in arr rt++; } } arr[rt]='\0';//set last arg to NULL if(execvp(arr[0],arr)<0)//execute the command perror("execvp()");//error if return value negative } } else//if normal process { pid_t pid1=fork();//create new process if(pid1==-1)//error if fork return -1 { perror("Error in creating fork : "); exit(EXIT_FAILURE); } else if(pid1==0)//child process { ret=execvp(arg[0],arg);//execute the process if (ret == -1)//it return value -ve error { perror("no such command"); fflush(stdout); _exit(1); } } else if(pid1>0)//in parent { if(background==1 )//if background process set curpid to -1 { curpid=-1; for(j=0;j<100;j++)//store process in parr parr[parrptr].cname[j][0]='\0'; parr[parrptr].pid=pid1;//copy pid for(j=0;j<argc-1;j++)//copy all args except & { strcpy(parr[parrptr].cname[j],arg[j]); } parr[parrptr].stat=1;//set stat to running parr[parrptr].argcnt=argc-1;//argcnt to argc - 1 parr[parrptr].stop=0;//set stop to 0 parrptr++;//increment parr pointer } if(background==0)//for foreground process { waitpid(pid1,&status,WUNTRACED);//wait for process if(WIFSTOPPED(status)) //if status id is stopped push to background { parr[parrptr].pid = pid1;//set pid parr[parrptr].stat = 1; //set stat for(i=0;i<argc;i++)//copy all args strcpy(parr[parrptr].cname[i],arg[i]); parr[parrptr].argcnt=argc;//set argcnt to argc parr[parrptr].stop=2;//change stop to 2 parrptr++; //increment parr pointer } } } } check_status();//checks the status of all background processes }//exit while loop for(i=0;i<parrptr;i++)//kill all running proccesses { if(parr[i].stat)//if process is still running { kill(parr[i].pid,SIGKILL);//send kill signal } } return 0; }
char *stripdir(const char *dir) { const char * in; char * out; char * last; int ldots; int maxlen = DUC_PATH_MAX; char *buf = duc_malloc(maxlen); in = dir; out = buf; last = buf + maxlen; ldots = 0; *out = 0; if (*in != '/') { if (getcwd(buf, maxlen - 2) ) { out = buf + strlen(buf) - 1; if (*out != '/') *(++out) = '/'; out++; } else { free(buf); return NULL; } } while (out < last) { *out = *in; if (*in == '/') { while (*(++in) == '/') ; in--; } if (*in == '/' || !*in) { if (ldots == 1 || ldots == 2) { while (ldots > 0 && --out > buf) { if (*out == '/') ldots--; } *(out+1) = 0; } ldots = 0; } else if (*in == '.' && ldots > -1) { ldots++; } else { ldots = -1; } out++; if (!*in) break; in++; } if (*in) { errno = ENOMEM; free(buf); return NULL; } while (--out != buf && (*out == '/' || !*out)) *out=0; return buf; }
/* * MAIN */ int main(int argc, char *argv[]) { int opt_ch; int errs = 0; char *server; struct sockaddr_in server_addr; CLIENT *clnt = NULL; struct hostent *hp; int nodefault = 0; struct timeval tv; char *progname = NULL; /* * Compute program name */ if (argv[0]) { progname = strrchr(argv[0], '/'); if (progname && progname[1]) progname++; else progname = argv[0]; } if (!progname) progname = "amq"; am_set_progname(progname); /* * Parse arguments */ while ((opt_ch = getopt(argc, argv, "Hfh:il:mqsuvx:D:pP:TUw")) != -1) switch (opt_ch) { case 'H': goto show_usage; break; case 'f': flush_flag = 1; nodefault = 1; break; case 'h': def_server = optarg; break; case 'i': mapinfo_flag = 1; nodefault = 1; break; case 'l': amq_logfile = optarg; nodefault = 1; break; case 'm': minfo_flag = 1; nodefault = 1; break; case 'p': getpid_flag = 1; nodefault = 1; break; case 'q': quiet_flag = 1; nodefault = 1; break; case 's': stats_flag = 1; nodefault = 1; break; case 'u': unmount_flag++; nodefault = 1; break; case 'v': getvers_flag = 1; nodefault = 1; break; case 'x': xlog_optstr = optarg; nodefault = 1; break; case 'D': debug_opts = optarg; nodefault = 1; break; case 'P': amd_program_number = atoi(optarg); break; case 'T': use_tcp_flag = 1; break; case 'U': use_udp_flag = 1; break; case 'w': getpwd_flag = 1; break; default: errs = 1; break; } if (optind == argc) { if (unmount_flag) errs = 1; } if (errs) { show_usage: fprintf(stderr, "\ Usage: %s [-fimpqsvwHTU] [-h hostname] [-l log_file|\"syslog\"]\n\ \t[-x log_options] [-D debug_options]\n\ \t[-P program_number] [[-u[u]] directory ...]\n", am_get_progname() ); exit(1); } /* set use_udp and use_tcp flags both to on if none are defined */ if (!use_tcp_flag && !use_udp_flag) use_tcp_flag = use_udp_flag = 1; #if defined(HAVE_CLUSTER_H) && defined(HAVE_CNODEID) && defined(HAVE_GETCCENT) /* * Figure out root server of cluster */ if (def_server == localhost) server = cluster_server(); else #endif /* defined(HAVE_CLUSTER_H) && defined(HAVE_CNODEID) && defined(HAVE_GETCCENT) */ server = def_server; /* * Get address of server */ if ((hp = gethostbyname(server)) == 0 && !STREQ(server, localhost)) { fprintf(stderr, "%s: Can't get address of %s\n", am_get_progname(), server); exit(1); } memset(&server_addr, 0, sizeof(server_addr)); /* as per POSIX, sin_len need not be set (used internally by kernel) */ server_addr.sin_family = AF_INET; if (hp) { memmove((voidp) &server_addr.sin_addr, (voidp) hp->h_addr, sizeof(server_addr.sin_addr)); } else { /* fake "localhost" */ server_addr.sin_addr.s_addr = htonl(0x7f000001); } /* * Create RPC endpoint */ tv.tv_sec = 5; /* 5 seconds for timeout or per retry */ tv.tv_usec = 0; if (use_tcp_flag) /* try tcp first */ clnt = clnt_create(server, amd_program_number, AMQ_VERSION, "tcp"); if (!clnt && use_udp_flag) { /* try udp next */ clnt = clnt_create(server, amd_program_number, AMQ_VERSION, "udp"); /* if ok, set timeout (valid for connectionless transports only) */ if (clnt) clnt_control(clnt, CLSET_RETRY_TIMEOUT, (char *) &tv); } if (!clnt) { fprintf(stderr, "%s: ", am_get_progname()); clnt_pcreateerror(server); exit(1); } /* * Control debugging */ if (debug_opts) { int *rc; amq_setopt opt; opt.as_opt = AMOPT_DEBUG; opt.as_str = debug_opts; rc = amqproc_setopt_1(&opt, clnt); if (rc && *rc < 0) { fprintf(stderr, "%s: daemon not compiled for debug\n", am_get_progname()); errs = 1; } else if (!rc || *rc > 0) { fprintf(stderr, "%s: debug setting for \"%s\" failed\n", am_get_progname(), debug_opts); errs = 1; } } /* * Control logging */ if (xlog_optstr) { int *rc; amq_setopt opt; opt.as_opt = AMOPT_XLOG; opt.as_str = xlog_optstr; rc = amqproc_setopt_1(&opt, clnt); if (!rc || *rc) { fprintf(stderr, "%s: setting log level to \"%s\" failed\n", am_get_progname(), xlog_optstr); errs = 1; } } /* * Control log file */ if (amq_logfile) { int *rc; amq_setopt opt; opt.as_opt = AMOPT_LOGFILE; opt.as_str = amq_logfile; rc = amqproc_setopt_1(&opt, clnt); if (!rc || *rc) { fprintf(stderr, "%s: setting logfile to \"%s\" failed\n", am_get_progname(), amq_logfile); errs = 1; } } /* * Flush map cache */ if (flush_flag) { int *rc; amq_setopt opt; opt.as_opt = AMOPT_FLUSHMAPC; opt.as_str = ""; rc = amqproc_setopt_1(&opt, clnt); if (!rc || *rc) { fprintf(stderr, "%s: amd on %s cannot flush the map cache\n", am_get_progname(), server); errs = 1; } } /* * getpwd info */ if (getpwd_flag) { char path[MAXPATHLEN+1]; char *wd; amq_mount_tree_list *mlp; amq_mount_tree_p mt; u_int i; int flag; wd = getcwd(path, MAXPATHLEN+1); if (!wd) { fprintf(stderr, "%s: getcwd failed (%s)", am_get_progname(), strerror(errno)); exit(1); } mlp = amqproc_export_1((voidp) 0, clnt); for (i = 0; mlp && i < mlp->amq_mount_tree_list_len; i++) { mt = mlp->amq_mount_tree_list_val[i]; while (1) { flag = 0; show_pwd(mt, path, sizeof(path), &flag); if (!flag) { printf("%s\n", path); break; } } } exit(0); } /* * Mount info */ if (minfo_flag) { int dummy; amq_mount_info_list *ml = amqproc_getmntfs_1(&dummy, clnt); if (ml) { int mwid = 0, dwid = 0, twid = 0; show_mi(ml, Calc, &mwid, &dwid, &twid); mwid++; dwid++; twid++; show_mi(ml, Full, &mwid, &dwid, &twid); } else { fprintf(stderr, "%s: amd on %s cannot provide mount info\n", am_get_progname(), server); } } /* * Map */ if (mapinfo_flag) { int dummy; amq_map_info_list *ml = amqproc_getmapinfo_1(&dummy, clnt); if (ml) { int mwid = 0, wwid = 0; show_mapinfo(ml, Calc, &mwid, &wwid); mwid++; if (wwid) wwid++; show_mapinfo(ml, Full, &mwid, &wwid); } else { fprintf(stderr, "%s: amd on %s cannot provide map info\n", am_get_progname(), server); } } /* * Get Version */ if (getvers_flag) { amq_string *spp = amqproc_getvers_1((voidp) 0, clnt); if (spp && *spp) { fputs(*spp, stdout); XFREE(*spp); } else { fprintf(stderr, "%s: failed to get version information\n", am_get_progname()); errs = 1; } } /* * Get PID of amd */ if (getpid_flag) { int *ip = amqproc_getpid_1((voidp) 0, clnt); if (ip && *ip) { printf("%d\n", *ip); } else { fprintf(stderr, "%s: failed to get PID of amd\n", am_get_progname()); errs = 1; } } /* * Apply required operation to all remaining arguments */ if (optind < argc) { do { char *fs = argv[optind++]; if (unmount_flag > 1) { amq_sync_umnt *sup; /* * Synchronous unmount request */ sup = amqproc_sync_umnt_1(&fs, clnt); if (sup) { if (quiet_flag == 0) print_umnt_error(sup, fs); errs = amu_sync_umnt_to_retval(sup); } else { errs = clnt_failed(clnt, server); } } else if (unmount_flag) { /* * Unmount request */ amqproc_umnt_1(&fs, clnt); } else { /* * Stats request */ amq_mount_tree_p *mtp = amqproc_mnttree_1(&fs, clnt); if (mtp) { amq_mount_tree *mt = *mtp; if (mt) { int mwid = 0, dwid = 0, twid = 0; show_mt(mt, Calc, &mwid, &dwid, &twid); mwid++; dwid++, twid++; printf("%-*.*s Uid Getattr Lookup RdDir RdLnk Statfs Mounted@\n", dwid, dwid, "What"); show_mt(mt, Stats, &mwid, &dwid, &twid); } else { fprintf(stderr, "%s: %s not automounted\n", am_get_progname(), fs); } xdr_pri_free((XDRPROC_T_TYPE) xdr_amq_mount_tree_p, (caddr_t) mtp); } else { errs = clnt_failed(clnt, server); } } } while (optind < argc); } else if (unmount_flag) { goto show_usage; } else if (stats_flag) { amq_mount_stats *ms = amqproc_stats_1((voidp) 0, clnt); if (ms) { show_ms(ms); } else { errs = clnt_failed(clnt, server); } } else if (!nodefault) { amq_mount_tree_list *mlp = amqproc_export_1((voidp) 0, clnt); if (mlp) { enum show_opt e = Calc; int mwid = 0, dwid = 0, pwid = 0; while (e != ShowDone) { u_int i; for (i = 0; i < mlp->amq_mount_tree_list_len; i++) { show_mt(mlp->amq_mount_tree_list_val[i], e, &mwid, &dwid, &pwid); } mwid++; dwid++, pwid++; if (e == Calc) e = Short; else if (e == Short) e = ShowDone; } } else { errs = clnt_failed(clnt, server); } } exit(errs); return errs; /* should never reach here */ }
/* getwd */ char * getwd(char * buf) { /* XXX this is a potential security flaw */ return getcwd(buf, PATH_MAX); }
EXPORT bool glx_init(glxlink *mod) { gl_verbose("initializing matlab link"); gl_verbose("PATH=%s", getenv("PATH")); // initialize matlab engine MATLABLINK *matlab = (MATLABLINK*)mod->get_data(); matlab->status = 0; #ifdef WIN32 if ( matlab->command ) matlab->engine = engOpen(matlab->command); else matlab->engine = engOpenSingleUse(NULL,NULL,&matlab->status); if ( matlab->engine==NULL ) { gl_error("matlab engine start failed, status code is '%d'", matlab->status); return false; } #else matlab->engine = engOpen(matlab->command); if ( matlab->engine==NULL ) { gl_error("matlab engine start failed"); return false; } #endif // set the output buffer if ( matlab->output_buffer!=NULL ) engOutputBuffer(matlab->engine,matlab->output_buffer,(int)matlab->output_size); // setup matlab engine engSetVisible(matlab->engine,window_show(matlab)); gl_debug("matlab link is open"); // special values needed by matlab mxArray *ts_never = mxCreateDoubleScalar((double)(TIMESTAMP)TS_NEVER); engPutVariable(matlab->engine,"TS_NEVER",ts_never); mxArray *ts_error = mxCreateDoubleScalar((double)(TIMESTAMP)TS_INVALID); engPutVariable(matlab->engine,"TS_ERROR",ts_error); mxArray *gld_ok = mxCreateDoubleScalar((double)(bool)true); engPutVariable(matlab->engine,"GLD_OK",gld_ok); mxArray *gld_err = mxCreateDoubleScalar((double)(bool)false); engPutVariable(matlab->engine,"GLD_ERROR",gld_err); // set the workdir if ( strcmp(matlab->workdir,"")!=0 ) { #ifdef WIN32 _mkdir(matlab->workdir); #else mkdir(matlab->workdir,0750); #endif if ( matlab->workdir[0]=='/' ) matlab_exec(matlab,"cd '%s'", matlab->workdir); else matlab_exec(matlab,"cd '%s/%s'", getcwd(NULL,0),matlab->workdir); } // run the initialization command(s) if ( matlab->init ) { mxArray *ans = matlab_exec(matlab,"%s",matlab->init); if ( ans && mxIsDouble(ans) && (bool)*mxGetPr(ans)==false ) { gl_error("matlab init failed"); return false; } else if ( ans && mxIsChar(ans) ) { int buflen = (mxGetM(ans) * mxGetN(ans)) + 1; char *string =(char*)malloc(buflen); int status_error = mxGetString(ans, string, buflen); if (status_error == 0) { gl_error("'%s'",string); return false; } else { gl_error("Did not catch Matlab error"); return false; } } } if ( matlab->rootname!=NULL ) { // build gridlabd data mwSize dims[] = {1,1}; mxArray *gridlabd_struct = mxCreateStructArray(2,dims,0,NULL); /////////////////////////////////////////////////////////////////////////// // build global data LINKLIST *item; mxArray *global_struct = mxCreateStructArray(2,dims,0,NULL); for ( item=mod->get_globals() ; item!=NULL ; item=mod->get_next(item) ) { char *name = mod->get_name(item); GLOBALVAR *var = mod->get_globalvar(item); mxArray *var_struct = NULL; mwIndex var_index; if ( var==NULL ) continue; // do not map module or structured globals if ( strchr(var->prop->name,':')!=NULL ) { // ignore module globals here } else if ( strchr(var->prop->name,'.')!=NULL ) { char struct_name[256]; if ( sscanf(var->prop->name,"%[^.]",struct_name)==0 ) { gld_property prop(var); var_index = mxAddField(global_struct,prop.get_name()); var_struct = matlab_create_value(&prop); if ( var_struct!=NULL ) { //mod->add_copyto(var->prop->addr,mxGetData(var_struct)); mxSetFieldByNumber(global_struct,0,var_index,var_struct); } } } else // simple data { gld_property prop(var); var_index = mxAddField(global_struct,prop.get_name()); var_struct = matlab_create_value(&prop); if ( var_struct!=NULL ) { //mod->add_copyto(var->prop->addr,mxGetData(var_struct)); mxSetFieldByNumber(global_struct,0,var_index,var_struct); } } // update export list if ( var_struct!=NULL ) { mod->set_addr(item,(void*)var_struct); mod->set_index(item,(size_t)var_index); } } // add globals structure to gridlabd structure mwIndex gridlabd_index = mxAddField(gridlabd_struct,"global"); mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,global_struct); /////////////////////////////////////////////////////////////////////////// // build module data dims[0] = dims[1] = 1; mxArray *module_struct = mxCreateStructArray(2,dims,0,NULL); // add modules for ( MODULE *module = callback->module.getfirst() ; module!=NULL ; module=module->next ) { // create module info struct mwIndex dims[] = {1,1}; mxArray *module_data = mxCreateStructArray(2,dims,0,NULL); mwIndex module_index = mxAddField(module_struct,module->name); mxSetFieldByNumber(module_struct,0,module_index,module_data); // create version info struct const char *version_fields[] = {"major","minor"}; mxArray *version_data = mxCreateStructArray(2,dims,sizeof(version_fields)/sizeof(version_fields[0]),version_fields); mxArray *major_data = mxCreateDoubleScalar((double)module->major); mxArray *minor_data = mxCreateDoubleScalar((double)module->minor); mxSetFieldByNumber(version_data,0,0,major_data); mxSetFieldByNumber(version_data,0,1,minor_data); // attach version info to module info mwIndex version_index = mxAddField(module_data,"version"); mxSetFieldByNumber(module_data,0,version_index,version_data); } gridlabd_index = mxAddField(gridlabd_struct,"module"); mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,module_struct); /////////////////////////////////////////////////////////////////////////// // build class data dims[0] = dims[1] = 1; mxArray *class_struct = mxCreateStructArray(2,dims,0,NULL); gridlabd_index = mxAddField(gridlabd_struct,"class"); mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,class_struct); mwIndex class_id[1024]; // index into class struct memset(class_id,0,sizeof(class_id)); // add classes for ( CLASS *oclass = callback->class_getfirst() ; oclass!=NULL ; oclass=oclass->next ) { // count objects in this class mwIndex dims[] = {0,1}; for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) ) { OBJECT *obj = mod->get_object(item); if ( obj==NULL || obj->oclass!=oclass ) continue; dims[0]++; } if ( dims[0]==0 ) continue; mxArray *runtime_struct = mxCreateStructArray(2,dims,0,NULL); // add class mwIndex class_index = mxAddField(class_struct,oclass->name); mxSetFieldByNumber(class_struct,0,class_index,runtime_struct); // add properties to class for ( PROPERTY *prop=oclass->pmap ; prop!=NULL && prop->oclass==oclass ; prop=prop->next ) { mwIndex dims[] = {1,1}; mxArray *property_struct = mxCreateStructArray(2,dims,0,NULL); mwIndex runtime_index = mxAddField(runtime_struct,prop->name); mxSetFieldByNumber(runtime_struct,0,runtime_index,property_struct); } // add objects to class for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) ) { OBJECT *obj = mod->get_object(item); if ( obj==NULL || obj->oclass!=oclass ) continue; mwIndex index = class_id[obj->oclass->id]++; // add properties to class for ( PROPERTY *prop=oclass->pmap ; prop!=NULL && prop->oclass==oclass ; prop=prop->next ) { gld_property p(obj,prop); mxArray *data = matlab_create_value(&p); mxSetField(runtime_struct,index,prop->name,data); } // update export list mod->set_addr(item,(void*)runtime_struct); mod->set_index(item,(size_t)index); } } /////////////////////////////////////////////////////////////////////////// // build the object data dims[0] = 0; for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) ) { if ( mod->get_object(item)!=NULL ) dims[0]++; } dims[1] = 1; memset(class_id,0,sizeof(class_id)); const char *objfields[] = {"name","class","id","parent","rank","clock","valid_to","schedule_skew", "latitude","longitude","in","out","rng_state","heartbeat","lock","flags"}; mxArray *object_struct = mxCreateStructArray(2,dims,sizeof(objfields)/sizeof(objfields[0]),objfields); mwIndex n=0; for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) ) { OBJECT *obj = mod->get_object(item); if ( obj==NULL ) continue; class_id[obj->oclass->id]++; // index into class struct const char *objname[] = {obj->name&&isdigit(obj->name[0])?NULL:obj->name}; const char *oclassname[] = {obj->oclass->name}; if (obj->name) mxSetFieldByNumber(object_struct,n,0,mxCreateCharMatrixFromStrings(mwSize(1),objname)); mxSetFieldByNumber(object_struct,n,1,mxCreateCharMatrixFromStrings(mwSize(1),oclassname)); mxSetFieldByNumber(object_struct,n,2,mxCreateDoubleScalar((double)class_id[obj->oclass->id])); if (obj->parent) mxSetFieldByNumber(object_struct,n,3,mxCreateDoubleScalar((double)obj->parent->id+1)); mxSetFieldByNumber(object_struct,n,4,mxCreateDoubleScalar((double)obj->rank)); mxSetFieldByNumber(object_struct,n,5,mxCreateDoubleScalar((double)obj->clock)); mxSetFieldByNumber(object_struct,n,6,mxCreateDoubleScalar((double)obj->valid_to)); mxSetFieldByNumber(object_struct,n,7,mxCreateDoubleScalar((double)obj->schedule_skew)); if ( isfinite(obj->latitude) ) mxSetFieldByNumber(object_struct,n,8,mxCreateDoubleScalar((double)obj->latitude)); if ( isfinite(obj->longitude) ) mxSetFieldByNumber(object_struct,n,9,mxCreateDoubleScalar((double)obj->longitude)); mxSetFieldByNumber(object_struct,n,10,mxCreateDoubleScalar((double)obj->in_svc)); mxSetFieldByNumber(object_struct,n,11,mxCreateDoubleScalar((double)obj->out_svc)); mxSetFieldByNumber(object_struct,n,12,mxCreateDoubleScalar((double)obj->rng_state)); mxSetFieldByNumber(object_struct,n,13,mxCreateDoubleScalar((double)obj->heartbeat)); mxSetFieldByNumber(object_struct,n,14,mxCreateDoubleScalar((double)obj->lock)); mxSetFieldByNumber(object_struct,n,15,mxCreateDoubleScalar((double)obj->flags)); n++; } gridlabd_index = mxAddField(gridlabd_struct,"object"); mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,object_struct); /////////////////////////////////////////////////////////////////////////// // post the gridlabd structure matlab->root = gridlabd_struct; engPutVariable(matlab->engine,matlab->rootname,matlab->root); } /////////////////////////////////////////////////////////////////////////// // build the import/export data for ( LINKLIST *item=mod->get_exports() ; item!=NULL ; item=mod->get_next(item) ) { OBJECTPROPERTY *objprop = mod->get_export(item); if ( objprop==NULL ) continue; // add to published items gld_property prop(objprop->obj,objprop->prop); item->addr = (mxArray*)matlab_create_value(&prop); engPutVariable(matlab->engine,item->name,(mxArray*)item->addr); } for ( LINKLIST *item=mod->get_imports() ; item!=NULL ; item=mod->get_next(item) ) { OBJECTPROPERTY *objprop = mod->get_import(item); if ( objprop==NULL ) continue; // check that not already in export list LINKLIST *export_item; bool found=false; for ( export_item=mod->get_exports() ; export_item!=NULL ; export_item=mod->get_next(export_item) ) { OBJECTPROPERTY *other = mod->get_export(item); if ( memcmp(objprop,other,sizeof(OBJECTPROPERTY)) ) found=true; } if ( !found ) { gld_property prop(objprop->obj,objprop->prop); item->addr = (mxArray*)matlab_create_value(&prop); engPutVariable(matlab->engine,item->name,(mxArray*)item->addr); } } static int32 matlab_flag = 1; gl_global_create("MATLAB",PT_int32,&matlab_flag,PT_ACCESS,PA_REFERENCE,PT_DESCRIPTION,"indicates that MATLAB is available",NULL); mod->last_t = gl_globalclock; return true; }
int main(int argc, char *argv[]) #endif { #ifndef IPHONE #if defined(ARM_ARCH) ChangeWorkingDirectory(argv[0]); getcwd(gamepath, 256); #else #if defined(__WIN32__) if(argc == 1) strncpy(gamepath,"E:\\ps1",256); else strncpy(gamepath,argv[1],256); #else strncpy(gamepath,ROM_PREFIX,256); #endif #endif #endif #ifdef PSP sprintf(gamepath,""); #endif #ifdef IPHONE sprintf(gamepath,""); #endif // Configure the emulator. Hardcoded for now. memset(&Config, 0, sizeof(PsxConfig)); Config.PsxAuto = 1; Config.Cdda = 1; Config.Xa = 0; #ifdef DYNAREC Config.Cpu = 0; #else Config.Cpu = 1; #endif #ifdef WITH_HLE // Testing HLE? Config.HLE = 1; #else // HLE OFF Config.HLE = 0; #endif Config.Mdec = 0; Config.PsxOut = 0; Config.PsxType = 0; Config.QKeys = 0; Config.RCntFix = 0; Config.Sio = 0; Config.SpuIrq = 1; Config.VSyncWA = 0; #if defined(PSP) || defined(SDL) || defined(IPHONE) sprintf(Config.BiosDir, "%s/Media/ROMs/PSX/", appworkdir); sprintf(Config.Bios, "scph1001.bin"); sprintf(Config.Mcd1, "mcd001.mcr"); sprintf(Config.Mcd2, "mcd002.mcr"); #elif defined(HOME_DIR) strcpy(gamepath, getenv("HOME")); strcat(gamepath, "/.psx4all"); mkdir(gamepath, 0755); // create $HOME/.psx4all if doesn't exist sprintf(Config.BiosDir, "%s", gamepath); sprintf(Config.Bios, "/scph1001.bin"); sprintf(Config.Mcd1, "%s/mcd001.mcr", gamepath); sprintf(Config.Mcd2, "%s/mcd002.mcr", gamepath); #else sprintf(Config.BiosDir, "%s", gamepath); sprintf(Config.Bios, "/scph1001.bin"); sprintf(Config.Mcd1, "%s/mcd001.mcr", gamepath); sprintf(Config.Mcd2, "%s/mcd002.mcr", gamepath); #endif gp2x_init(1000, 16, 11025, 16, 1, 60, 1); #ifndef GP2X gp2x_video_flip_single(); #endif #ifdef IPHONE u32 loadsvs = 0; linesInterlace_user = preferences.interlace; skipCount = skipCountTablePhone[preferences.frameSkip]; skipRate = skipRateTablePhone[preferences.frameSkip]; iSoundMuted = preferences.muted; Config.Cdda = preferences.muted; Config.Xa = preferences.muted; #ifdef WITH_HLE // Testing HLE Config.HLE = !preferences.bios; #else // HLE OFF Config.HLE = 0; #endif if( (!strcasecmp(filename + (strlen(filename)-4), ".svs")) ) { u32 pos; loadsvs = 1; sprintf(svsfilename, "%s", filename); sprintf(iphonefile, "%s", filename); pos = strlen(iphonefile)-18; iphonefile[pos] = '\0'; packfile = iphonefile; } else { loadsvs = 0; sprintf(iphonefile, "%s", filename); packfile = iphonefile; } // clear screen gp2x_video_RGB_clearscreen16(); LoadCdBios = 0; if (SysInit() == -1) { gp2x_deinit(); return 0; } if (InitComponents() == -1) { gp2x_deinit(); return 0; } SysReset(); CheckCdrom(); if( Config.HLE ) { LoadCdBios = 0; if( LoadCdrom() == -1 ) { gp2x_printf(NULL, 120, 120, "LOAD FAILED"); gp2x_video_flip(); gp2x_timer_delay(2000); // clear screen gp2x_video_RGB_clearscreen16(); return 0; } } if (loadsvs) { if( LoadState(svsfilename) == -1 ) { gp2x_printf(NULL, 120, 120, "LOAD SAVE FAILED"); gp2x_video_flip(); gp2x_timer_delay(2000); // clear screen gp2x_video_RGB_clearscreen16(); psxShutdown(); CloseComponents(); gp2x_deinit(); pthread_exit(NULL); } } psx4all_emulating=1; psx4all_prof_start(PROFILER_TOTAL); psxCpu->Execute(); psx4all_prof_end(PROFILER_TOTAL); psx4all_emulating=0; psx4all_prof_show(); #else if( 0 != SelectGame() ) { psx4all_emulating=1; psx4all_prof_start(PROFILER_TOTAL); psxCpu->Execute(); psx4all_prof_end(PROFILER_TOTAL); psx4all_emulating=0; psx4all_prof_show(); } #endif gp2x_deinit(); return 0; }
char *osd_getcwd (/*@returned@*/ char *str, size_t size) { return getcwd (str, size); }
int sh( int argc, char **argv, char **envp ) { signal(SIGINT, sig_handle); signal(SIGTERM, SIG_IGN); signal(SIGTSTP, SIG_IGN); char *prompt = calloc(PROMPTMAX, sizeof(char)); char *commandline = calloc(MAX_CANON, sizeof(char)); char *command, *arg, *aliashelp, *commandpath, *p, *pwd, *owd; /* Use these two save chars for strtok_r on command and alias commands*/ char *command_save, *alias_save; char **args = calloc(MAXARGS, sizeof(char*)); int uid, i, status, argsct, a, go = 1; int background, bg_pid = 0; struct passwd *password_entry; char *homedir; struct pathelement *pathlist, *history; struct aliaselement *aliases; const char sp[2] = " "; extern char **environ; glob_t globbuf; size_t glc; char **gl; pthread_t pt_warnload, pt_watchuser; /* for use with warnload */ float load = 0.0; int load_thread = 1; /* for use with watchuser */ static pthread_mutex_t user_lock = PTHREAD_MUTEX_INITIALIZER; int user_thread = 1; struct userarg *userargs; /* for use with file redirection */ int fid; int file_redirect, error_redirect, input_redirect = 0; int noclobber = 0; /* for use with pipe */ int ipc = 0; int ipc_err = 0; int pipefd[2]; char **pipeargs = calloc(5, sizeof(char*)); uid = getuid(); password_entry = getpwuid(uid); /* get passwd info */ homedir = getenv("HOME"); /* get homedir */ if ( (pwd = getcwd(NULL, PATH_MAX+1)) == NULL ) { perror("getcwd"); exit(2); } owd = calloc(strlen(pwd) + 1, sizeof(char)); memcpy(owd, pwd, strlen(pwd)); prompt[0] = ' '; prompt[1] = '\0'; /* Put PATH into a linked list */ pathlist = get_path(); /* By default, we have no history or aliases or users */ history = NULL; aliases = NULL; userargs = NULL; while ( go ) { /* wait on background processes */ bg_pid = waitpid(-1, &status, WNOHANG); if(bg_pid > 0) { printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status)); } /* print prompt */ printf("\n"); printf(prompt); printf(" ["); printf(pwd); printf("]> "); i = 0; /* get command line and process */ while (fgets(commandline, MAX_CANON, stdin) != NULL) { /* wait on background processes */ bg_pid = waitpid(-1, &status, WNOHANG); if(bg_pid > 0) { printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status)); } if (commandline[strlen(commandline) - 1] == '\n') { commandline[strlen(commandline) - 1] = 0; } /* Add the command to history */ history = add_last(history, commandline); /* Get the command */ command = strtok_r(commandline, sp, &command_save); if(command == NULL) { break; } /* Search for aliases */ a = 0; struct aliaselement *alias = aliases; while(alias != NULL) { if(strcmp(command, alias->name) == 0) { a = 1; break; } alias = alias->next; } /* If we have an alias */ i = 0; if(a) { /* parse alias command */ arg = calloc(strlen(alias->command) + 1, sizeof(char)); strcpy(arg, alias->command); aliashelp = strtok_r(arg, sp, &alias_save); while(aliashelp != NULL) { if(i == MAXARGS) { strcpy(args[0], "maxargs"); break; } args[i] = calloc(strlen(aliashelp) + 1, sizeof(char)); strcpy(args[i], aliashelp); aliashelp = strtok_r(NULL, sp, &alias_save); i++; } command = strtok_r(NULL, sp, &command_save); free(arg); } /* parse command line or remainder of command line if we have an alias */ while (command != NULL) { if(i == MAXARGS) { strcpy(args[0], "maxargs"); break; } args[i] = calloc(strlen(command) + 1, sizeof(char)); strcpy(args[i], command); command = strtok_r(NULL, sp, &command_save); i++; } /* SANITY CHECK: make sure the user passed in something */ if(args[0] == NULL) { break; } /* Expand wildcard characters */ glob(args[0], GLOB_NOCHECK, NULL, &globbuf); i = 1; while(args[i] != NULL) { glob(args[i], GLOB_APPEND | GLOB_NOCHECK, NULL, &globbuf); i++; } /* gl becomes our arguments, it is the expanded version of args */ gl = globbuf.gl_pathv; /* glc is the number of arguments. Use it for checking built in commands */ glc = globbuf.gl_pathc; /* Check for background & at end of last argument */ char* last_arg = gl[glc - 1]; char last_char = last_arg[(strlen(last_arg) - 1)]; if(strcmp(&last_char, "&") == 0) { last_arg[(strlen(last_arg) - 1)] = '\0'; background = 1; } /* Check for file output redirection (without appending) */ if(glc > 2 && (strcmp(gl[glc-2], ">") == 0 || strcmp(gl[glc-2], ">&") == 0)) { /* Don't overwrite an existing file if noclobber is set */ if(noclobber) { if(access(gl[glc-1], F_OK) == 0) { fprintf(stderr, "%s: File exists.\n", gl[glc-1]); free_args(args); break; } } /* Redirect the output to given file */ fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP); if(fid == -1) { perror(gl[glc-1]); free_args(args); break; } close(1); dup(fid); /* Redirect error output to the given file */ if(strcmp(gl[glc-2], ">&") == 0) { close(2); dup(fid); error_redirect = 1; } close(fid); file_redirect = 1; /* Hide redirection character and filename */ gl[glc-2] = '\0'; gl[glc-1] = '\0'; glc = glc - 2; } /* Check for file output redirection (with appending) */ if(glc > 2 && (strcmp(gl[glc-2], ">>") == 0 || strcmp(gl[glc-2], ">>&") == 0)) { /* Don't append to a file that doesn't exist */ if(noclobber) { if(access(gl[glc-1], F_OK) != 0) { fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]); free_args(args); break; } } /* Redirect the output to given file */ fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP); if(fid == -1) { perror(gl[glc-1]); free_args(args); break; } close(1); dup(fid); /* Redirect error output to the given file */ if(strcmp(gl[glc-2], ">>&") == 0) { close(2); dup(fid); error_redirect = 1; } close(fid); file_redirect = 1; /* Hide redirection character and filename */ gl[glc-2] = '\0'; gl[glc-1] = '\0'; glc = glc - 2; } /* Check for file input redirection */ if(glc > 2 && strcmp(gl[glc-2], "<") == 0) { /* Can't take input from a nonexisistent file */ if(access(gl[glc-1], F_OK) != 0) { fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]); free_args(args); break; } /* Open the file to read from */ fid = open(gl[glc-1], O_RDONLY); if(fid == -1) { perror(gl[glc-1]); free_args(args); break; } close(0); dup(fid); close(fid); input_redirect = 1; /* Hide redirection character and filename */ gl[glc-2] = '\0'; gl[glc-1] = '\0'; glc = glc - 2; } /* Check for inter-process communication */ if(glc > 2 && (strcmp(gl[1], "|") == 0 || strcmp(gl[1], "|&") == 0)) { ipc = 1; if(strcmp(gl[1], "|&") == 0) { ipc_err = 1; } /* Create our pipe */ if(pipe(pipefd) == -1) { perror("pipe"); free_args(args); break; } /* Put the command to the right of the pipe in a second arguments list */ i = 2; int p = 0; while(gl[i] != NULL) { pipeargs[p] = malloc(strlen(gl[i]) + 1 * sizeof(char)); pipeargs[p] = gl[i]; i++; p++; } gl[1] = '\0'; glc = 1; } /* check for each built in command and implement */ /* Built in warnload */ if(strcmp(gl[0], "warnload") == 0) { printf("Executing built-in [%s]\n", gl[0]); char *end; if(glc != 2) { printf("Usage: warnload LOAD\n"); } else if (strcmp(gl[1], "0.0") != 0 && (strtof(gl[1], &end) == 0 || strtof(gl[1], &end) < 0)) { printf("LOAD must be a positive floating point number\n"); } else if (strcmp(gl[1], "0.0") == 0) { load = 0.0; load_thread = 1; } else { load = strtof(gl[1], &end); if(load_thread != 0) { load_thread = 0; pthread_create(&pt_warnload, NULL, warnload, &load); } } } /* Built in watchuser */ else if(strcmp(gl[0], "watchuser") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { fprintf(stderr, "watchuser: Too few arguements.\n"); } else if(glc > 3) { fprintf(stderr, "watchuser: Too many arguments.\n"); } else if (glc == 3 && strcmp(gl[2], "off") != 0) { printf("Usage: watchuser USERNAME [off]\n"); } else if (glc == 3 && strcmp(gl[2], "off") == 0 ){ /* remove the given username from watched users list */ if(user_thread == 0) { pthread_mutex_lock(&user_lock); userargs->users = remove_user(userargs->users, gl[1]); pthread_mutex_unlock(&user_lock); } else { printf("No watched users have been added yet\n"); } } else { /* Add the user to the list. Create the watchuser thread if it isn't already created */ if(user_thread == 1) { user_thread = 0; userargs = calloc(1, sizeof(struct userarg)); userargs->lock = user_lock; userargs->users = add_user(NULL, gl[1]); pthread_create(&pt_watchuser, NULL, watchuser, userargs); } else { pthread_mutex_lock(&user_lock); userargs->users = add_user(userargs->users, gl[1]); pthread_mutex_unlock(&user_lock); } } } /* WATCHMAIL NOT IMPLEMENTED */ else if(strcmp(gl[0], "watchmail") == 0) { printf("We were not able to implement watchmail as we could not figure out\nhow to correctly use pthread_cancel(3) to cancel threads\n"); } /* Build in fg */ else if(strcmp(gl[0], "fg") == 0) { printf("Executing build-in [%s]\n", gl[0]); /* No arguments, bring a default process into foreground */ if(glc == 1) { kill(0, SIGCONT); wait(NULL); } /* One argument, bring the process with pid into foreground */ else if(glc == 2) { if(atoi(gl[1])) { kill(atoi(gl[1]), SIGCONT); waitpid(atoi(gl[1]), NULL, 0); } else { fprintf(stderr, "pid must be an integer\n"); } } else { fprintf(stderr, "Usage: fg [pid]\n"); } } /* Built in list */ else if(strcmp(gl[0], "list") == 0) { printf("Executing built-in [%s]\n", gl[0]); i = 1; /* No arguments, print the current working directory */ if(glc < 2) { list(pwd); } else { /* list each of the arguments passed in */ while(i < glc) { list(gl[i]); printf("\n"); i++; } } } /* Built in exit */ else if (strcmp(gl[0], "exit") == 0) { printf("Executing built-in [%s]\n", gl[0]); go = 0; break; } /* Built in prompt */ else if (strcmp(gl[0], "prompt") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { /* user didn't enter a prompt so request one */ printf("input prompt prefix:"); fgets(prompt, PROMPTMAX, stdin); if(prompt[strlen(prompt) - 1] == '\n') { prompt[strlen(prompt) - 1] = 0; } } else { /* set the prompt to be the first argument */ strncpy(prompt, gl[1], PROMPTMAX); } } /* Built in pwd */ else if (strcmp(gl[0], "pwd") == 0) { printf("Executing built-in [%s]\n", gl[0]); printf(pwd); printf("\n"); } /* Built in noclobber */ else if (strcmp(gl[0], "noclobber") == 0){ if(noclobber == 0) { noclobber = 1; } else { noclobber = 0; } printf("noclobber is set to %d\n", noclobber); } /* Built in pid */ else if (strcmp(gl[0], "pid") == 0) { printf("Executing built-in [%s]\n", gl[0]); printf("%d\n", getpid()); } /* Built in which */ else if (strcmp(gl[0], "which") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { fprintf(stderr, "which: Too few arguments.\n"); } else { i = 1; while(i < glc) { char *wh; /* call the which function which will check for the command in the path */ wh = which(gl[i], pathlist); if(wh == NULL) { fprintf(stderr, "%s: Command not found.\n", gl[i]); } else { printf("%s\n", wh); } free(wh); i++; } } } /* Built in where */ else if (strcmp(gl[0], "where") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { fprintf(stderr, "where: Too few arguments.\n"); } else { i = 1; while(i < glc) { where(gl[i], pathlist); i++; } } } /* Built in cd */ else if (strcmp(gl[0], "cd") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc > 2) { printf("cd: Too many arguments.\n"); } else { char *tmp; /* tmp will be the new directory or NULL on failure */ tmp = cd(gl[1], homedir, owd); if(tmp == NULL) { break; } else { free(owd); /* set owd to be the old (previous) working directory */ owd = pwd; /* set the new working directory */ pwd = tmp; } tmp = NULL; } } /* Built in printenv */ else if (strcmp(gl[0], "printenv") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc > 2) { fprintf(stderr, "%s: Too many arguments.\n", gl[0]); } else if (glc > 1) { /* print a particular environmental variable */ char *tmp; tmp = getenv(gl[1]); if(tmp == NULL) { fprintf(stderr, "%s: Environmental variable not found.\n", gl[1]); } else { printf("%s\n", tmp); } tmp = NULL; } else { /* print all environmental variables */ i = 0; while(environ[i] != NULL) { printf("%s\n", environ[i]); i++; } } } /* Built in setenv */ else if (strcmp(gl[0], "setenv") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc > 3) { fprintf(stderr, "%s: Too many arguments.\n", gl[0]); } else if (glc > 2) { /* set an environmental variable to the given value */ setenv(gl[1], gl[2], 1); } else if (glc > 1) { /* set an environmental variable to an empty value */ setenv(gl[1], "", 1); } else { /* print all environmental variables */ i = 0; while(environ[i] != NULL) { printf("%s\n", environ[i]); i++; } } /* in case we update the home directory */ homedir = getenv("HOME"); } /* Built in history */ else if (strcmp(gl[0], "history") == 0) { printf("Executing built-in [%s]\n", gl[0]); int n = 10; /* set how many history records to print */ if(glc > 1 && atoi(gl[1]) != 0) { n = atoi(gl[1]); } struct pathelement *curr = history; /* loop and print past commands */ while(curr != NULL && n > 0) { printf("%s\n", curr->element); curr = curr->next; n--; } } /* Built in alias */ else if (strcmp(gl[0], "alias") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { /* list all aliases */ struct aliaselement *curr = aliases; while(curr != NULL) { printf("%s %s\n", curr->name, curr->command); curr = curr->next; } } else if(glc < 3) { /* list a specific alias */ struct aliaselement *curr = aliases; while(curr != NULL) { if(strcmp(gl[1], curr->name) == 0) { printf("%s\n", curr->command); } curr = curr->next; } } else { /* add an alias */ char buf[MAX_CANON]; snprintf(buf, MAX_CANON, "%s", gl[2]); i = 3; while(gl[i] != NULL && i < MAXARGS) { strcat(buf, " "); strcat(buf, gl[i]); i++; } aliases = add_alias(aliases, gl[1], buf); } } /* Built in kill */ else if (strcmp(gl[0], "kill") == 0) { printf("Executing built-in [%s]\n", gl[0]); if(glc < 2) { fprintf(stderr, "kill: Too few arguments.\n"); } else if(glc < 3 || strchr(gl[1], '-') == NULL) { /* default kill with SIGINT */ i = 1; while(gl[i] != NULL) { kill_process(gl[i]); i++; } } else { /* kill with the given signal number */ char *signal; signal = strtok(gl[1], "-"); i = 2; while(gl[i] != NULL) { kill_process_signal(gl[i], signal); i++; } } } /* MAXARGS handler */ else if (strcmp(gl[0], "maxargs") == 0) { fprintf(stderr, "Error: Too many arguments.\n"); } /* Absolute/Relative paths */ else if (strncmp(gl[0], "/", 1) == 0 || strncmp(gl[0], "./", 2) == 0 || strncmp(gl[0], "../", 3) == 0) { if(access(gl[0], X_OK) == 0) { pid_t pid = fork(); if(pid == -1) { perror("fork"); } else if(pid == 0) { /* print what child is executing and execve it */ printf("Executing [%s]\n", gl[0]); /* If we are piping this is the command on the left, set standard output to the pipe output */ if(ipc) { close(1); dup(pipefd[1]); if(ipc_err) { close(2); dup(pipefd[1]); } close(pipefd[0]); close(pipefd[1]); } execve(gl[0], gl, environ); /* on exec error */ perror(gl[0]); exit(127); } else { /* if not a background process, wait */ if(!background) { /* If we are piping this is the command on the right. Wait for the first command to finish */ if(ipc) { waitpid(pid, &status, 0); pid_t pid2 = fork(); if(pid2 == -1) { perror("fork"); } else if (pid2 == 0) { /* Set stdin to be the pipe input */ close(0); dup(pipefd[0]); close(pipefd[1]); close(pipefd[0]); /* Which command should we run */ char* wh; wh = which(pipeargs[0], pathlist); if(wh == NULL) { fprintf(stderr, "%s: Command not found", pipeargs[0]); } else { execve(wh, pipeargs, environ); } } else { close(pipefd[0]); close(pipefd[1]); } } else { /* wait for chil process */ waitpid(pid, &status, 0); /* if child exits with non-zero status print it */ if(WEXITSTATUS(status) != 0) { printf("Exit: %d\n", WEXITSTATUS(status)); } } } } } else { /* path doens't exist */ fprintf(stderr,"%s: Command not found.\n", gl[0]); } } /* Executable */ else { char* wh; char* wh2; /* figure out which executable to execute */ wh = which(gl[0], pathlist); if(wh == NULL) { fprintf(stderr, "%s: Command not found.\n", gl[0]); } else { pid_t pid = fork(); if(pid == -1) { perror("fork"); } else if (pid == 0) { /* what we are executing */ printf("Executing [%s]\n", wh); /* If we are piping this is the command on the left, set standard output to be the pipe output*/ if(ipc) { close(1); dup(pipefd[1]); if(ipc_err) { close(2); dup(pipefd[1]); } close(pipefd[0]); close(pipefd[1]); } execve(wh, gl, environ); /* on execve error */ perror(wh); exit(127); } else { /* if not a background process, wait */ if(!background) { /* If we are piping this is the command on the right, wait for command on left to finish */ if(ipc) { waitpid(pid, &status, 0); pid_t pid2 = fork(); if(pid2 == -1) { perror("fork"); } else if (pid2 == 0) { /* Set standard input to be pipe input */ close(0); dup(pipefd[0]); close(pipefd[1]); close(pipefd[0]); /* Which command should we run */ wh2 = which(pipeargs[0], pathlist); if(wh2 == NULL) { fprintf(stderr, "%s: Command not found", pipeargs[0]); } else { execve(wh2, pipeargs, environ); } } else { close(pipefd[0]); close(pipefd[1]); } } else { /* wait for child */ waitpid(pid, &status, 0); /* if child exits with nonzero value print it */ if(WEXITSTATUS(status) != 0){ printf("Exit: %d\n", WEXITSTATUS(status)); } } } } free(wh); } } /* reset background */ background = 0; /* reset glob */ globfree(&globbuf); /* reset args */ free_args(args); free_args(pipeargs); /* if we redirected file output, reset it to the screen */ if(file_redirect == 1) { file_redirect = 0; fid = open("/dev/tty", O_WRONLY); close(1); dup(fid); if(error_redirect == 1) { error_redirect = 0; close(2); dup(fid); } close(fid); } /* if we redirected file input, reset it to the keyboard */ if(input_redirect == 1) { input_redirect = 0; fid = open("/dev/tty", O_RDONLY); close(0); dup(fid); close(fid); } ipc = 0; ipc_err = 0; sleep(1); /* Print prompt again */ printf(prompt); printf(" ["); printf(pwd); printf("]> "); } } /* free allocated memory */ free(prompt); free(commandline); free_args(args); free_args(pipeargs); free(args); free(pipeargs); free(owd); free(pwd); struct pathelement *tmp; while(pathlist != NULL) { tmp = pathlist->next; free(pathlist); pathlist = tmp; } while(history != NULL) { tmp = history->next; free(history->element); free(history); history = tmp; } struct aliaselement *temp; while(aliases != NULL) { temp = aliases->next; free(aliases->name); free(aliases->command); free(aliases); aliases = temp; } struct userelement *tem; while(userargs != NULL && userargs->users != NULL) { tem = userargs->users->next; free(userargs->users->username); free(userargs->users); userargs->users = tem; } if(userargs != NULL) { pthread_mutex_destroy(&userargs->lock); free(userargs); } globfree(&globbuf); return 0; } /* sh() */
int main(int argc, char **argv) { int i; sigset_t set; #if ENABLE_MPEGTS uint32_t adapter_mask = 0; #endif int log_level = LOG_INFO; int log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG; const char *log_debug = NULL, *log_trace = NULL; gid_t gid = -1; uid_t uid = -1; char buf[512]; FILE *pidfile = NULL; extern int dvb_bouquets_parse; main_tid = pthread_self(); /* Setup global mutexes */ pthread_mutex_init(&fork_lock, NULL); pthread_mutex_init(&global_lock, NULL); pthread_mutex_init(&tasklet_lock, NULL); pthread_mutex_init(&atomic_lock, NULL); pthread_cond_init(>imer_cond, NULL); pthread_cond_init(&tasklet_cond, NULL); TAILQ_INIT(&tasklets); /* Defaults */ tvheadend_webui_port = 9981; tvheadend_webroot = NULL; tvheadend_htsp_port = 9982; tvheadend_htsp_port_extra = 0; time(&dispatch_clock); /* Command line options */ int opt_help = 0, opt_version = 0, opt_fork = 0, opt_firstrun = 0, opt_stderr = 0, opt_syslog = 0, opt_nosyslog = 0, opt_uidebug = 0, opt_abort = 0, opt_noacl = 0, opt_fileline = 0, opt_threadid = 0, opt_libav = 0, opt_ipv6 = 0, opt_satip_rtsp = 0, #if ENABLE_TSFILE opt_tsfile_tuner = 0, #endif opt_dump = 0, opt_xspf = 0, opt_dbus = 0, opt_dbus_session = 0, opt_nobackup = 0, opt_nobat = 0; const char *opt_config = NULL, *opt_user = NULL, *opt_group = NULL, *opt_logpath = NULL, *opt_log_debug = NULL, *opt_log_trace = NULL, *opt_pidpath = "/var/run/tvheadend.pid", #if ENABLE_LINUXDVB *opt_dvb_adapters = NULL, #endif *opt_bindaddr = NULL, *opt_subscribe = NULL, *opt_user_agent = NULL; str_list_t opt_satip_xml = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; str_list_t opt_tsfile = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; cmdline_opt_t cmdline_opts[] = { { 0, NULL, N_("Generic Options"), OPT_BOOL, NULL }, { 'h', "help", N_("Show this page"), OPT_BOOL, &opt_help }, { 'v', "version", N_("Show version information"),OPT_BOOL, &opt_version }, { 0, NULL, N_("Service Configuration"), OPT_BOOL, NULL }, { 'c', "config", N_("Alternate config path"), OPT_STR, &opt_config }, { 'B', "nobackup", N_("Don't backup config tree at upgrade"), OPT_BOOL, &opt_nobackup }, { 'f', "fork", N_("Fork and run as daemon"), OPT_BOOL, &opt_fork }, { 'u', "user", N_("Run as user"), OPT_STR, &opt_user }, { 'g', "group", N_("Run as group"), OPT_STR, &opt_group }, { 'p', "pid", N_("Alternate pid path"), OPT_STR, &opt_pidpath }, { 'C', "firstrun", N_("If no user account exists then create one with\n" "no username and no password. Use with care as\n" "it will allow world-wide administrative access\n" "to your Tvheadend installation until you edit/create\n" "access-control from within the Tvheadend UI"), OPT_BOOL, &opt_firstrun }, #if ENABLE_DBUS_1 { 'U', "dbus", N_("Enable DBus"), OPT_BOOL, &opt_dbus }, { 'e', "dbus_session", N_("DBus - use the session message bus instead system one"), OPT_BOOL, &opt_dbus_session }, #endif #if ENABLE_LINUXDVB { 'a', "adapters", N_("Only use specified DVB adapters (comma separated)"), OPT_STR, &opt_dvb_adapters }, #endif #if ENABLE_SATIP_SERVER { 0, "satip_rtsp", N_("SAT>IP RTSP port number for server\n" "(default: -1 = disable, 0 = webconfig, standard port is 554)"), OPT_INT, &opt_satip_rtsp }, #endif #if ENABLE_SATIP_CLIENT { 0, "satip_xml", N_("URL with the SAT>IP server XML location"), OPT_STR_LIST, &opt_satip_xml }, #endif { 0, NULL, N_("Server Connectivity"), OPT_BOOL, NULL }, { '6', "ipv6", N_("Listen on IPv6"), OPT_BOOL, &opt_ipv6 }, { 'b', "bindaddr", N_("Specify bind address"), OPT_STR, &opt_bindaddr}, { 0, "http_port", N_("Specify alternative http port"), OPT_INT, &tvheadend_webui_port }, { 0, "http_root", N_("Specify alternative http webroot"), OPT_STR, &tvheadend_webroot }, { 0, "htsp_port", N_("Specify alternative htsp port"), OPT_INT, &tvheadend_htsp_port }, { 0, "htsp_port2", N_("Specify extra htsp port"), OPT_INT, &tvheadend_htsp_port_extra }, { 0, "useragent", N_("Specify User-Agent header for the http client"), OPT_STR, &opt_user_agent }, { 0, "xspf", N_("Use XSPF playlist instead of M3U"), OPT_BOOL, &opt_xspf }, { 0, NULL, N_("Debug Options"), OPT_BOOL, NULL }, { 'd', "stderr", N_("Enable debug on stderr"), OPT_BOOL, &opt_stderr }, { 's', "syslog", N_("Enable debug to syslog"), OPT_BOOL, &opt_syslog }, { 'S', "nosyslog", N_("Disable syslog (all msgs)"), OPT_BOOL, &opt_nosyslog }, { 'l', "logfile", N_("Enable debug to file"), OPT_STR, &opt_logpath }, { 0, "debug", N_("Enable debug subsystems"), OPT_STR, &opt_log_debug }, #if ENABLE_TRACE { 0, "trace", N_("Enable trace subsystems"), OPT_STR, &opt_log_trace }, #endif { 0, "fileline", N_("Add file and line numbers to debug"), OPT_BOOL, &opt_fileline }, { 0, "threadid", N_("Add the thread ID to debug"), OPT_BOOL, &opt_threadid }, #if ENABLE_LIBAV { 0, "libav", N_("More verbose libav log"), OPT_BOOL, &opt_libav }, #endif { 0, "uidebug", N_("Enable webUI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug }, { 'A', "abort", N_("Immediately abort"), OPT_BOOL, &opt_abort }, { 'D', "dump", N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump }, { 0, "noacl", N_("Disable all access control checks"), OPT_BOOL, &opt_noacl }, { 0, "nobat", N_("Disable DVB bouquets"), OPT_BOOL, &opt_nobat }, { 'j', "join", N_("Subscribe to a service permanently"), OPT_STR, &opt_subscribe }, #if ENABLE_TSFILE || ENABLE_TSDEBUG { 0, NULL, N_("Testing options"), OPT_BOOL, NULL }, { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner }, { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile }, #endif #if ENABLE_TSDEBUG { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug }, #endif }; /* Get current directory */ tvheadend_cwd0 = dirname(tvh_strdupa(argv[0])); tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0)); /* Set locale */ setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); tvh_gettext_init(); /* make sure the timezone is set */ tzset(); /* Process command line */ for (i = 1; i < argc; i++) { /* Find option */ cmdline_opt_t *opt = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]); if (!opt) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), _("invalid option specified [%s]"), argv[i]); /* Process */ if (opt->type == OPT_BOOL) *((int*)opt->param) = 1; else if (++i == argc) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), _("option %s requires a value"), opt->lopt); else if (opt->type == OPT_INT) *((int*)opt->param) = atoi(argv[i]); else if (opt->type == OPT_STR_LIST) { str_list_t *strl = opt->param; if (strl->num < strl->max) strl->str[strl->num++] = argv[i]; } else *((char**)opt->param) = argv[i]; /* Stop processing */ if (opt_help) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL); if (opt_version) show_version(argv[0]); } /* Additional cmdline processing */ if (opt_nobat) dvb_bouquets_parse = 0; #if ENABLE_LINUXDVB if (!opt_dvb_adapters) { adapter_mask = ~0; } else { char *p, *e; char *r = NULL; char *dvb_adapters = strdup(opt_dvb_adapters); adapter_mask = 0x0; p = strtok_r(dvb_adapters, ",", &r); while (p) { int a = strtol(p, &e, 10); if (*e != 0 || a < 0 || a > 31) { fprintf(stderr, _("Invalid adapter number '%s'\n"), p); free(dvb_adapters); return 1; } adapter_mask |= (1 << a); p = strtok_r(NULL, ",", &r); } free(dvb_adapters); if (!adapter_mask) { fprintf(stderr, "%s", _("No adapters specified!\n")); return 1; } } #endif if (tvheadend_webroot) { char *tmp; if (*tvheadend_webroot == '/') tmp = strdup(tvheadend_webroot); else { tmp = malloc(strlen(tvheadend_webroot)+2); *tmp = '/'; strcpy(tmp+1, tvheadend_webroot); } if (tmp[strlen(tmp)-1] == '/') tmp[strlen(tmp)-1] = '\0'; tvheadend_webroot = tmp; } tvheadend_webui_debug = opt_uidebug; /* Setup logging */ if (isatty(2)) log_options |= TVHLOG_OPT_DECORATE; if (opt_stderr || opt_syslog || opt_logpath) { if (!opt_log_trace && !opt_log_debug) log_debug = "all"; log_level = LOG_DEBUG; if (opt_stderr) log_options |= TVHLOG_OPT_DBG_STDERR; if (opt_syslog) log_options |= TVHLOG_OPT_DBG_SYSLOG; if (opt_logpath) log_options |= TVHLOG_OPT_DBG_FILE; } if (opt_nosyslog) log_options &= ~(TVHLOG_OPT_SYSLOG|TVHLOG_OPT_DBG_SYSLOG); if (opt_fileline) log_options |= TVHLOG_OPT_FILELINE; if (opt_threadid) log_options |= TVHLOG_OPT_THREAD; if (opt_libav) log_options |= TVHLOG_OPT_LIBAV; if (opt_log_trace) { log_level = LOG_TRACE; log_trace = opt_log_trace; } if (opt_log_debug) log_debug = opt_log_debug; tvhlog_init(log_level, log_options, opt_logpath); tvhlog_set_debug(log_debug); tvhlog_set_trace(log_trace); tvhinfo("main", "Log started"); signal(SIGPIPE, handle_sigpipe); // will be redundant later signal(SIGILL, handle_sigill); // see handler.. /* Set priviledges */ if(opt_fork || opt_group || opt_user) { const char *homedir; struct group *grp = getgrnam(opt_group ?: "video"); struct passwd *pw = opt_user ? getpwnam(opt_user) : NULL; if(grp != NULL) { gid = grp->gr_gid; } else { gid = 1; } if (pw != NULL) { if (getuid() != pw->pw_uid) { gid_t glist[16]; int gnum; gnum = get_user_groups(pw, glist, ARRAY_SIZE(glist)); if (gnum > 0 && setgroups(gnum, glist)) { char buf[256] = ""; int i; for (i = 0; i < gnum; i++) snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf), ",%d", glist[i]); tvhlog(LOG_ALERT, "START", "setgroups(%s) failed, do you have permission?", buf+1); return 1; } } uid = pw->pw_uid; homedir = pw->pw_dir; setenv("HOME", homedir, 1); } else { uid = 1; } } uuid_init(); config_boot(opt_config, gid, uid); tcp_server_preinit(opt_ipv6); http_server_init(opt_bindaddr); // bind to ports only htsp_init(opt_bindaddr); // bind to ports only satip_server_init(opt_satip_rtsp); // bind to ports only if (opt_fork) pidfile = tvh_fopen(opt_pidpath, "w+"); if (gid != -1 && (getgid() != gid) && setgid(gid)) { tvhlog(LOG_ALERT, "START", "setgid(%d) failed, do you have permission?", gid); return 1; } if (uid != -1 && (getuid() != uid) && setuid(uid)) { tvhlog(LOG_ALERT, "START", "setuid(%d) failed, do you have permission?", uid); return 1; } /* Daemonise */ if(opt_fork) { if(daemon(0, 0)) { exit(2); } if(pidfile != NULL) { fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } /* Make dumpable */ if (opt_dump) { #ifdef PLATFORM_LINUX if (chdir("/tmp")) tvhwarn("START", "failed to change cwd to /tmp"); prctl(PR_SET_DUMPABLE, 1); #else tvhwarn("START", "Coredumps not implemented on your platform"); #endif } umask(0); } tvheadend_running = 1; /* Start log thread (must be done post fork) */ tvhlog_start(); /* Alter logging */ if (opt_fork) tvhlog_options &= ~TVHLOG_OPT_STDERR; if (!isatty(2)) tvhlog_options &= ~TVHLOG_OPT_DECORATE; /* Initialise clock */ pthread_mutex_lock(&global_lock); time(&dispatch_clock); /* Signal handling */ sigfillset(&set); sigprocmask(SIG_BLOCK, &set, NULL); trap_init(argv[0]); /* SSL library init */ OPENSSL_config(NULL); SSL_load_error_strings(); SSL_library_init(); /* Initialise configuration */ notify_init(); idnode_init(); spawn_init(); config_init(opt_nobackup == 0); /** * Initialize subsystems */ epg_in_load = 1; tvhthread_create(&tasklet_tid, NULL, tasklet_thread, NULL); dbus_server_init(opt_dbus, opt_dbus_session); intlconv_init(); api_init(); fsmonitor_init(); libav_init(); tvhtime_init(); profile_init(); imagecache_init(); http_client_init(opt_user_agent); esfilter_init(); bouquet_init(); service_init(); dvb_init(); #if ENABLE_MPEGTS mpegts_init(adapter_mask, &opt_satip_xml, &opt_tsfile, opt_tsfile_tuner); #endif channel_init(); bouquet_service_resolve(); subscription_init(); dvr_config_init(); access_init(opt_firstrun, opt_noacl); #if ENABLE_TIMESHIFT timeshift_init(); #endif tcp_server_init(); webui_init(opt_xspf); #if ENABLE_UPNP upnp_server_init(opt_bindaddr); #endif service_mapper_init(); descrambler_init(); epggrab_init(); epg_init(); dvr_init(); dbus_server_start(); http_server_register(); satip_server_register(); htsp_register(); if(opt_subscribe != NULL) subscription_dummy_join(opt_subscribe, 1); avahi_init(); bonjour_init(); epg_updated(); // cleanup now all prev ref's should have been created epg_in_load = 0; pthread_mutex_unlock(&global_lock); /** * Wait for SIGTERM / SIGINT, but only in this thread */ sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGINT); signal(SIGTERM, doexit); signal(SIGINT, doexit); pthread_sigmask(SIG_UNBLOCK, &set, NULL); tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, " "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s", tvheadend_version, getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)), hts_settings_get_root()); if(opt_abort) abort(); mainloop(); #if ENABLE_DBUS_1 tvhftrace("main", dbus_server_done); #endif #if ENABLE_UPNP tvhftrace("main", upnp_server_done); #endif tvhftrace("main", satip_server_done); tvhftrace("main", htsp_done); tvhftrace("main", http_server_done); tvhftrace("main", webui_done); tvhftrace("main", fsmonitor_done); tvhftrace("main", http_client_done); tvhftrace("main", tcp_server_done); // Note: the locking is obviously a bit redundant, but without // we need to disable the gtimer_arm call in epg_save() pthread_mutex_lock(&global_lock); tvhftrace("main", epg_save); #if ENABLE_TIMESHIFT tvhftrace("main", timeshift_term); #endif pthread_mutex_unlock(&global_lock); tvhftrace("main", epggrab_done); #if ENABLE_MPEGTS tvhftrace("main", mpegts_done); #endif tvhftrace("main", descrambler_done); tvhftrace("main", service_mapper_done); tvhftrace("main", service_done); tvhftrace("main", channel_done); tvhftrace("main", bouquet_done); tvhftrace("main", dvr_done); tvhftrace("main", subscription_done); tvhftrace("main", access_done); tvhftrace("main", epg_done); tvhftrace("main", avahi_done); tvhftrace("main", bonjour_done); tvhftrace("main", imagecache_done); tvhftrace("main", lang_code_done); tvhftrace("main", api_done); tvhtrace("main", "tasklet enter"); pthread_cond_signal(&tasklet_cond); pthread_join(tasklet_tid, NULL); tvhtrace("main", "tasklet thread end"); tasklet_flush(); tvhtrace("main", "tasklet leave"); tvhftrace("main", hts_settings_done); tvhftrace("main", dvb_done); tvhftrace("main", lang_str_done); tvhftrace("main", esfilter_done); tvhftrace("main", profile_done); tvhftrace("main", intlconv_done); tvhftrace("main", urlparse_done); tvhftrace("main", idnode_done); tvhftrace("main", notify_done); tvhftrace("main", spawn_done); tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend"); tvhlog_end(); tvhftrace("main", config_done); if(opt_fork) unlink(opt_pidpath); #if ENABLE_TSFILE free(opt_tsfile.str); #endif free(opt_satip_xml.str); /* OpenSSL - welcome to the "cleanup" hell */ ENGINE_cleanup(); RAND_cleanup(); CRYPTO_cleanup_all_ex_data(); EVP_cleanup(); CONF_modules_free(); #ifndef OPENSSL_NO_COMP COMP_zlib_cleanup(); #endif ERR_remove_state(0); ERR_free_strings(); #ifndef OPENSSL_NO_COMP sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); #endif /* end of OpenSSL cleanup code */ #if ENABLE_DBUS_1 extern void dbus_shutdown(void); if (opt_dbus) dbus_shutdown(); #endif tvh_gettext_done(); return 0; } /** * */ void tvh_str_set(char **strp, const char *src) { free(*strp); *strp = src ? strdup(src) : NULL; } /** * */ int tvh_str_update(char **strp, const char *src) { if(src == NULL) return 0; free(*strp); *strp = strdup(src); return 1; } /** * */ void scopedunlock(pthread_mutex_t **mtxp) { pthread_mutex_unlock(*mtxp); }
sprawl::String sprawl::filesystem::GetCwd() { char cwd[PATH_MAX]; getcwd(cwd, PATH_MAX); return sprawl::String(cwd); }
static void path_error(const char* file_name){ char path[512]; getcwd(path, 512); printf("\"%s%s\" does not exist\n", path, file_name); }