Ejemplo n.º 1
1
bool doCmd(const char* path, enum CmdType cmd_type, enum FileType file_type, CacheStat* pStat){
    int  fd = 0;
    DIR  *dir = NULL;
    DIR  *soft_dir = NULL;
    struct dirent *dp = NULL;
    char file_name[256];
    char link_name[256];
    char real_path[256];

    void *pbase = NULL;
    char *vec = NULL;
    
    struct stat st;
    int in_cache = 0;
    int str_len  = 0;
    
    int page_index;
    int page_count;
    int pagesize = getpagesize();

    int time_used = 0;
    struct timeval begin, end;

    if(realpath(path, real_path) == NULL){
        goto ERROR;
    }

    if(file_type == REGFILE){
        fd = open(real_path, O_RDONLY);
        if(fd<0){
            goto ERROR;
        }

        if(stat(real_path, &st)<0){
            goto ERROR;
        }

        switch(cmd_type){
            case CLEAR:
                if(posix_fadvise(fd, 0, st.st_size, POSIX_FADV_DONTNEED) != 0){
                    goto ERROR;
                }
                fprintf(stdout, "Release:%s\n", real_path);
                break;
            case STAT:
                if(st.st_size == 0)
                    goto EMPTYFILE;

                pbase = mmap((void *)0, st.st_size, PROT_NONE, MAP_SHARED, fd, 0);
                if(pbase == MAP_FAILED){
                    goto ERROR;
                }

                page_count = (st.st_size+pagesize-1)/pagesize;
                vec = (char*)calloc(1, page_count);
                if(mincore(pbase, st.st_size, (unsigned char *)vec) != 0){
                    goto ERROR; 
                }

                for(page_index=0; page_index<page_count; page_index++){
                    if(vec[page_index]&1 != 0){
                        ++in_cache;
                    } 
                }

                pStat->page_count += page_count;
                pStat->in_cache   += in_cache;

EMPTYFILE:
                if(pStat->is_print == true){
                    fprintf(stdout, "Stat:%s size:%s cached:%s\n", 
                            real_path,
                            sizeFit(st.st_size, buf1),
                            sizeFit(in_cache*(pagesize), buf2));
                }
                break;
            case LOCK:
                if(st.st_size == 0){
                    fprintf(stderr, "Empty file %s\n", real_path);
                    return true;
                }

                pbase = mmap((void *)0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
                if(pbase == MAP_FAILED){
                    goto ERROR;
                }

                if(mlock(pbase, st.st_size) == 0){
                    fprintf(stdout, "Lock %s succeed, size:%s\n", real_path, sizeFit(st.st_size, buf1));
                    return true;
                }else{
                    goto ERROR;
                }
            case WARM:
                gettimeofday(&begin, NULL);
                if(posix_fadvise(fd, 0, st.st_size, POSIX_FADV_WILLNEED) != 0){
                    goto ERROR;
                }
                gettimeofday(&end, NULL);
                time_used = getUsedTime(&begin, &end);
                fprintf(stdout, "Warmup File:%s TimeUsed:%d ms\n", real_path, time_used);
                break;
            default:
                fprintf(stderr, "do not support cmd type %d\n", cmd_type);
                goto ERROR;
        }

        close(fd);
        if(vec)     free(vec);
        if(pbase)   munmap(pbase, st.st_size);
        return true;
    }else if(file_type == DIRECTORY){
        if((dir = opendir(real_path)) == NULL){
            goto ERROR;
        }

        gettimeofday(&begin, NULL);

        while((dp = readdir(dir)) != NULL){
            if(strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0){
                memset(file_name, 0, sizeof(file_name));
                strcat(file_name, real_path);
                strcat(file_name, "/");
                strcat(file_name, dp->d_name);
                if(dp->d_type == DT_REG){
                    doCmd(file_name, cmd_type, REGFILE,  pStat);
                }else if(dp->d_type == DT_DIR){
                    doCmd(file_name, cmd_type, DIRECTORY, pStat);
                }else if(dp->d_type == DT_LNK){
                    if(realpath(file_name, link_name) != NULL){
                        if(stat(link_name, &st)<0){
                            goto ERROR;
                        }

                        if(st.st_mode & S_IFREG){
                            doCmd(file_name, cmd_type, REGFILE,  pStat);
                        }else if(st.st_mode & S_IFDIR){
                            doCmd(file_name, cmd_type, DIRECTORY, pStat);
                        }
                    }
                }else{
                    fprintf(stdout, "%s:%c type unsupported!\n", dp->d_name, dp->d_type);
                }
            }
        }

        gettimeofday(&end, NULL);
        time_used = getUsedTime(&begin, &end);
        if(cmd_type == WARM){
            fprintf(stdout, "Warmup Dir:%s TimeUsed:%d ms\n", real_path, time_used);
        }

        closedir(dir);
        return true;
    }

ERROR:
    fprintf(stderr, "File:%s %s\n", real_path, strerror(errno));
    if(fd)      close(fd);
    if(dir)     closedir(dir);
    if(vec)     free(vec);
    if(pbase)   munmap(pbase, st.st_size);
    return false;
}
Ejemplo n.º 2
0
int realStat(const char *path, long interval, enum FileType file_type, bool is_suppress){
    CacheStat stat;
    int pre = 0;
    bool first = true;
    bool ret = false;

    memset(&stat, 0, sizeof(stat));
    fprintf(stdout, "file:%s\n", path);
    fprintf(stdout, "time\tpage_count\tin_cache\tchange\n");

    while(1){
        pre = stat.in_cache;
        memset(&stat, 0, sizeof(stat));
        ret = doCmd(path, STAT, file_type, &stat);

        if(pre==stat.in_cache && is_suppress && !first) continue;
        first = false;
        if(ret == false){
            fprintf(stderr, "real stat error %s\n", path);
            exit(0);
        }else{
            fprintf(stdout, "%s %d\t%d\t%d\n", 
               getTimeStr(), stat.page_count, stat.in_cache, stat.in_cache-pre);
        } 
        usleep(interval);
    }
}
Ejemplo n.º 3
0
/*
 *  ======== cleanup ========
 */
static Void cleanup(Void)
{
    static CmdObj dcmdInit = {NULL, NULL, NONE, NONE, NULL, NULL, NULL};

    if (curInit != FALSE) {
        curInit = FALSE;
        if (dcmd.dproc != NULL) {
            doCmd(EXIT, NULL);
            // Thread_join(dcmd.dproc);
            Thread_delete( dcmd.dproc ); /* will do join first? */
            dcmd.dproc = NULL;
        }

        if (dcmd.cmdPresent != NULL) {
            Sem_delete(dcmd.cmdPresent);
            dcmd.cmdPresent = NULL;
        }

        if (dcmd.replyPresent != NULL) {
            Sem_delete(dcmd.replyPresent);
            dcmd.replyPresent = NULL;
        }

        if (dcmd.gate != NULL) {
            Lock_delete(dcmd.gate);
            dcmd.gate = NULL;
        }

        dcmd = dcmdInit;
    }
}
Ejemplo n.º 4
0
void doCommand( const char* cmd, const char* param, ...) {
	va_list arg;
	string sarg;
	va_start(arg,param);
	sarg = string(va_arg(arg,const char*));
	va_end(arg);
	doCmd(cmd,sarg.c_str());
	printf("executing command %s with param %s\n",cmd,param);
}
Ejemplo n.º 5
0
bool GTPWrapper::islegal(bool first)
{
  stringstream ss;
  string s = getColoredCoord(first);
  //  cout << "s: \"" << s << "\""<<endl;
  ss << "is_legal " << s;
   
  string r = doCmd(ss.str());
  //    cout << "r: \"" << r << "\"" << endl;
  r = r.substr(r.find(" ")+1,r.length());
  r = r.substr(0,r.length());
  return atof(r.c_str());
}
/*
 *  ======== Processor_create ========
 */
Processor_Handle Processor_create(String imageName, String memMap,
    Processor_Attrs *attrs)
{
    Processor_Handle proc = NULL;
    struct stat statBuf;

    Assert_isTrue(curInit == TRUE, (Assert_Id)NULL);

    Log_print3(Diags_ENTRY, "[+E] Processor_create> "
            "Enter(imageName='%s', memMap='%s', attrs=0x%x)",
            (IArg)imageName, (IArg)memMap, (IArg)attrs);

    if (attrs == NULL) {
        attrs = &Processor_ATTRS;
    }

    if (stat(imageName, &statBuf) != 0) {
        Log_print1(Diags_USER7, "[+7] Processor_create> "
                "ERROR: cannot access file %s", (IArg)imageName);
        return (NULL);
    }

    proc = Memory_alloc(sizeof(Processor_Obj), NULL);
    if (proc == NULL) {
        Log_print0(Diags_USER7, "[+7] Processor_create> "
                "ERROR: Memory_alloc failed");
        return (NULL);
    }

    proc->attrs = *attrs;
    proc->imageName = imageName;
    proc->memMapName = memMap;
    proc->loaded = FALSE;
    proc->fileId = 0xffffffff;
    proc->heapH = NULL;
    proc->procMgrH = NULL;
    proc->heapId = Processor_INVALID;
    proc->loadCallBackStatus = -1;
    proc->startCallBackStatus = -1;
    proc->useExtLoader = attrs->useExtLoader;

    if (doCmd(CREATE, proc) != SUCCESS) {
        Processor_delete(proc);
        return (NULL);
    }
    proc->loaded = TRUE;

    Log_print1(Diags_EXIT, "[+X] Processor_create> return (0x%x)", (IArg)proc);

    return (proc);
}
Ejemplo n.º 7
0
int main(int argc, char *argv[]){
    if(argc<=2){
        usage(argv[0]);
        exit(-1);
    } 

    int pagesize = getpagesize();
    CmdParam cmd;
    CacheStat stat;
    memset(&stat, 0, sizeof(stat));
    memset(&cmd, 0, sizeof(cmd));
    stat.is_print = true; //default true
    parseArgs(argc, argv, &cmd);

    if(cmd.is_daemon)
        daemonMe();

    if(cmd.cmd_type == CLEAR){
        doCmd(cmd.path, cmd.cmd_type, cmd.file_type, NULL);
    }else if(cmd.cmd_type == STAT){
        doCmd(cmd.path, cmd.cmd_type, cmd.file_type, &stat);
        if(cmd.file_type == DIRECTORY){
            fprintf(stdout, "\nTotal Cache of Directory:%s size:%s cached:%s\n", 
                    cmd.path,
                    sizeFit(stat.page_count*pagesize, buf1), 
                    sizeFit(stat.in_cache*pagesize, buf2));
        }
    }else if(cmd.cmd_type == RSTAT){
        realStat(cmd.path, cmd.interval, cmd.file_type, cmd.is_suppress);
    }else if(cmd.cmd_type == LOCK){
        doCmd(cmd.path, cmd.cmd_type, cmd.file_type, NULL);
        select(0, NULL, NULL, NULL, NULL);
    }else if(cmd.cmd_type == WARM){
        doCmd(cmd.path, cmd.cmd_type, cmd.file_type, NULL);
    }

    return 0;
}
Ejemplo n.º 8
0
int main (int argc, char** argv) {
    errorFunnel(setState(argc, argv));
    if (hushState.isInteractive) {
        while(hushState.isRunning) {
              size_t linecap = 0, lineLen = 0;
              printf("%s", hushEnv.PS1);
              lineLen = getline(&(hushState.jobs[hushState.jobCount].cmdStr), &linecap, stdin);
              //remove trailing newline
              if (hushState.jobs[hushState.jobCount].cmdStr[lineLen - 1] == '\n') {
                  hushState.jobs[hushState.jobCount].cmdStr[lineLen - 1] = '\0';
              }
              errorFunnel(preprocessCmd(lineLen, hushState.jobs[hushState.jobCount].cmdStr));
              errorFunnel(doCmd(hushState.jobs[hushState.jobCount].handleInternally));
              errorFunnel(postprocessCmd());
              //The exit command will exit this loop.
        }
    }
    else { //hush is being run non-interactively with command specified with -n option.
        errorFunnel(preprocessCmd(strlen(hushState.jobs[hushState.jobCount].cmdStr), 
                    hushState.jobs[hushState.jobCount].cmdStr));
        doCmd(hushState.jobs[hushState.jobCount].handleInternally); 
    }
    return (hushState.hushErrno);
}
Ejemplo n.º 9
0
void GTPWrapper::genmove(bool first)
{
  
  if(moves==1&&bsize==5&&!first&&board[24]==0&&board[25]==1) {//kens trick
    if(doMove("white B3")) {board[22]=1;board[23]=0;
      //      board.at(11) = 1;//cout << "setting white at b3.."<<endl;
      moves++; return;} 
    else{//cout << "could not white at b3.."<<endl; 
      setPass(first); return;}
  }
  // to make gnugo play through a 5x5 match..
  string r = (first) ? doCmd("genmove black") : doCmd("genmove white");
  //int s = first+1;
  //  cout << "r: " << r << endl;

  if(r.find("?")!=string::npos)
    return;
  if(r.find("PASS")!=string::npos){
    //    string s = (first) ? "black" : "white";
    //cout << ((first) ? "black" : "white") << " passed board: "<< endl << getLocalBoardAscii();
    setPass(first);
    return;
  }
  moves++;
//   r = r.substr(r.find(" ")+1,r.length());
//   r = r.substr(0,r.length());
//   int x = getCol(r[0]); int y = atoi(r.substr(1,r.length()).c_str()); y--; x++;
//   //   cout << "white moved to" << endl;   cout << "x:"<<x<<" y:"<<y<<"   r: " << r << " s:" << s << " first:" << first <<  endl; 
//   //  cout << "setting board at: " << ((bsize-x)*bsize)+y << " to " << s<<endl;
//   board.at(((bsize-x)*bsize)+y)  = s;
  updateFromGnuGo();
  //  int fanda;
  //  cin >> fanda;
  //  cout << "board at: " << ((x-bsize)*bsize)+y << ": " << board.at((x*bsize)+y) <<endl;
  //  cout << getBoardAscii() << endl;
}
Ejemplo n.º 10
0
/*
 *  ======== Processor_create ========
 */
Processor_Handle Processor_create(String imageName, String linkCfg,
    Processor_Attrs *attrs)
{
    Processor_Handle proc = NULL;
    File_Stat statBuf;

    GT_assert(curTrace, curInit == TRUE);

    GT_3trace(curTrace, GT_ENTER, "Processor_create> "
        "Enter(imageName='%s', linkCfg='%s', attrs=0x%x)\n", imageName,
        linkCfg, attrs);

    if (attrs == NULL) {
        attrs = &Processor_ATTRS;
    }

    if ((!Global_useLinkArbiter) &&
            (File_stat(imageName, &statBuf) != File_EOK)) {
        GT_1trace(curTrace, GT_7CLASS, "Processor_create> "
            "ERROR: cannot access file %s\n", imageName);
        return (NULL);
    }

    if ((proc = Memory_alloc(sizeof(Processor_Obj), NULL)) == NULL) {
        GT_0trace(curTrace, GT_7CLASS, "Processor_create> "
            "ERROR: Memory_alloc failed\n");
        return (NULL);
    }

    proc->attrs = *attrs;
    proc->imageName = imageName;
    proc->linkConfigName = linkCfg;
    proc->loaded = FALSE;
    proc->powerHandle = NULL;
    proc->connected = FALSE;

    if (doCmd(CREATE, proc) != SUCCESS) {
        Processor_delete(proc);
        return (NULL);
    }
    proc->loaded = TRUE;

    GT_1trace(curTrace, GT_ENTER, "Processor_create> return (0x%x)\n", proc);

    return (proc);
}
Ejemplo n.º 11
0
/*
 *  ======== Processor_delete ========
 */
Void Processor_delete(Processor_Handle proc)
{
    GT_assert(curTrace, curInit == TRUE);

    GT_1trace(curTrace, GT_ENTER, "Processor_delete> Enter(proc=0x%x)\n", proc);

    if (proc != NULL) {
        if (proc->loaded == TRUE && dcmd.dproc != NULL) {
            doCmd(DELETE, proc);
        }

        GT_1trace(curTrace, GT_1CLASS,
            "Processor_delete(0x%x) freeing object ...\n", proc);
        Memory_free(proc, sizeof(Processor_Obj), NULL);
    }

    GT_0trace(curTrace, GT_ENTER, "Processor_delete> return.\n");
}
/*
 *  ======== Processor_delete ========
 */
Void Processor_delete(Processor_Handle proc)
{
    Assert_isTrue(curInit == TRUE, (Assert_Id)NULL);

    Log_print1(Diags_ENTRY, "[+E] Processor_delete> Enter(proc=0x%x)",
            (IArg)proc);

    if (proc != NULL) {
        if (proc->loaded == TRUE && dcmd.dproc != NULL) {
            doCmd(DELETE, proc);
        }

        Log_print1(Diags_USER1,
                "[+1] Processor_delete(0x%x) freeing object ...", (IArg)proc);
        Memory_free(proc, sizeof(Processor_Obj), NULL);
    }

    Log_print0(Diags_EXIT, "[+X] Processor_delete> return");
}
Ejemplo n.º 13
0
MStatus
cgfxShaderCmd::doIt( const MArgList& args )
{
	MStatus stat;
	try
	{
		stat = doCmd( args );
	}
	catch ( cgfxShaderCommon::InternalError* e )   
	{
		reportInternalError( __FILE__, (size_t)e );
		stat = MS::kFailure;
	}
	catch ( ... )
	{
		reportInternalError( __FILE__, __LINE__ );
		stat = MS::kFailure;
	}
	return stat;
}                                      // MStatus cgfxShaderCmd::doIt
/*
 *  ======== cleanup ========
 */
static Void cleanup(Void)
{
    static CmdObj dcmdInit = {NULL, NULL, NONE, NONE, NULL, NULL, NULL};

    if (curInit != FALSE) {
        curInit = FALSE;
        if (dcmd.dproc != NULL) {
            doCmd(EXIT, NULL);
            // Thread_join(dcmd.dproc);
            Thread_delete(&dcmd.dproc); /* will do join first? */
            dcmd.dproc = NULL;
        }

        Log_print0(Diags_USER2, "[+2] Processor cleanup()> "
                "SysLink_destroy()...");
        SysLink_destroy();
        Log_print0(Diags_USER2, "[+2] Processor cleanup()> "
                "... SysLink_destroy() complete");

        if (dcmd.cmdPresent != NULL) {
            SemThread_delete(&dcmd.cmdPresent);
            dcmd.cmdPresent = NULL;
        }

        if (dcmd.replyPresent != NULL) {
            SemThread_delete(&dcmd.replyPresent);
            dcmd.replyPresent = NULL;
        }

        if (dcmd.gate != NULL) {
            GateThread_delete(&dcmd.gate);
            dcmd.gate = NULL;
        }

        dcmd = dcmdInit;
    }
}
Ejemplo n.º 15
0
void AdminConnection::on_data()
{
    char buf[1026];
again:
    size_t sz = ec_->peekIn(buf, 1024);
    if (sz == 1024)
    {
        buf[1024] = '\n';
        buf[0] = 0;
    }
    else
    {
        buf[sz] = 0;
    }
    for (size_t i = 0; i != sz; ++i)
    {
        if (buf[i] == '\n')
        {
            ec_->consume(i + 1);
            doCmd(std::string(&buf[0], &buf[i]));
            goto again;
        }
    }
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
	bool isBTSDo = false;	// If set, execute one command without prompting, then exit.
	std::string sCommand("");
	progname = argv[0];
	argc--; argv++;			// Skip program name.
	while(argc > 0) {
		if (argv[0][0] == '-') {
			if (strlen(argv[0]) > 2) {
				oops("Invalid option '%s'\n", argv[0]);
				exit(1);
			}
			switch(argv[0][1]) {
				case 'd': // OpenBTSDo interface
					isBTSDo = true;
					break;
				case 'c': // Run command on command line then exit.
					isBTSDo = true;
					if (argc == 1) {
						oops("Missing argument to -c\n");
					}
					{
						// Gather up the command line.
						for (int j = 1; j < argc; j++) {
							sCommand += argv[j];
							sCommand += " ";
						}
					}
					argc = 1;	// terminates while loop.
					break;
				case 'p': // TCP Port number
					argc--, argv++;
					port = atoi(argv[0]);
					printf("TCP %d\n", port);
					break;
				case 't': // target
					argc--, argv++;
					snprintf(target, sizeof(target)-1, "%s", argv[0]);
					break;
				default:
					oops("Invalid option '%s'\n", argv[0]);
					exit(1);	// NOTREACHED but makes the compiler happy.
			}
			argc--;
			argv++;
		} else {
			oops("Invalid argument '%s'\n", argv[0]);
			exit(1);	// NOTREACHED but makes the compiler happy.
		}
	}

    // Note that this only works if we are communicating across localhost.
    // TODO: Fix this so we can push the file across the socket if done
    // remotely.
    // Don't do this if running the single line configuration methods, we
    // will assume running from an external script is mostly a testing
    // thing, not a deployment thing for an actual base station.

	if (sCommand.c_str()[0] == '\0') {
		banner();
		printf("Connecting to %s:%d...\n", target, port);
	}

	int sock = -1;
	char prompt[16] = "OpenBTS> ";

	// Define this stuff "globally" as it's needed in various places
	memset(&sa, 0, sizeof(sa));

	// the socket
	sock = socket(AF_INET,SOCK_STREAM,0);
	if (sock<0) {
		perror("opening stream socket");
		exit(1);
	}

	// destination address
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	if (inet_pton(AF_INET, target, &sa.sin_addr) <= 0) {
		oops("unable to convert target to an IP address\n");
	}

	if (0) {
		// (pat) I used this code for testing.
		// If you wanted to specify the port you were binding from, this is how you would do it...
		// We dont use this code - we let the connect system call pick the port.
		struct sockaddr_in sockAddrBuf;
		memset(&sockAddrBuf,0,sizeof(sockAddrBuf));		// overkill.
		sockAddrBuf.sin_family = AF_INET;
		sockAddrBuf.sin_addr.s_addr = INADDR_ANY;
		sockAddrBuf.sin_port = htons(13011);
		if (bind(sock, (struct sockaddr *) &sockAddrBuf, sizeof(struct sockaddr_in))) {	// Bind the socket to our assigned port.
			printf("bind call failed: %s",strerror(errno));
			exit(2);
		}
	}

	if (connect(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
		perror("connect stream socket");
		fprintf(stderr, "Is OpenBTS running?\n");
		exit(1);
	}

#ifdef HAVE_LIBREADLINE
	char *history_name = 0;
	if (!isBTSDo)
	{
	    // start console
	    using_history();

	    static const char * const history_file_name = "/.openbts_history";
	    char *home_dir = getenv("HOME");

	    if(home_dir) {
		    size_t home_dir_len = strlen(home_dir);
		    size_t history_file_len = strlen(history_file_name);
		    size_t history_len = home_dir_len + history_file_len + 1;
		    if(history_len > home_dir_len) {
			    if(!(history_name = (char *)malloc(history_len))) {
				    perror("malloc failed");
				    exit(2);
			    }
			    memcpy(history_name, home_dir, home_dir_len);
			    memcpy(history_name + home_dir_len, history_file_name,
			       history_file_len + 1);
			    read_history(history_name);
		    }
	    }
	}
#endif


	if (!isBTSDo)
	    printf("Remote Interface Ready.\nType:\n \"help\" to see commands,\n \"version\" for version information,\n \"notices\" for licensing information,\n \"quit\" to exit console interface.\n");


        if (sCommand.c_str()[0] != '\0') {
                doCmd(sock, (char *)sCommand.c_str());
        } else
            while (1)
            {
#ifdef HAVE_LIBREADLINE
                char *cmd = readline(isBTSDo ? NULL : prompt);
                if (!cmd) continue;
                        if (cmd[0] == '\0') continue;
                if (!isBTSDo)
                    if (*cmd) add_history(cmd);
#else // HAVE_LIBREADLINE
                if (!isBTSDo)
                {
                    printf("%s",prompt);
                    fflush(stdout);
                }
                char *inbuf = (char*)malloc(BUFSIZ);
                char *cmd = fgets(inbuf,BUFSIZ-1,stdin);
                if (!cmd)
                {
                    if (isBTSDo)
                        break;
                    continue;
                }
                        if (cmd[0] == '\0') continue;
                // strip trailing CR
                cmd[strlen(cmd)-1] = '\0';
#endif
                if (!isBTSDo)
                {
                    // local quit?
                    if (strcmp(cmd,"quit")==0) {
                        printf("closing remote console\n");
                        break;
                    }
                            // shutdown via upstart
                    if (strcmp(cmd,"shutdown")==0) {
                        printf("terminating openbts\n");
                        if (getuid() == 0)
                            system("stop openbts");
                        else
                        {
                            printf("If prompted, enter the password you use for sudo\n");
                            system("sudo stop openbts");
                        }
                        break;
                    }
                    // shell escape?
                    if (cmd[0]=='!') {
                        int i = system(cmd+1);
                        if (i < 0)
                        {
                            perror("system");
                        }
                        continue;
                    }
                }
                char *pCmd = cmd;
                while(isspace(*pCmd)) pCmd++; // skip leading whitespace
                if (*pCmd)
                {
                    if (doCmd(sock, cmd) == false)
                    {
                        bool sd = false;
                        if (strcmp(cmd,"shutdown")==0)
                            sd = true;
                        else if (strcmp(cmd,"restart")==0)
                            sd = true;
                        free(cmd);
                        //{
                            if (isBTSDo)
                                break;
                            if (sd)
                                break;
                            continue;
                        //}
                    }
                }
                free(cmd);
                if (isBTSDo)
                    break;
            }

#ifdef HAVE_LIBREADLINE
	if (!isBTSDo)
	{
	    if(history_name)
	    {
		    int e = write_history(history_name);
		    if(e) {
			    fprintf(stderr, "error: history: %s\n", strerror(e));
		    }
		    free(history_name);
		    history_name = 0;
	    }
	}
#endif


	close(sock);
}
Ejemplo n.º 17
0
/*
 * Here, we should handle exit code.
 *
 * If each command ran and exit normally, maximum (worst) value of the status code
 * will be returned.
 *
 * If SIGINT is detected, then the status will be set with EC_IFSTOPPED flag, as well as
 * EC_STOPSIG to SIGINT.  In this case, EC_IFSTOPPED will be set and EC_SIGNAL will be
 * set to SIGKILL as well.  Exit status will be set to 2.
 */
int doCmdList(cmdList_t *cmds)
{
	int ii, jj;
	xc_status rc = 0;

	dump_cmdList(cmds);
	if (cmds->cmds == NULL)
		return(0);
	old_HandlerDoShell = signal(SIGINT, do_shell_SigHandler);
	whereToJumpDoShell = &dcJmpBufDoShell;
	/*
	 * Invoke remote command with SSH
	 */
	prepareStdout(cmds);
	if (setjmp(dcJmpBufDoShell) == 0)
	{
		for (ii = 0; cmds->cmds[ii]; ii++)
		{
			if (!isVarYes(VAR_debug))
			{
				if ((cmds->cmds[ii]->pid = fork()) != 0)
				{
					if (cmds->cmds[ii]->pid == -1)
					{
						elog(ERROR, "Process for \"%s\" failed to start. %s\n",
									cmds->cmds[ii]->actualCmd,
									strerror(errno));
						cmds->cmds[ii]->pid = 0;
					}
					continue;
				}
				else
					exit(doCmd(cmds->cmds[ii]));
			}
			else
			{
				cmds->cmds[ii]->excode = doCmd(cmds->cmds[ii]);
				rc = WEXITSTATUS(cmds->cmds[ii]->excode);
			}
		}
	}
	else
	{
		/* Signal exit here */
		for (ii = 0; cmds->cmds[ii]; ii++)
		{
			if (!isVarYes(VAR_debug))
			{
				if (cmds->cmds[ii]->pid)
				{
					/*
					 * We don't care if the process is alive or not.
					 * Try to kill anyway.  Then handle remote/local
					 * stdin/stdout in the next step.
					 *
					 * If it's bothering to wait for printing, the user can
					 * issue a SIGINT again.
					 */
					kill(cmds->cmds[ii]->pid, SIGKILL);
					cmds->cmds[ii]->pid = 0;
				}
			}
			else
			{
				/* Something to do at non-parallel execution */
			}
		}
		elog(NOTICE, "%s:%d Finish by interrupt\n", __FUNCTION__, __LINE__);
		return 2;
	}
	/*
	 * Handle remote/local stdin/stdout
	 */
	signal(SIGINT, do_shell_SigHandler);
	if (setjmp(dcJmpBufDoShell) == 0)
	{
		for (ii = 0; cmds->cmds[ii]; ii++)
		{
			int status;
			cmd_t *cur;

			if (!isVarYes(VAR_debug))
			{
				if (cmds->cmds[ii]->pid)
				{
					int rc_new;
					
					rc_new = waitpid(cmds->cmds[ii]->pid, &status, 0);
					rc = WEXITSTATUS(rc_new);
				}
			}
			cmds->cmds[ii]->pid = 0;
			for (cur = cmds->cmds[ii]; cur; cur = cur->next)
			{
				elogFile(MANDATORY, cur->localStdout);
				doImmediateRaw("(rm -f %s) < /dev/null > /dev/null", cur->localStdout);
				freeAndReset(cur->actualCmd);
				freeAndReset(cur->localStdout);
				freeAndReset(cur->msg);
			}
		}
	}
	else
	{
		/* Captured SIGINT */
		signal(SIGINT, old_HandlerDoShell);

		for (jj = 0; cmds->cmds[jj]; jj++)
		{
			/* Need to handle the case with non-parallel execution */
			if (cmds->cmds[jj]->pid)
			{
				kill(cmds->cmds[jj]->pid, SIGKILL);
				cmds->cmds[jj]->pid = 0;
			}
			if (cmds->cmds[jj]->localStdout)
				doImmediate(NULL, NULL, "rm -f %s", cmds->cmds[jj]->localStdout);
			if (cmds->cmds[jj]->remoteStdout)		/* Note that remote stdout will be removed anyway */
				doImmediate(cmds->cmds[jj]->host, NULL, "rm -f %s",
							cmds->cmds[jj]->remoteStdout);
			freeAndReset(cmds->cmds[jj]->actualCmd);
			freeAndReset(cmds->cmds[jj]->localStdout);
			freeAndReset(cmds->cmds[jj]->msg);
			freeAndReset(cmds->cmds[jj]->remoteStdout);
		}
		elog(NOTICE, "%s:%d Finish by interrupt\n", __FUNCTION__, __LINE__);
		return(2);
	}
	signal(SIGINT, old_HandlerDoShell);
	whereToJumpDoShell = NULL;
	return(rc);
}
Ejemplo n.º 18
0
Archivo: docmd.c Proyecto: Zorgie/OSOld
int main(int argc, char* argv[], char* env[])
{
	return doCmd(argc, argv);
}