예제 #1
0
/*
 * Function: exec_command()
 * ------------------------
 * Checks the command string for pipes and builtin commands.
 *
 * @param command_str; All commands given as string.
 * @returns; void.
 */
void exec_command(char* command_str) {

    funcp_t builtin_func;

    /* Split the commands on pipes */
    char** commands = split_command(command_str, "|");

    /* Split the first command to check for builtins */
    char** command_args = split_command(commands[0], " ");
    builtin_func = get_builtin_command(command_args[0]);

    /* If builtin the execute, else goto pipeline execution. */
    if (builtin_func) {
        (*builtin_func)(command_args);
    } else {
        exec_pipeline(commands, STDIN_FILENO);
    }

    /* Free all splitted commands */
    unsigned int i = 0;
    while (commands[i])
        free(commands[i++]);
    i = 0;
    while (command_args[i])
        free(command_args[i++]);
    free(commands);
}
/*
 * This method gets called when user tapped tab key.
 * line - points to command line
 * len - size of line that should be used for completions. This should be
 *   cursor position during tab hit.
 */
void process_tab(const char *line, int len)
{
	int argc;
	static split_arg_t buf[(LINE_BUF_MAX * 2) / sizeof(split_arg_t)];
	const struct method *method;

	argc = split_command(line, len, buf, sizeof(buf));
	tab_hit_count++;

	if (argc == 0)
		return;

	if (argc == 1) {
		command_completion(buf);
		return;
	}

	method = get_command(buf[0].ntcopy);
	if (method != NULL) {
		param_completion(argc, buf, method, 1);
	} else if (argc == 2) {
		method_completion(get_interface(buf[0].ntcopy), buf);
	} else {
		/* Find method for <interface, name> pair */
		method = get_interface_method(buf[0].ntcopy,
							buf[0].next->ntcopy);
		param_completion(argc, buf, method, 2);
	}
}
예제 #3
0
파일: smsh1.c 프로젝트: yangmiemie/books
int main(int argc, char *argv[])
{
  char *cmdline, **arglist;
  char *prompt;
  char **single_cmds;
  int i, cmd_number;
  int rv;

  prompt = DEL_PROMPT;
  setup();

  exec_cmds = malloc(sizeof(char*) * MAXEXECCMDS);

  while((cmdline = next_command(prompt, stdin)) != NULL)
  {
    single_cmds = split_command(cmdline);

    for (i = 0; single_cmds[i] != '\0'; ++i)
    {
      if ((arglist = splitline(single_cmds[i])) != NULL)
      {
        // for those arglist executed later, we don't free it.
        // we free later arglists in do_control_command's fi.
        if ((rv = process(arglist)) != -1)
          freelist(arglist);
      }
    }

    freelist(single_cmds);
    free(cmdline);
  }

  free(exec_cmds);
  return 0;
}
예제 #4
0
void* cl_recv(void* args){
	printf("Pret a recevoir...\n");
	char* ch = (char*)malloc(100);
	char* buff = (char*)malloc(1024);
	int i,r;
	Params* p = (Params*)args;
	int sockfd = p->sock;
	while(1){
		r = recv(sockfd,ch,100,0);
		if(r < 0){return NULL;}
		i = 0;
		while(i<r && ch[i] != '\0'){
			if(ch[i] != '\n'){
				sprintf(buff,"%s%c",buff,ch[i]);
			}
			else{
				struct Command c = split_command(buff);
				puts("\nReception : ");
				pthread_mutex_lock(&mutex_stock);
				command_treatment(p->p_game,&c);
				pthread_mutex_unlock(&mutex_stock);
				int j = 0;
				while(j < 1024){
					buff[j++] = '\0';
				}
				game_print(p->p_game);
			}
			i++;
		}
	}
    pthread_cancel(pth_display);
    pthread_cancel(pth_recv);
	return NULL;
}
예제 #5
0
void* cl_display(void* args) {
	printf("Pret a afficher...\n");
	Params* p = (Params*)args;
	int sockfd = p->sock;
	screen_init(p->p_screen,p->p_game);
	int continuer = 1;
	p->p_screen->curpos = 0;
    SDL_EnableUNICODE(1);
    while (continuer)
    {
    	SDL_Event event;
    	SDL_PollEvent(&event);
        SDL_WaitEvent(&event);
        switch(event.type)
        {
            case SDL_QUIT:
                continuer = 0;
                break;
            case SDL_KEYDOWN:
            	 p->p_screen->curpos = gereTouche(&(event.key), p->p_screen->chaine, p->p_screen->curpos);
                 break;
        }
        if(p->p_screen->curpos==-1){
			struct Command c = split_command(p->p_screen->chaine);
			int num_cmd = command_num(c.name);
			pthread_mutex_lock(&mutex_stock);
			if(num_cmd==17 && command_treatment(p->p_game,&c)==2){
				continuer = 0;
				break;
			}
			if(num_cmd==16 || num_cmd==18 || num_cmd==22)
				command_treatment(p->p_game,&c);
			if(num_cmd != 14 || num_cmd==-1 || (num_cmd==14 && command_treatment(p->p_game,&c)==0)){
				p->p_game->last_command = &c;
				send(sockfd,p->p_screen->chaine,strlen(p->p_screen->chaine),0);
			}
			pthread_mutex_unlock(&mutex_stock);
        }
        if(p->p_screen->curpos==-1 || p->p_screen->curpos==-2){
			p->p_screen->curpos = 0;
			int j = 0;
			while(j < 100){
				p->p_screen->chaine[j++] = '\0';
			}
        }
        pthread_mutex_lock(&mutex_stock);
        screen_init(p->p_screen,p->p_game);
        pthread_mutex_unlock(&mutex_stock);
    }
    SDL_EnableUNICODE(0);
    pthread_cancel(pth_recv);
	free(p->p_screen);
	free(p->p_game);
	SDL_Quit();
	pthread_cancel(pth_display);
	exit(0);
	return NULL;
}
예제 #6
0
파일: ftpd.c 프로젝트: epicsdeb/rtems
/*PAGE
 *
 * session
 *
 * This task handles single session.  It is waked up when the FTP daemon gets a
 * service request from a remote machine.  Here, we watch for commands that
 * will come through the control connection.  These commands are then parsed
 * and executed until the connection is closed, either unintentionally or
 * intentionally with the "QUIT" command.
 *
 * Input parameters:
 *   arg - pointer to corresponding SessionInfo.
 *
 * Output parameters:
 *   NONE
 */
static void
session(rtems_task_argument arg)
{
  FTPD_SessionInfo_t  *const info = (FTPD_SessionInfo_t  *)arg;
  int chroot_made = 0;

  rtems_libio_set_private_env();

  /* chroot() can fail here because the directory may not exist yet. */
  chroot_made = chroot(ftpd_root) == 0;

  while(1)
  {
    rtems_event_set set;

    rtems_event_receive(FTPD_RTEMS_EVENT, RTEMS_EVENT_ANY, RTEMS_NO_TIMEOUT,
      &set);

    chroot_made = chroot_made || chroot(ftpd_root) == 0;
    chdir("/");

    errno = 0;

    send_reply(info, 220, FTPD_SERVER_MESSAGE);

    while (1)
    {
      char buf[FTPD_BUFSIZE];
      char *cmd, *opts, *args;

      if (fgets(buf, FTPD_BUFSIZE, info->ctrl_fp) == NULL)
      {
        syslog(LOG_INFO, "ftpd: Connection aborted.");
        break;
      }

      split_command(buf, &cmd, &opts, &args);

      if (!strcmp("QUIT", cmd))
      {
        send_reply(info, 221, "Goodbye.");
        break;
      }
      else
      {
        exec_command(info, cmd, args);
      }
    }

    /* Close connection and put ourselves back into the task pool. */
    close_data_socket(info);
    close_stream(info);
    task_pool_release(info);
  }
}
예제 #7
0
static array<tree>
parse_vernac_proof (string s) {
  array<tree> r;
  array<string> a= split_command (s);
  if (N(a) == 0) return r;
  r << compound ("coq-command", "", "dark grey", parse_subcommand (a[0]));
  if (N(a) > 1) {
    string pf= recompose (range (a, 1, N(a)), " ");
    r << parse_vernac_command (pf);
  }
  return r;
}
예제 #8
0
/*
 * Function: exec_pipeline()
 * ------------------------
 * Execute the commands given in a pipeline, where the given
 * file descriptor is the write side of the pipe precessor.
 *
 * @param commands; All commands due for executing in the pipeline
 * @param in_fd; file descriptor to read from.
 * @returns; void.
 */
void  exec_pipeline(char** commands, int in_fd) {

    char** args = split_command(commands[0], " ");
    pid_t child;

    int fd[2];
    pipe(fd);

    switch (child = fork()) {
        /* Something wrong */
        case -1:
            perror("Fork:");
            exit(EXIT_FAILURE);
        /* Child */
        case 0:
            /* Reset to the default signal handler to kill processes */
            signal(SIGINT, SIG_DFL);

            if (commands[1] != NULL) {
                /* Set the OUTPUT of child to WRITE f_desc. */
                dup2(fd[1], STDOUT_FILENO);
            }

            /* Set the INPUT of child to the given output of the previes call. */
            dup2(in_fd, STDIN_FILENO);

            /* Disobey parent. (stop reading from shell). */
            close(fd[0]);

            execvp(args[0], args);
            perror("Error:");
            _exit(EXIT_FAILURE);
        /* Parent */
        default:
            /* Parent cannot write to child. */
            close(fd[1]);
            /* If there are more commands, put them in pipeline. */
            if (commands[1] != NULL) {
                exec_pipeline(++commands, fd[0]);
            }
            /* Else wait for the last child from the pipeline to finish. */
            else {
                while (wait(NULL) != child);
            }
    }
    /* Free the splitted string */
    unsigned int i = 0;
    while (args[i])
        free(args[i++]);
    free(args);
}
예제 #9
0
파일: esplsh.c 프로젝트: razlib/espl
int main(int _argc, char **_argv) {
  /* clear shell variables and re-assign a minimum set */
	 	  
  clearenv();
  setenv("PATH", ":/bin:/usr/bin", 1);
  setenv("PROMPT", "$ ", 1);
  setenv("SHELL", _argv[0], 1);

  signal(SIGINT, SIG_IGN); /* ignore ^C */

  while(1) {
    printf("%s", getenv("PROMPT"));
    if(!read_command())
      break;
    split_command();
    if(!argc)
      continue;
    expand_args();
    /* process builtin commands */
    if(!strcmp(argv[0],"exit")) {
      break;
    } else if(!strcmp(argv[0],"set")) {
      if(argc!=3) {
        fprintf(stderr, "set: two arguments required\n");
        continue;
      }
      setenv(argv[1], argv[2], 1);
    } else if(!strcmp(argv[0], "cd")) {
      if(argc!=2) {
        fprintf(stderr, "cd: one argument required\n");
        continue;
      }
      if(chdir(argv[1])==-1) {
        perror("cd");
      }
    } else if(!strcmp(argv[0], "pwd")) {
      if(argc!=1) {
        fprintf(stderr, "pwd: no arguments allowed\n");
        continue;
      }
      printf("%s\n", getcwd(command, BUF_LEN));
    }  else {
      /* run external command */
      run_program();
    }
    free_args();
  }
  printf("\n");

  return 0;
}
예제 #10
0
static tree
parse_vernac_command (string s, bool wrap= false) {
  tree r (CONCAT);
  array<string> a= split_command (s);
  if (N(a) == 1)
    return compound ("coq-command", "", "dark grey",
                     parse_subcommand (a[0], wrap));
  else if (N(a) > 0) {
    for (int i=0; i<N(a)-1; i++)
      r << compound ("coq-command", "", "dark grey",
                     ensure_inline (parse_subcommand (a[i], wrap)))
        << " ";
    r << compound ("coq-command", "", "dark grey",
                   ensure_inline (parse_subcommand (a[N(a)-1], wrap)));
  }
  return r;
}
예제 #11
0
void*  task_nmap(void *comd)
{
    char **fake=NULL;
    int i;
    pid_t pid;
    
    int id;
    char pd[32];
    pid_t del_pid;
    char  del_comd[256]={0};
 //   LOG_INFO("here is %s",comd);  
   fake=split_command(comd);
  ////ɾ³ýɨÃè 
  if(strcmp(fake[2],"type=stop")==0)
   {
     del_pid=atoi(fake[3]+4); 
     snprintf(del_comd,256,"kill -9 %d",del_pid); 
     system(del_comd);
     goto over;
   }
  ////н¨É¨ÃèÈÎÎñ

   pid=fork();  
   signal(SIGCHLD, SIG_IGN);  
	if(pid == 0 )
	{
	 
    if( execl(_PATH_, _FILE_,fake[1],fake[2],fake[3], NULL)<0)
          LOG_INFO("execl error!!!");
	}
	id=atoi(fake[1]+3);
    sprintf(pd,"%d",pid);
   // printf("child process pid is %d  id is %d pd is %s\n",pid,id ,pd);
   save_pid_to_db(id,pd); 
  
over:  if(fake!=NULL)
       {
        for(i=0;i<4;i++)
          free(fake[i]);
         free(fake);
         fake=NULL;
       }
     free(comd);    
	return NULL;
}
예제 #12
0
		// handle command
		// /log read user startline
		// /log find user substr startline
		extern int handle_log_command(t_connection * c, char const *text)
		{
			const char *subcommand, *username;
			long startline = 0;
			std::map<long, char*> lines;

			// split command args
			std::vector<std::string> args = split_command(text, 4);
			if (args[1].empty() || args[2].empty() 
				|| (args[1].at(0) != 'r' && args[1].at(0) != 'f')) // check start symbols for subcommand
			{
				describe_command(c, args[0].c_str());
				return -1;
			}
			subcommand = args[1].c_str(); // sub command
			username = args[2].c_str(); // username

			if (!accountlist_find_account(username))
			{
				message_send_text(c, message_type_error, c, localize(c, "Invalid user."));
				return -1;
			}

			std::string title = localize(c, "{}'s log output", username);
			// read
			if (subcommand[0] == 'r')
			{
				if (!args[3].empty())
					startline = atoi(args[3].c_str());

				lines = userlog_read(username, startline);
			}
			// find
			else if (subcommand[0] == 'f')
			{
				if (args[3].empty())
				{
					describe_command(c, args[0].c_str());
					return -1;
				}
				const char * search = args[3].c_str();
				title += localize(c, " by occurrence \"{}\"", search);

				if (!args[4].empty())
					startline = atoi(args[4].c_str());

				lines = userlog_find_text(username, search, startline);
			}

			title += ":";
			message_send_text(c, message_type_info, c, title);

			int linelen = 0;
			int paddedlen = 0;
			std::string linenum;

			// send each log line to user
			for (std::map<long, char*>::reverse_iterator it = lines.rbegin(); it != lines.rend(); ++it)
			{
				int linelen = floor(log10(static_cast<double>(abs(it->first)))) + 1; // get length of integer (line number)
				if (linelen > paddedlen)
					paddedlen = linelen;

				linenum = std_to_string(it->first);
				// pad left to max line length
				linenum.insert(linenum.begin(), paddedlen - linenum.size(), '0');

				message_send_text(c, message_type_info, c, linenum + ": " + std::string(it->second));
			}

			return 0;
		}
예제 #13
0
void read_command(Command* com) {
	fgets(buffer, 400, stdin);
	split_command(buffer, com);
}
예제 #14
0
int main(void)
{

	struct person player =
	{
		// Name
		"\0",
		// Position
		{0, 0},
		// Map
		{
			{"+=======+==========+"},
			{"|SHP    |G         |"},
			{"|G      |          |"},
			{"|=======+==========|"},
			{"|       |PP        |"},
			{"|       |PP        |"},
			{"|       +==========|"},
			{"|       |HHHH      |"},
			{"|       |HH        |"},
			{"|       +====+     |"},
			{"|=======+    |     |"},
			{"|     GG|    |SS   |"},
			{"|       |    +=====|"},
			{"|       |          |"},
			{"|=======+          |"},
			{"|       HHH        |"},
			{"|        Ho====+===|"},
			{"|   PPP        |   |"},
			{"|   PPP        |   |"},
			{"+==============+===+"}
		},
		// Health (actual, full)
		{50, 100},
		// Money
		10000.00,

		// Skill_points;
		10,
		// Intelligence;
		1,
		// Stealth;
		1,
		// Charisma;
		1,

		// Equipped Weapon
		0,
		// Equipped Ammo
		{0,0},
		// Weapons
		{
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
			{0,0},
		},
		// Items
		{
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0},
			{0, 0}
		}
	};

	// Command list
	char commandlist[MAX_COMMAND_LENGTH][NUM_OF_COMMANDS]=
	{
		{"enter"},
		{"exit"},
		{"help"},
		{"inv"},
		{"map"},
		{"tile"},
		{"walk"}
	};

	// Command
	char command[100];
	char cmdprompt[10];

	// Word (Sectioned Command)
	char *word[100];

	/////////////////////////
	// Database

	//item objects = NULL;
	//int num_obj = 0;

	/////////////////////////
	// Main Menu
	do
	{
		clearscr();
		printf("Urban Sprawl\n");
		printl();
		printf("By: Sami Volk	2012\n");
		pause();
		//clearscr();
		do
		{
			printf("Please type in one of the commands: \n");
			printf("NEW - starts a new game \t\t");
			printf("QUIT - quits game\n");

			get_command(">> ",command);
			//clearscr();

			// check for "exit" command.
			if ((strcmp("exit", command) == 0) || (strcmp("quit", command) == 0))
			{
				printf("Good bye!");
				pause();
				exit(0);
			}
			else if (strcmp("new", command) == 0)
			{
				printf("What is your name?\n");
				fgets(player.name, 100, stdin);
				fflush(stdin);
				//clearscr();
				break;
			}
			else
			{
				printf("Command not recognized.\n");
				pause();
			}

		}while (1);

		break;

	}while (1);

	/////////////////////////
	// Main game loop
	do
	{

		//printf("name: %s\n", player.name);
		//printf("Position: %d, %d \n", player.position[0], player.position[1]);
		//printf("Health: %d / %d\n", player.health[0], player.health[1]);
		//printf("Money: $%.2f\n", player.money);
		//printl();

		//tile_info(player.map, player.position);
		//printl();

		sprintf(cmdprompt, "\033[22;31m%d/%d \033[22;37m>> ", player.health[0], player.health[1]);
		//printf("%s\n", cmdprompt);

		get_command(cmdprompt,command);
		split_command(command, word);
		check_command(word, &player);
		printl();

	} while (1);

	return 0;

}
예제 #15
0
파일: shell.c 프로젝트: rooa/myshell
int main(int argc, char *argv[])
{
  int i,pid;
  int pid2;
  int status;
  int delimiter;
  
  char *tokens[NUMTOKEN];
  char *command;
  char *PIPE = "|";
  int num_tokens;
  int pipe_indices[10];
  
  read_path();

  while(1){
    allocate(tokens);
    command = (char *)malloc(sizeof(char) * 100);  // Cannot move to allocate(). TODO resolve
    printf (">>> ");
    fflush(stdout);
    
    input(0,command);
    printf ("%s\n",command);
    num_tokens = split_command(command, tokens);
    

    
    delimiter = 0;
    for (i = 0; i < num_tokens; ++i){
      if (strcmp(tokens[i],PIPE) == 0) {
	pipe_indices[delimiter] = i;
	delimiter++;
      }
    }
    child_process(delimiter+1);

    pid = fork();
    // Child process
    if (pid == 0)
      {
	puts("Child process started.");
	execvp(tokens[0],tokens);
	perror("fork error");
	exit(-1);
      }
    else if (pid == -1)
      {
    	//ERROR
      }

    waitpid(pid, &status, 0); /*子プロセスが終了するのを待つ*/    
    if (WIFEXITED(status)) {
      // 子プロセスが正常終了の場合
      printf("child exit-code=%d\n", WEXITSTATUS(status));
    } else {
      printf("child status=%04x\n", status);
    }
    free_arrays(tokens,command);
  }

  free(tokens);

  return EXIT_SUCCESS;

}
예제 #16
0
/*
 * This will receive a file from a remote host. Expects a socket integer and
 * a filename. The file will be basename'd and saved into /tmp.
 *
 */
void receive_file(int skt, const char *filename, int server)
{
  char msg[MSGLEN], cmd[CMDLEN], arg[MSGLEN], lname[MSGLEN], errmsg[ERRMSGLEN];
  char *basefname;
  FILE *outfile;
  int fsize = 0, segments = 0, cur_segment = 0;
  
  /* get the local file name in /tmp */
  memset(lname, '\0', MSGLEN);
  memset(errmsg, '\0', ERRMSGLEN);
  strcpy(msg, filename);
  basefname = basename(msg);
  sprintf(lname, "/tmp/%s", basefname);
  
  /* if file exists, send err to remote, otherwise send cts and await size */
  if(exist(lname))
  {
    debug("Filesystem", "Not receiving file since it already exists");
    if(server)
    {
      send_packet(skt, "err:File already exists");
    }
    return;
  }
  
  /* open file for writing */
  outfile = fopen(lname, "w");
  if(outfile == NULL)
  {
    sprintf(errmsg, "Could not open file for writing: %s", strerror(errno));
    debug("Filesystem", errmsg);
    if(server)
    {
      send_packet(skt, "err:File could not be written");
    }
    return;
  }
  
  /* ready to receive file */
  if(server)
  {
    memset(msg, '\0', MSGLEN);
    strcpy(msg, "cts");
    send_message(skt, msg);
  }
  else
  {
    receive_packet(skt, msg);
  }
  split_command(msg, cmd, arg);
  segments = atoi(cmd);
  fsize = atoi(arg);
  sprintf(errmsg, "Going to receive %d bytes in %d segments", fsize, segments);
  debug("Filesystem", errmsg);
  
  /* loop through segments packet count and get the file */
  for(cur_segment = 0; cur_segment <= segments; cur_segment++)
  {
    printf("\rFilesystem: Receiving File: %d / %d", cur_segment, segments);
    memset(msg, '\0', MSGLEN);
    receive_packet(skt, msg);
    if(cur_segment == segments)
    {
      /* write remaining bytes */
      fwrite(msg, (fsize - (segments * MSGLEN)), 1, outfile);
    }
    else
    {
      /* write complete segment */
      fwrite(msg, MSGLEN, 1, outfile);
    }
  }
  printf("\n");
  fclose(outfile);
}
예제 #17
0
파일: mmc.c 프로젝트: zhsyourai/mmc-utils
/*
	This function performs the following jobs:
	- show the help if '--help' or 'help' or '-h' are passed
	- verify that a command is not ambiguous, otherwise show which
	  part of the command is ambiguous
	- if after a (even partial) command there is '--help' show detailed help
	  for all the matching commands
	- if the command doesn't match show an error
	- finally, if a command matches, they return which command matched and
	  the arguments

	The function return 0 in case of help is requested; <0 in case
	of uncorrect command; >0 in case of matching commands
	argc, argv are the arg-counter and arg-vector (input)
	*nargs_ is the number of the arguments after the command (output)
	**cmd_  is the invoked command (output)
	***args_ are the arguments after the command

*/
static int parse_args(int argc, char **argv,
		      CommandFunction *func_,
		      int *nargs_, char **cmd_, char ***args_ )
{
	struct Command	*cp;
	struct Command	*matchcmd=0;
	char		*prgname = get_prgname(argv[0]);
	int		i=0, helprequested=0;

	if( argc < 2 || !strcmp(argv[1], "help") ||
		!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
		help(prgname);
		return 0;
	}

	for( cp = commands; cp->verb; cp++ )
		if( !cp->ncmds)
			cp->ncmds = split_command(cp->verb, &(cp->cmds));

	for( cp = commands; cp->verb; cp++ ){
		int     match;

		if( argc-1 < cp->ncmds )
			continue;
		for( match = 1, i = 0 ; i < cp->ncmds ; i++ ){
			char	*s1, *s2;
			s1 = cp->cmds[i];
			s2 = argv[i+1];

			for(s2 = cp->cmds[i], s1 = argv[i+1];
				*s1 == *s2 && *s1;
				s1++, s2++ ) ;
			if( *s1 ){
				match=0;
				break;
			}
		}

		/* If you understand why this code works ...
			you are a genious !! */
		if(argc>i+1 && !strcmp(argv[i+1],"--help")){
			if(!helprequested)
				printf("Usage:\n");
			print_help(prgname, cp, ADVANCED_HELP);
			helprequested=1;
			continue;
		}

		if(!match)
			continue;

		matchcmd = cp;
		*nargs_  = argc-matchcmd->ncmds-1;
		*cmd_ = matchcmd->verb;
		*args_ = argv+matchcmd->ncmds+1;
		*func_ = cp->func;

		break;
	}

	if(helprequested){
		printf("\n%s\n", MMC_VERSION);
		return 0;
	}

	if(!matchcmd){
		fprintf( stderr, "ERROR: unknown command '%s'\n",argv[1]);
		help(prgname);
		return -1;
	}

	if(check_ambiguity(matchcmd, argv))
		return -2;

	/* check the number of argument */
	if (matchcmd->nargs < 0 && matchcmd->nargs < -*nargs_ ){
		fprintf(stderr, "ERROR: '%s' requires minimum %d arg(s)\n",
			matchcmd->verb, -matchcmd->nargs);
			return -2;
	}
	if(matchcmd->nargs >= 0 && matchcmd->nargs != *nargs_ && matchcmd->nargs != 999){
		fprintf(stderr, "ERROR: '%s' requires %d arg(s)\n",
			matchcmd->verb, matchcmd->nargs);
			return -2;
	}
	
        if (prepare_args( nargs_, args_, prgname, matchcmd )){
                fprintf(stderr, "ERROR: not enough memory\\n");
		return -20;
        }


	return 1;
}
예제 #18
0
파일: ftpd.c 프로젝트: epicsdeb/rtems
/*PAGE
 *
 * exec_command
 *
 * Parse and execute FTP command.
 *
 * FIXME: This section is somewhat of a hack.  We should have a better
 *        way to parse commands.
 *
 * Input parameters:
 *   info - corresponding SessionInfo structure
 *   cmd  - command to be executed (upper-case)
 *   args - arguments of the command
 *
 * Output parameters:
 *    NONE
 */
static void
exec_command(FTPD_SessionInfo_t *info, char* cmd, char* args)
{
  char fname[FTPD_BUFSIZE];
  int wrong_command = 0;

  fname[0] = '\0';

  if (!strcmp("PORT", cmd))
  {
    command_port(info, args);
  }
  else if (!strcmp("PASV", cmd))
  {
    command_pasv(info);
  }
  else if (!strcmp("RETR", cmd))
  {
    strncpy(fname, args, 254);
    command_retrieve(info, fname);
  }
  else if (!strcmp("STOR", cmd))
  {
    strncpy(fname, args, 254);
    command_store(info, fname);
  }
  else if (!strcmp("LIST", cmd))
  {
    strncpy(fname, args, 254);
    command_list(info, fname, 1);
  }
  else if (!strcmp("NLST", cmd))
  {
    strncpy(fname, args, 254);
    command_list(info, fname, 0);
  }
  else if (!strcmp("MDTM", cmd))
  {
    strncpy(fname, args, 254);
    command_mdtm(info, fname);
  }
  else if (!strcmp("SYST", cmd))
  {
    send_reply(info, 215, FTPD_SYSTYPE);
  }
  else if (!strcmp("TYPE", cmd))
  {
    if (args[0] == 'I')
    {
      info->xfer_mode = TYPE_I;
      send_reply(info, 200, "Type set to I.");
    }
    else if (args[0] == 'A')
    {
      info->xfer_mode = TYPE_A;
      send_reply(info, 200, "Type set to A.");
    }
    else
    {
      info->xfer_mode = TYPE_I;
      send_reply(info, 504, "Type not implemented.  Set to I.");
    }
  }
  else if (!strcmp("USER", cmd) || !strcmp("PASS", cmd))
  {
    send_reply(info, 230, "User logged in.");
  }
  else if (!strcmp("DELE", cmd))
  {
    if(!can_write())
    {
      send_reply(info, 550, "Access denied.");
    }
    else if (
      strncpy(fname, args, 254) &&
      unlink(fname) == 0)
    {
      send_reply(info, 257, "DELE successful.");
    }
    else
    {
      send_reply(info, 550, "DELE failed.");
    }
  }
  else if (!strcmp("SITE", cmd))
  {
    char* opts;
    split_command(args, &cmd, &opts, &args);
    if(!strcmp("CHMOD", cmd))
    {
      int mask;

      if(!can_write())
      {
        send_reply(info, 550, "Access denied.");
      }
      else {
        char *c;
        c = strchr(args, ' ');
        if((c != NULL) && (sscanf(args, "%o", &mask) == 1) && strncpy(fname, c+1, 254) 
          && (chmod(fname, (mode_t)mask) == 0))
          send_reply(info, 257, "CHMOD successful.");
        else
          send_reply(info, 550, "CHMOD failed.");
      }
    }
    else
      wrong_command = 1;
  }
  else if (!strcmp("RMD", cmd))
  {
    if(!can_write())
    {
      send_reply(info, 550, "Access denied.");
    }
    else if (
      strncpy(fname, args, 254) &&
      rmdir(fname) == 0)
    {
      send_reply(info, 257, "RMD successful.");
    }
    else
    {
      send_reply(info, 550, "RMD failed.");
    }
  }
  else if (!strcmp("MKD", cmd))
  {
    if(!can_write())
    {
      send_reply(info, 550, "Access denied.");
    }
    else if (
      strncpy(fname, args, 254) &&
      mkdir(fname, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
    {
      send_reply(info, 257, "MKD successful.");
    }
    else
    {
      send_reply(info, 550, "MKD failed.");
    }
  }
  else if (!strcmp("CWD", cmd))
  {
    strncpy(fname, args, 254);
    command_cwd(info, fname);
  }
  else if (!strcmp("CDUP", cmd))
  {
    command_cwd(info, "..");
  }
  else if (!strcmp("PWD", cmd))
  {
    command_pwd(info);
  }
  else
    wrong_command = 1;

  if(wrong_command)
    send_reply(info, 500, "Command not understood.");
}
예제 #19
0
		// add new line at the end of log file
		extern void userlog_append(t_account * account, const char * text)
		{
			// is logging enabled?
			if (!prefs_get_log_commands())
				return;
			
			unsigned int groups = 0;
			const char * cglist = prefs_get_log_command_groups();

			// convert string groups from config to integer
			for (int i = 0; i < strlen(cglist); i++)
			{
				if (cglist[i] == '1') groups |= 1;
				else if (cglist[i] == '2') groups |= 2;
				else if (cglist[i] == '3') groups |= 4;
				else if (cglist[i] == '4') groups |= 8;
				else if (cglist[i] == '5') groups |= 16;
				else if (cglist[i] == '6') groups |= 32;
				else if (cglist[i] == '7') groups |= 64;
				else if (cglist[i] == '8') groups |= 128;
			}

			// log only commands for admins/operators and users in "groups" defined in config
			if (!account_is_operator_or_admin(account, NULL) && !(account_get_command_groups(account) & groups))
				return;

			bool is_cmd_found = false;

			// if command list empty then log all commands
			if (userlog_commands.size() == 0)
				is_cmd_found = true;
			else
			{
				// get command name
				std::vector<std::string> args = split_command(text, 0);
				std::string cmd = args[0];

				// find command in defined command list
				for (std::vector<std::string>::iterator it = userlog_commands.begin(); it != userlog_commands.end(); ++it) {
					if (*it == cmd)
					{
						is_cmd_found = true;
						break;
					}
				}
			}
			if (!is_cmd_found)
				return;

			// get time string
			char        time_string[USEREVENT_TIME_MAXLEN];
			struct std::tm * tmnow;
			std::time_t      now;

			std::time(&now);
			if (!(tmnow = std::localtime(&now)))
				std::strcpy(time_string, "?");
			else
				std::strftime(time_string, USEREVENT_TIME_MAXLEN, USEREVENT_TIME_FORMAT, tmnow);


			char * filename = userlog_filename(account_get_name(account), true);

			if (FILE *fp = fopen(filename, "a"))
			{
				// append date and text
				std::fprintf(fp, "[%s] %s\n", time_string, text);
				std::fclose(fp);
			}
			else
			{
				ERROR1("could not write into user log file \"%s\"", filename);
			}
		}
예제 #20
0
파일: exec.c 프로젝트: gjednaszewski/ipxe
/**
 * Execute command line
 *
 * @v command		Command line
 * @ret rc		Return status code
 *
 * Execute the named command and arguments.
 */
int system ( const char *command ) {
	int count = split_command ( ( char * ) command, NULL );
	char *all_tokens[ count + 1 ];
	int ( * process_next ) ( int rc );
	char *command_copy;
	char **tokens;
	int argc;
	int process;
	int rc = 0;

	/* Create modifiable copy of command */
	command_copy = strdup ( command );
	if ( ! command_copy )
		return -ENOMEM;

	/* Split command into tokens */
	split_command ( command_copy, all_tokens );
	all_tokens[count] = NULL;

	/* Process individual commands */
	process = 1;
	for ( tokens = all_tokens ; ; tokens += ( argc + 1 ) ) {

		/* Find command terminator */
		argc = command_terminator ( tokens, &process_next );

		/* Expand tokens and execute command */
		if ( process ) {
			char *argv[ argc + 1 ];

			/* Expand tokens */
			if ( ( rc = expand_tokens ( argc, tokens, argv ) ) != 0)
				break;
			argv[argc] = NULL;

			/* Execute command */
			rc = execv ( argv[0], argv );

			/* Free tokens */
			free_tokens ( argv );
		}

		/* Stop processing, if applicable */
		if ( shell_stopped ( SHELL_STOP_COMMAND ) )
			break;

		/* Stop processing if we have reached the end of the
		 * command.
		 */
		if ( ! process_next )
			break;

		/* Determine whether or not to process next command */
		process = process_next ( rc );
	}

	/* Free modified copy of command */
	free ( command_copy );

	return rc;
}
예제 #21
0
/****** Interactive/qrsh/startJob() ***************************************
*
*  NAME
*     startJob() -- start a shell with commands to execute
*
*  SYNOPSIS
*     static int startJob(char *command, char *wrapper, int noshell);
*
*  FUNCTION
*     Starts the commands and arguments to be executed as 
*     specified in parameter <command>. 
*     If the parameter noshell is set to 1, the command is directly called
*     by exec.
*     If a wrapper is specified (parameter wrapper, set by environment
*     variable QRSH_WRAPPER), this wrapper is called and is passed the 
*     command to execute as commandline parameters.
*     If neither noshell nor wrapper is set, a users login shell is called
*     with the parameters -c <command>.
*     The child process creates an own process group.
*     The pid of the child process is written to a pid file in $TMPDIR.
*
*  INPUTS
*     command - commandline to be executed
*     wrapper - name and path of a wrapper script
*     noshell - if != 0, call the command directly without shell
*
*  RESULT
*     status of the child process after it terminated
*     or EXIT_FAILURE, if the process of starting the child 
*     failed because of one of the following error situations:
*        - fork failed
*        - the pid of the child process cannot be written to pid file
*        - the name of actual user cannot be determined
*        - info about the actual user cannot be determined (getpwnam)
*        - necessary memory cannot be allocated
*        - executing the shell failed
*
*  SEE ALSO
*     Interactive/qrsh/write_pid_file()
*     Interactive/qrsh/split_command()
*     Interactive/qrsh/join_command()
*
****************************************************************************
*/
static int startJob(char *command, char *wrapper, int noshell)
{

   child_pid = fork();
   if(child_pid == -1) {
      qrsh_error(MSG_QRSH_STARTER_CANNOTFORKCHILD_S, strerror(errno));
      return EXIT_FAILURE;
   }

   if(child_pid) {
      /* parent */
      int status;

#if defined(LINUX)
      int ttyfd;
#endif

      signal(SIGINT,  forward_signal);
      signal(SIGQUIT, forward_signal);
      signal(SIGTERM, forward_signal);

      /* preserve pseudo terminal */
#if defined(LINUX)
      ttyfd = open("/dev/tty", O_RDWR);
      if (ttyfd != -1) {
         tcsetpgrp(ttyfd, child_pid);
         close(ttyfd); 
      }
#endif

      while(waitpid(child_pid, &status, 0) != child_pid && errno == EINTR);
      return(status);
   } else {
      /* child */
      char *buffer = NULL;
      int size;
      struct passwd pw_struct;
      char *shell    = NULL;
      char *userName = NULL;
      int    argc = 0;
      const char **args = NULL;
      char *cmd = NULL;
      int cmdargc;
      char **cmdargs = NULL;
      int i;

      if(!write_pid_file(getpid())) {
         exit(EXIT_FAILURE);
      }

      cmdargc = split_command(command, &cmdargs);

      if(cmdargc == 0) {
         qrsh_error(MSG_QRSH_STARTER_INVALIDCOMMAND);
         exit(EXIT_FAILURE);
      }

      if(!noshell) {
         struct passwd *pw = NULL;

         if((userName = search_conf_val("job_owner")) == NULL) {
            qrsh_error(MSG_QRSH_STARTER_CANNOTGETLOGIN_S, strerror(errno));
            exit(EXIT_FAILURE);
         }

         size = get_pw_buffer_size();
         buffer = sge_malloc(size);

         if ((pw = sge_getpwnam_r(userName, &pw_struct, buffer, size)) == NULL) {
            qrsh_error(MSG_QRSH_STARTER_CANNOTGETUSERINFO_S, strerror(errno));
            exit(EXIT_FAILURE);
         }
         
         shell = pw->pw_shell;
         
         if(shell == NULL) { 
            qrsh_error(MSG_QRSH_STARTER_CANNOTDETERMSHELL_S, "/bin/sh");
            shell = "/bin/sh";
         } 
      }
     
      if((args = malloc((cmdargc + 3) * sizeof(char *))) == NULL) {
         qrsh_error(MSG_QRSH_STARTER_MALLOCFAILED_S, strerror(errno));
         exit(EXIT_FAILURE);
      }         
    
      if(wrapper == NULL) {
         if(noshell) {
            cmd = cmdargs[0];
            for(i = 0; i < cmdargc; i++) {
               args[argc++] = cmdargs[i];
            }
         } else {
            cmd = shell;
            args[argc++] = sge_basename(shell, '/');
            args[argc++] = "-c";
            args[argc++] = join_command(cmdargc, cmdargs);
         }
      } else {
         cmd = wrapper;
         args[argc++] = sge_basename(wrapper, '/');
         for(i = 0; i < cmdargc; i++) {
            args[argc++] = cmdargs[i];
         }
      }

      args[argc++] = NULL;

#if 0
{
   /* debug code */
   int i;
   
   fflush(stdout) ; fflush(stderr);
   printf("qrsh_starter: executing %s\n", cmd);
   for(i = 1; args[i] != NULL; i++) {
      printf("args[%d] = %s\n", i, args[i]);
   }
   printf("\n");
   fflush(stdout) ; fflush(stderr); 
} 
#endif

      SETPGRP;
      execvp(cmd, (char *const *)args);
      /* exec failed */
      fprintf(stderr, MSG_QRSH_STARTER_EXECCHILDFAILED_S, args[0], strerror(errno));
      fprintf(stderr, "\n");
      exit(EXIT_FAILURE);
   }

   /* will never be reached */
   return EXIT_FAILURE; 
}