Esempio n. 1
0
void
cmdline_parser_init (struct gengetopt_args_info *args_info)
{
  clear_given (args_info);
  clear_args (args_info);
  init_args_info (args_info);
}
Esempio n. 2
0
void
cmdline_parser_init (struct gengetopt_args_info *args_info)
{
  clear_given (args_info);
  clear_args (args_info);
  init_args_info (args_info);

  args_info->inputs = NULL;
  args_info->inputs_num = 0;
}
Esempio n. 3
0
void process_multiple()
{
	/* Arguments:
			none
			
		Purpose:
			this function will split a sequence of commands
			by semicolon and execute them in order
			
	*/	
	char* list_cmds[20]; //we assume no more than 20 commands
	char *tmp_cmd = (char *)malloc(sizeof(char)*100);
	memset(tmp_cmd,0,100);
	int cmd_num = 0;
	
	int x,y=0;
	for(x=0;x<strlen(line);++x){
		if(line[x] != ';'){
			tmp_cmd[y] = line[x];
			++y;
		}
		else {
			tmp_cmd[y] = '\0';
			list_cmds[cmd_num] = (char *)calloc(100,sizeof(char)*strlen(tmp_cmd));
			//memset(list_cmds[cmd_num],0,strlen(tmp_cmd)+1);
			strcpy(list_cmds[cmd_num],tmp_cmd);
			memset(tmp_cmd, 0, 100);
			++cmd_num;
			y = 0;
		}
	}
	tmp_cmd[y+1] = '\0';
	list_cmds[cmd_num] = (char *)malloc(sizeof(char)*strlen(tmp_cmd));
	strcpy(list_cmds[cmd_num],tmp_cmd);
	memset(tmp_cmd,0,100);
	for(x=0;x<=cmd_num;++x){
		if(!check_pipe(list_cmds[x])){
			parse_args(list_cmds[x]);
			strcpy(tmp_cmd,args[0]);
			execute(tmp_cmd);
			clear_args();
			free(list_cmds[x]);
		}
	}	
	free(tmp_cmd);
}
int
main (int argc, char **argv)
{
  struct commandline cmd;

  (void) memset ((char *) &cmd, 0, sizeof (struct commandline));
  clear_args ();
  if (!parseargs (argc, argv, &cmd) || !cmd.infile)
    usage ();

  if (cmd.cflag || cmd.hflag || cmd.tflag)
    checkfiles (cmd.infile, cmd.outfile);
  else
    checkfiles (cmd.infile, NULL);

  if (cmd.cflag) {
    c_output (cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile);
  }
  else if (cmd.hflag) {
    h_output (cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile);
  }
  else if (cmd.tflag) {
    t_output (cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile);
  }
  else {
    /* the rescans are required, since cpp may effect input */
    c_output (cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c");
    reinitialize ();
    h_output (cmd.infile, "-DRPC_HDR", EXTEND, ".h");
    reinitialize ();
    t_output (cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.c");
  }
#ifdef __MSDOS__
  if (dos_cppfile != NULL) {
    (void) fclose (fin);
    (void) unlink (dos_cppfile);
  }
#endif
  exit (nonfatalerrors);
  /* NOTREACHED */
}
Esempio n. 5
0
int
cmdline_parser (int argc, char * const *argv, struct gengetopt_args_info *args_info)
{
  int c;	/* Character of the parsed option.  */
  int missing_required_options = 0;

  args_info->help_given = 0 ;
  args_info->version_given = 0 ;
  args_info->auto_given = 0 ;
  args_info->coordinated_given = 0 ;
  args_info->delay_given = 0 ;
  args_info->federation_given = 0 ;
  args_info->logfile_given = 0 ;
  args_info->name_given = 0 ;
  args_info->demo_given = 0 ;
  args_info->timer_given = 0 ;
  args_info->verbose_given = 0 ;
  args_info->xoffset_given = 0 ;
  args_info->yoffset_given = 0 ;
  args_info->initx_given = 0 ;
  args_info->inity_given = 0 ;
  args_info->filename_given = 0 ;
  args_info->notimestamp_given = 0 ;
#define clear_args() { \
  args_info->coordinated_flag = 1;\
  args_info->federation_arg = NULL; \
  args_info->logfile_arg = NULL; \
  args_info->name_arg = NULL; \
  args_info->demo_arg = NULL; \
  args_info->verbose_flag = 0;\
  args_info->filename_arg = NULL;\
  args_info->notimestamp_flag = 1;\
}

  clear_args();

  optarg = 0;
  optind = 1;
  opterr = 1;
  optopt = '?';

  while (1)
    {
      int option_index = 0;
      char *stop_char;

      static struct option long_options[] = {
        { "help",	0, NULL, 'h' },
        { "version",	0, NULL, 'V' },
        { "auto",	1, NULL, 'a' },
        { "coordinated",	0, NULL, 'c' },
        { "delay",	1, NULL, 'd' },
        { "notimestamp",	0, NULL, 'e' },
        { "federation",	1, NULL, 'f' },
        { "logfile",	1, NULL, 'l' },
        { "name",	1, NULL, 'n' },
        { "demo",	1, NULL, 'o' },
        { "timer",	1, NULL, 't' },
        { "verbose",	0, NULL, 'v' },
        { "xoffset",	1, NULL, 'x' },
        { "yoffset",	1, NULL, 'y' },
        { "initx",	1, NULL, 'X' },
        { "inity",	1, NULL, 'Y' },
        { "filename",   1, NULL, 'F' },
        { NULL,	0, NULL, 0 }
      };

      stop_char = 0;
      c = getopt_long (argc, argv, "hVa:cd:f:l:n:o:t:vx:y:X:Y:F:e", long_options, &option_index);

      if (c == -1) break;	/* Exit from `while (1)' loop.  */

      switch (c)
        {
        case 'h':	/* Print help and exit.  */
          clear_args ();
          cmdline_parser_print_help ();
          exit (EXIT_SUCCESS);

        case 'V':	/* Print version and exit.  */
          clear_args ();
          cmdline_parser_print_version ();
          exit (EXIT_SUCCESS);

        case 'a':	/* auto start.  */
          if (args_info->auto_given)
            {
              fprintf (stderr, "%s: `--auto' (`-a') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->auto_given = 1;
          args_info->auto_arg = strtol (optarg,&stop_char,0);
          break;

        case 'c':	/* coordinated time.  */
          if (args_info->coordinated_given)
            {
              fprintf (stderr, "%s: `--coordinated' (`-c') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->coordinated_given = 1;
          args_info->coordinated_flag = !(args_info->coordinated_flag);
          break;

        case 'd':	/* delay before 1st step.  */
          if (args_info->delay_given)
            {
              fprintf (stderr, "%s: `--delay' (`-d') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->delay_given = 1;
          args_info->delay_arg = strtol (optarg,&stop_char,0);
          break;

        case 'e':	/* no time stamp.  */
          if (args_info->notimestamp_given)
            {
              fprintf (stderr, "%s: `--notimestamp' (`-e') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->notimestamp_given = 1;
          args_info->notimestamp_flag = !(args_info->notimestamp_flag);
          break;

        case 'f':	/* federation name.  */
          if (args_info->federation_given)
            {
              fprintf (stderr, "%s: `--federation' (`-f') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->federation_given = 1;
          args_info->federation_arg = gengetopt_strdup (optarg);
          break;

        case 'l':	/* file to log events.  */
          if (args_info->logfile_given)
            {
              fprintf (stderr, "%s: `--logfile' (`-l') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->logfile_given = 1;
          args_info->logfile_arg = gengetopt_strdup (optarg);
          break;

        case 'n':	/* federate name.  */
          if (args_info->name_given)
            {
              fprintf (stderr, "%s: `--name' (`-n') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->name_given = 1;
          args_info->name_arg = gengetopt_strdup (optarg);
          break;

        case 'o':	/* select demo (static-ddm, dynamic-ddm).  */
          if (args_info->demo_given)
            {
              fprintf (stderr, "%s: `--demo' (`-o') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->demo_given = 1;
          args_info->demo_arg = gengetopt_strdup (optarg);
          break;

        case 't':	/* timer.  */
          if (args_info->timer_given)
            {
              fprintf (stderr, "%s: `--timer' (`-t') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->timer_given = 1;
          args_info->timer_arg = strtol (optarg,&stop_char,0);
          break;

        case 'v':	/* verbose mode.  */
          if (args_info->verbose_given)
            {
              fprintf (stderr, "%s: `--verbose' (`-v') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->verbose_given = 1;
          args_info->verbose_flag = !(args_info->verbose_flag);
          break;

        case 'x':	/* X offset (X11).  */
          if (args_info->xoffset_given)
            {
              fprintf (stderr, "%s: `--xoffset' (`-x') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->xoffset_given = 1;
          args_info->xoffset_arg = strtol (optarg,&stop_char,0);
          break;

        case 'y':	/* Y offset (X11).  */
          if (args_info->yoffset_given)
            {
              fprintf (stderr, "%s: `--yoffset' (`-y') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->yoffset_given = 1;
          args_info->yoffset_arg = strtol (optarg,&stop_char,0);
          break;

        case 'X':	/* ball initial X value.  */
          if (args_info->initx_given)
            {
              fprintf (stderr, "%s: `--initx' (`-X') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->initx_given = 1;
          args_info->initx_arg = strtol (optarg,&stop_char,0);
          break;

        case 'Y':	/* ball initial Y value.  */
          if (args_info->inity_given)
            {
              fprintf (stderr, "%s: `--inity' (`-Y') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->inity_given = 1;
          args_info->inity_arg = strtol (optarg,&stop_char,0);
          break;

       case 'F':	/* FED file name  */
          if (args_info->filename_given)
            {
              fprintf (stderr, "%s: `--filename' (`-F') option given more than once\n",
                       CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->filename_given = 1;
          args_info->filename_arg = gengetopt_strdup (optarg);
          break;

        case 0:	/* Long option with no short option */

        case '?':	/* Invalid option.  */
          /* `getopt_long' already printed an error message.  */
          exit (EXIT_FAILURE);

        default:	/* bug: option not considered.  */
          fprintf (stderr, "%s: option unknown: %c\n", CMDLINE_PARSER_PACKAGE, c);
          abort ();
        } /* switch */
    } /* while */


  if (! args_info->federation_given)
    {
      fprintf (stderr, "%s: '--federation' ('-f') option required\n", CMDLINE_PARSER_PACKAGE);
      missing_required_options = 1;
    }
  if (! args_info->name_given)
    {
      fprintf (stderr, "%s: '--name' ('-n') option required\n", CMDLINE_PARSER_PACKAGE);
      missing_required_options = 1;
    }
  if (! args_info->filename_given)
    {
      fprintf (stderr, "%s: '--filename' ('-F') option required\n", CMDLINE_PARSER_PACKAGE);
      missing_required_options = 1;
    }
  if ( missing_required_options )
    exit (EXIT_FAILURE);

  return 0;
}
Esempio n. 6
0
int
main(int argc, const char **argv)
{
	struct commandline cmd;

	memset(&cmd, 0, sizeof (struct commandline));
	clear_args();
	if (!parseargs(argc, argv, &cmd))
		usage();
	/*
	 * Only the client and server side stubs are likely to be customized,
	 *  so in that case only, check if the outfile exists, and if so,
	 *  print an error message and exit.
	 */
	if (cmd.Ssflag || cmd.Scflag || cmd.makefileflag)
		checkfiles(cmd.infile, cmd.outfile);
	else
		checkfiles(cmd.infile, NULL);

	if (cmd.cflag) {
		c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile);
	} else if (cmd.hflag) {
		h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile,
		    cmd.hflag);
	} else if (cmd.lflag) {
		l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile);
	} else if (cmd.sflag || cmd.mflag || (cmd.nflag)) {
		s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND,
			cmd.outfile, cmd.mflag, cmd.nflag);
	} else if (cmd.tflag) {
		t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile);
	} else if  (cmd.Ssflag) {
		svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND,
			cmd.outfile);
	} else if (cmd.Scflag) {
		clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND,
			    cmd.outfile);
	} else if (cmd.makefileflag) {
		mkfile_output(&cmd);
	} else {
		/* the rescans are required, since cpp may effect input */
		c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c");
		reinitialize();
		h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h", cmd.hflag);
		reinitialize();
		l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c");
		reinitialize();
		if (inetdflag || !tirpcflag)
			s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND,
			"_svc.c", cmd.mflag, cmd.nflag);
		else
			s_output(allnc, allnv, cmd.infile, "-DRPC_SVC",
				EXTEND, "_svc.c", cmd.mflag, cmd.nflag);
		if (tblflag) {
			reinitialize();
			t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i");
		}

		if (allfiles) {
			reinitialize();
			svc_output(cmd.infile, "-DRPC_SERVER", EXTEND,
				"_server.c");
			reinitialize();
			clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND,
				"_client.c");

		}
		if (allfiles || (cmd.makefileflag == 1)){
			reinitialize();
			mkfile_output(&cmd);
		}
	}

	exit(nonfatalerrors);
	/* NOTREACHED */
}
Esempio n. 7
0
bool cli_command_format::run_command(cmd_line *cmd_ptr, std::queue<std::string> args, bool &done)
{
    clear_args();

    bool args_ok = true;
    size_t m_i = 0;
    int match_count = 0;
    int total_matched = 0;
    while (args.size() && (m_i < m_args.size()) && args_ok)
    {
        bool ok = m_args[m_i]->set_value(args.front());

        const int match_max = m_args[m_i]->get_match_max();
        const int match_min = m_args[m_i]->get_match_min();
        if (ok)
        {
            args.pop();
            match_count++;
            total_matched++;

            if ((match_max != UINT_MAX) && (match_count >= match_max))
            {
                // Move to next argument - completed this one
                m_i++;
                match_count = 0;
            }
        }
        else if (match_count >= match_min)
        {
            // Move to next argument - matched enough of this one
            m_i++;
            match_count = 0;
        }
        else
        {
            args_ok = false;
        }
    }

    if (args.size())
    {
        // Unused arguments left
        args_ok = false;
    }

    while (m_i < m_args.size() && args_ok)
    {
        if (m_args[m_i]->get_match_min() > m_args[m_i]->get_all_value_count())
        {
            // Left over arguments that are not optional
            args_ok = false;
        }
        m_i++;
    }

    if (args_ok && m_action)
    {
        done = ((cmd_ptr->*(m_action))(total_matched, m_args) != 0);
        return true;
    }

    return false;
}
Esempio n. 8
0
void check_redir(void)
{
	/* Arguments:
			none
		
		Purpose:
			analyzes args for possible redirection and handles
			any if found.
			
			this will be called after a fork()	but before an execvp() 
			so that fash's file descriptors are unchanged
	*/
	if(strstr(line,"<") || strstr(line,">")) { //do work if there exists a < or >
		int i =0;
		int fd;
		char *arg = (char*)malloc(sizeof(char)*100);
		char *fName = (char*)malloc(sizeof(char) * 100);
		memset(fName,0,100);
		memset(arg,0,100);
		//char *pArg;
		arg = args[i];
		//pArg = arg;
		while(arg != NULL) {
			//lets check  all the cases
			if(arg[0] == '>') {
				//want to redirect stdout
				if(arg[1] == '\0') {
					// next argument is the file name
					strcpy(args[i], ""); //we dont want this in the arg list
					strcpy(fName, args[++i]);
					strcpy(args[i], ""); //user will have to play nice and not do 2 things w/o space		
					fd = open(fName, O_WRONLY | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH);
				} else if((arg[1] >= 65 && arg[1] <= 90) || (arg[1] >= 97 && arg[1] <= 122)) {
					// next part of this argument is the file name
					strcpy(fName, arg+1);
					strcpy(args[i], ""); //remove from args list		
					fd = open(fName, O_WRONLY | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH);
				} else if(arg[1] == '>') {
					//want to redirect and append to stdout
					if(arg[2] == '\0') {
						//next argument is file name
						strcpy(args[i], ""); //we dont want this in the arg list
						strcpy(fName, args[++i]);
						strcpy(args[i], ""); //user will have to play nice and not do 2 things w/o space		
						fd = open(fName, O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH);
					} else if((arg[2] >= 65 && arg[2] <= 90) || (arg[2] >= 97 && arg[2]<= 122)) {
						//rest of this argument is the filename
						strcpy(fName, arg+2);
						strcpy(args[i], ""); //remove from args list		
						fd = open(fName, O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH);
					}
				}				
				//now do redirection if open was successful
				if(fd < 0) {
					//error opening file
					char *tmp = (char*)malloc(sizeof(char)*100);
					memset(tmp,0,100);
					sprintf(tmp,"fash: %s: No such file or directory\n", fName);
					write(1,tmp,strlen(tmp));
					free(tmp);
					return;
				}
				dup2(fd, 1);
				close(fd);
			} else if(arg[0] == '<') {
				//want to redirect stdin
				if(arg[1] == '\0') {
					//next argument is file name
					strcpy(args[i], ""); //we dont want this in the arg list
					strcpy(fName, args[++i]);
					strcpy(args[i], ""); //user will have to play nice and not do 2 things w/o space		
					fd = open(fName, O_RDONLY);
				} else if((arg[1] >= 65 && arg[1] <= 90) || (arg[1] >= 97 && arg[1] <= 122)) {
					//rest of this argument is file name
					strcpy(fName, arg+1);
					strcpy(args[i], ""); //remove from args list		
					fd = open(fName, O_RDONLY);
				}
				if(fd < 0) {
					//error opening file
					char *tmp = (char*)malloc(sizeof(char)*100);
					memset(tmp,0,100);
					sprintf(tmp,"fash: %s: No such file or directory\n", fName);
					write(1,tmp,strlen(tmp));
					free(tmp);
					return;
				}
				//now do redirection
				close(0);
				dup(fd);
				close(fd);
			}		
			++i;
			arg = args[i];
		}
		
		//since we've removed some "arguments" we need
		//to rebuild the new command line and reparse
		char *s;
		s = args[0];
		i = 1;
		memset(line,0,100);
		while(s!=NULL) {
			strcat(line,s);
			strcat(line, " ");
			s = args[i];
			++i;
		}
		clear_args();
		parse_args(line);
		
		//cleanup
		free(arg);
		free(fName);
	}
}
Esempio n. 9
0
int check_pipe(char *line)
{
	/* Arguments:
			none
		
		Purpose:
			first looks for '|' character in the command line
			
			if it doesnt find one, then the function returns,
			if it does find a pipe, it will split the string by
			pipes and run each command in order, doing the
			correct piping to/from different commands
			
		Returns:
			0 - if the line contains a | character
			1 - if this function has handled the command
	*/
	if(!strchr(line,(int)'|')){ return 0;}
	
	char *pipes[100]; //= (char*)malloc(sizeof(char)*100);
	int numPipes = 0;
	
	//split by pipes
	int i;
	int x = strlen(line);
	char *tmp = (char*)malloc(sizeof(char)*100);
	memset(tmp,0,100);
	int pos = 0;
	for(i = 0; i<x; ++i) {
		if(line[i] == '|') {
			//add the subline to our pipes array
			strncat(tmp,"\0",1);
			pipes[numPipes] = (char *)malloc(sizeof(char)*100);
			memset(pipes[numPipes],0,100);
			strcpy(pipes[numPipes],tmp);
			memset(tmp,0,100);
			++numPipes;
			pos = 0;
		} else {
			//build the line
			tmp[pos] = line[i];
			++pos;
		}
	}
	//add the last substring
	strncat(tmp,"\0",1);
	pipes[numPipes] = (char *)malloc(sizeof(char)*100);
	memset(pipes[numPipes],0,100);
	strcpy(pipes[numPipes],tmp);

	//loop through each command
	//quit_raw_mode();
	for(i = 0; i<=numPipes;++i) {
		parse_args(pipes[i]); //parse the subcom
		if(i == 0){
			//first pipe command
			pipe_execute(args[0], 1);
		}
		else if(i > 0 && i != numPipes) {
			//in a middle pipe command
			pipe_execute(args[0], 2);
		}
		else if(i == numPipes) {
			//end pipe command
			pipe_execute(args[0], 0);
		}
		clear_args(); //clear subcom args
	}
		system("rm -f pipe"); //destroy the pipe
		system("rm -f pipe_middle");
	//tty_raw_mode();
	return 1;
}
Esempio n. 10
0
void exec_history(char* cmd)
{
	/* Arguments:
			cmd = ![number]
		
		Purpose:
			executes the command in history
			specified by the # in history 
			
			Example:
				!13 -- executes history #13 if
					it exists
				
				! -- executes the last command
	*/
	++cmd; //removes ! char
	int hisNum = atoi(cmd); //converts string number to int
	if(strlen(cmd) == 0) { hisNum = historyInd; } //if they provide no number, run most recent
	if(hisNum == 0) { 
		//some error
		char *tmp = (char*)malloc(sizeof(char) * 40);
		memset(tmp,0,40);
		sprintf(tmp, "-fritzbash: !%s: not a valid event\n", cmd);
		write(1,tmp,strlen(tmp));
		free(tmp);
		return;
	}
	char *tmp = (char*)malloc(sizeof(char) * 100);
	memset(tmp,0,100);
	if(hisNum > historyInd || hisNum < 0) { 
		//if they request a negative command or one that
		// "hasn't" happened yet
		char *tmp = (char*)malloc(sizeof(char) * 40);
		memset(tmp,0,40);
		sprintf(tmp, "-fritzbash: !%i: event not found\n", hisNum);
		write(1,tmp,strlen(tmp));
		free(tmp);
	} else {			
		if(hisNum <= (int)(historyInd/2)) {
			//go forward through linked list
			int x = 0;
			struct HistoryList *cur = historyHead; 
			for(;x<hisNum-1;++x) {
				cur = cur->next;	//next node			
			}
			strncpy(tmp,cur->data,strlen(cur->data)); //copy command
		} else {
			//go backward through linked list
			int x = 0;
			int y = historyInd-hisNum;
			struct HistoryList *cur = historyHead->prev; //start at end
			for(;x<y;++x) {
				cur = cur->prev; //go back
			}
			strncpy(tmp,cur->data,strlen(cur->data)); //copy command		
		}
		//now prepare to send to execute
		char *tmp2 = (char*)malloc(sizeof(char) * 100);
		memset(tmp2,0,100);
		sprintf(tmp2,"%s\n",tmp); //print the command they chose
		write(1,tmp2,strlen(tmp2));
		clear_args(); //clear all old arguments
		parse_args(tmp); //reparse this old command
		add_history(tmp); //this is what goes into history
		execute(args[0]); //arg[0] is the command itself
		free(tmp);
	}
	
}
Esempio n. 11
0
int cmdline_parser( int argc, char * const *argv, struct gengetopt_args_info *args_info ) {
	/* Character of the parsed option.  */
	int c;
	/* Tmd retval */
	int r;
	int missing_required_options = 0;

	args_info->help_given = 0;
	args_info->version_given = 0;
	args_info->user_given = 0;
	args_info->pass_given = 0;
	args_info->remuser_given = 0;
	args_info->rempass_given = 0;
	args_info->proxy_given = 0;
	args_info->proxyauth_given = 0;
	args_info->proxyhost_given = 0;
	args_info->proxyport_given = 0;
	args_info->dest_given = 0;
	args_info->remproxy_given = 0;
	args_info->remproxyauth_given = 0;
	args_info->verbose_given = 0;
	args_info->ntlm_given = 0;
	args_info->inetd_given = 0;
	args_info->quiet_given = 0;
	args_info->header_given = 0;
	args_info->domain_given = 0;
	args_info->encrypt_given = 0;
	args_info->encryptproxy_given = 0;
	args_info->encryptremproxy_given = 0;
	args_info->proctitle_given = 0;
	args_info->host_given = 0;

/* No... we can't make this a function... -- Maniac */
#define clear_args() \
{ \
	args_info->user_arg = NULL; \
	args_info->pass_arg = NULL; \
	args_info->remuser_arg = NULL; \
	args_info->rempass_arg = NULL; \
	args_info->domain_arg = NULL; \
	args_info->proxy_arg = NULL; \
	args_info->proxyauth_arg = NULL; \
	args_info->proxyhost_arg = NULL; \
	args_info->dest_arg = NULL; \
	args_info->remproxy_arg = NULL; \
	args_info->remproxyauth_arg = NULL; \
	args_info->header_arg[0] = '\0'; \
	args_info->verbose_flag = 0; \
	args_info->ntlm_flag = 0; \
	args_info->inetd_flag = 0; \
	args_info->quiet_flag = 0; \
	args_info->standalone_arg = 0; \
	args_info->encrypt_flag = 0; \
	args_info->encryptproxy_flag = 0; \
	args_info->encryptremproxy_flag = 0; \
	args_info->proctitle_arg = NULL; \
	args_info->host_arg = NULL; \
} 

	clear_args();

	optarg = 0;

#ifdef HAVE_GETOPT_LONG
	optind = 1;
	opterr = 1;
	optopt = '?';
#endif

	while (1) {
#ifdef HAVE_GETOPT_LONG
		int option_index = 0;

		/* Struct option: Name, Has_arg, Flag, Value */
		static struct option long_options[] = {
			{ "help",			0, NULL, 'h' },
			{ "version",		0, NULL, 'V' },
			{ "user",			1, NULL, 'u' },
			{ "pass",			1, NULL, 's' },
			{ "domain",			1, NULL, 't' },
//			{ "uservar",		1, NULL, 'U' },
//			{ "passvar",		1, NULL, 'S' },
			{ "passfile",		1, NULL, 'F' },
			{ "proxy",			1, NULL, 'p' },
			{ "proxyauth",		1, NULL, 'P' },
			{ "dest",			1, NULL, 'd' },
			{ "remproxy",		1, NULL, 'r' },
			{ "remproxyauth",	1, NULL, 'R' },
			{ "proctitle",		1, NULL, 'x' },
			{ "host",		1, NULL, 'o' },
			{ "header",			1, NULL, 'H' },
			{ "verbose",		0, NULL, 'v' },
			{ "ntlm",			0, NULL, 'N' },
			{ "inetd",			0, NULL, 'i' },
			{ "standalone", 	1, NULL, 'a' },
			{ "quiet",			0, NULL, 'q' },
			{ "encrypt",		0, NULL, 'e' },
			{ "encrypt-proxy",	0, NULL, 'E' },
			{ "encrypt-remproxy",0,NULL, 'X' },
			{ NULL,				0, NULL, 0 }
		};

		c = getopt_long (argc, argv, "hVia:u:s:t:F:p:P:r:R:d:H:x:nvNeEXqo:", long_options, &option_index);
#else
		c = getopt( argc, argv, "hVia:u:s:t:F:p:P:r:R:d:H:x:nvNeEXqo:" );
#endif

		if (c == -1)
			break;	/* Exit from `while (1)' loop.  */

		switch (c) {
			case 'h':	/* Print help and exit.  */
				clear_args ();
				cmdline_parser_print_help ();
				exit(0);

#ifdef USE_SSL
			case 'e':       /* Turn on SSL encryption */
				args_info->encrypt_flag = !(args_info->encrypt_flag);
				if( args_info->verbose_flag )
					message("SSL enabled\n");
				break;

			case 'E':	/* Turn on client to proxy SSL encryption */
				args_info->encryptproxy_flag = !(args_info->encryptproxy_flag);
				if( args_info->verbose_flag )
					message("SSL client to proxy enabled\n");
				break;
#endif

			case 'i':	/* Run from inetd. */
				if ( args_info->standalone_arg > 0 ) {
					fprintf( stderr, "%s: '--inetd' ('-i') conflicts with '--standalone' ('-a')\n", PACKAGE );
					clear_args();
					exit( 1 );
				}
				args_info->inetd_flag = !(args_info->inetd_flag);
				break;

			case 'a':       /* Run as standalone daemon */
				if ( args_info->inetd_flag ) {
					fprintf( stderr, "%s: `--standalone' (`-a') conflicts with `--inetd' (`-i')\n", PACKAGE );
					clear_args();
					exit(1);
				}
				if ( ( args_info->standalone_arg = atoi( optarg ) ) < 1 ) {
					fprintf( stderr, "%s: Illegal port value for `--standalone' (`-a')\n", PACKAGE);
					clear_args();
					exit(1);
				}
				break;

			case 'V':	/* Print version and exit.  */
				clear_args ();
				cmdline_parser_print_version ();
				exit(0);

			case 'x':
				args_info->proctitle_given = 1;
				message( "Proctitle override enabled\n" );
				args_info->proctitle_arg = gengetopt_strdup (optarg);
				break;

			case 'o':
				args_info->host_given = 1;
				/* message( "Host-header override enabled\n" ); */
				args_info->host_arg = gengetopt_strdup (optarg);
				break;

			case 'u':	/* Username to send to HTTPS proxy for authentication.  */
				if (args_info->user_given) {
					fprintf (stderr, "%s: `--user' (`-u'), `--proxyauth' (`-P') or `--passfile' (`-F') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->user_given = 1;
				args_info->user_arg = gengetopt_strdup (optarg);
				message ("Option -u/--user is deprecated, please use -P/--proxyauth user:pass\n");
				break;


			case 's':	/* Password to send to HTTPS proxy for authentication.  */
				if (args_info->pass_given) {
					fprintf (stderr, "%s: `--pass' (`-s') or `--passfile' (`-F') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->pass_given = 1;
				args_info->pass_arg = gengetopt_strdup (optarg);
				message ("Option -s/--pass is deprecated, please use -P/--proxyauth user:pass\n");
				break;

			case 't':	/* Env Var with NTLM DOMAIN (when overriding).  */
				if (args_info->domain_given) {
					fprintf (stderr, "%s: `--domain' (`-t') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->domain_given = 1;
				args_info->domain_arg = gengetopt_strdup (optarg);
				break;

			case 'F':  /* File containing Username & Password to send to
							HTTPS proxy for authentication.  */
				if (args_info->user_given) {
					fprintf (stderr, "%s: `--user' (`-u') or `--passfile' (`-F') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				if (args_info->pass_given) {
					fprintf (stderr, "%s: `--pass' (`-s') or `--passfile' (`-F') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				char *result = getCredentialsFromFile(optarg, &(args_info->user_arg), &(args_info->pass_arg), &(args_info->remuser_arg), &(args_info->rempass_arg) );
				if ( args_info->user_arg != NULL )
					args_info->user_given = 1;
				if ( args_info->pass_arg != NULL )
					args_info->pass_given = 1;
				if ( args_info->remuser_arg != NULL )
					args_info->remuser_given = 1;
				if ( args_info->rempass_arg != NULL )
					args_info->rempass_given = 1;

				if( result != NULL ) {
					fprintf( stderr, "%s: Bad password file for `--passfile' (`-F')\n%s\n", PACKAGE, result);
					clear_args();
					exit(1);
				}
				break;

			case 'p':       /* HTTPS Proxy host:port to connect to.  */
				if (args_info->proxy_given) {
					fprintf (stderr, "%s: `--proxy' (`-p') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->proxy_given = 1;
				args_info->proxy_arg = gengetopt_strdup (optarg);
				break;

			case 'P':       /* HTTPS Proxy auth user:pass for local proxy */
				if (args_info->proxyauth_given) {
					fprintf (stderr, "%s: `--proxyauth' (`-P') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->proxyauth_given = 1;
				args_info->proxyauth_arg = gengetopt_strdup (optarg);
				break;

			case 'r':       /* Use a remote proxy */
				if (args_info->remproxy_given) {
					fprintf (stderr, "%s: `--remproxy' (`-r') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->remproxy_given = 1;
				args_info->remproxy_arg = gengetopt_strdup (optarg);
				break;

			case 'R':       /* HTTPS Proxy auth user:pass for remote proxy */
				if (args_info->remproxyauth_given) {
					fprintf (stderr, "%s: `--remproxyauth' (`-P') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->remproxyauth_given = 1;
				args_info->remproxyauth_arg = gengetopt_strdup (optarg);
				break;

			case 'X':   /* Turn on local to remote proxy SSL encryption */
				args_info->encryptremproxy_flag = !(args_info->encryptremproxy_flag);
				if( args_info->verbose_flag )
					message("SSL local to remote proxy enabled\n");
				break;


			case 'd':	/* Destination host to built the tunnel to.  */
				if (args_info->dest_given) {
					fprintf (stderr, "%s: `--dest' (`-d') option given more than once\n", PACKAGE);
					clear_args ();
					exit(1);
				}
				args_info->dest_given = 1;
				args_info->dest_arg = gengetopt_strdup (optarg);
				break;

			case 'H':	/* Extra headers to send to HTTPS proxy. */
				args_info->header_given++;
				strzcat( args_info->header_arg, "%s\r\n", optarg);
				break;

			case 'v':	/* Turn on verbosity.  */
				if (args_info->quiet_flag) {       /* -q also on cmd line */
					fprintf (stderr, "-v and -q are mutually exclusive\n");
					clear_args();
					exit(1);
				}
				args_info->verbose_flag = !(args_info->verbose_flag);
				break;

			case 'N':	/* Turn on NTLM.  */
				args_info->ntlm_flag = !(args_info->ntlm_flag);
				break;

			case 'q':	/* Suppress messages -- Quiet mode */
				args_info->quiet_flag = !(args_info->quiet_flag);
				break;

			case 0:	/* Long option with no short option */

			case '?':	/* Invalid option.  */
				/* `getopt_long' already printed an error message.  */
				clear_args();
				exit(1);

			default:	/* bug: option not considered.  */
				fprintf (stderr, "%s: option unknown: %c\n", PACKAGE, c);
				clear_args();
				abort();
		} /* switch */
	} /* while */

/* For Windows quiet is the default output. -- Dag */
#ifdef CYGWIN
	if (! args_info->verbose_flag ) {
		args_info->quiet_flag = 1;
	}
#endif

/* Get credentials from environment. -- Dag */
	char *tmp = NULL;
	if ( args_info->user_arg == NULL ) {
		if ( (tmp = getenv("PROXYUSER")) != NULL) {
			args_info->user_given = 1;
			args_info->user_arg = gengetopt_strdup (tmp);
			if( args_info->verbose_flag )
				message( "Found user '%s' in env variable PROXYUSER.\n", args_info->user_arg);
		}
	}
	if ( args_info->pass_arg == NULL ) {
		if ( (tmp = getenv("PROXYPASS")) != NULL ) {
			args_info->pass_given = 1;
			args_info->pass_arg = gengetopt_strdup (tmp);
			if( args_info->verbose_flag )
				message( "Found password in env variable PROXYPASS.\n", args_info->pass_arg);
		}
	}
	if ( args_info->remuser_arg == NULL ) {
		if ( (tmp = getenv("REMPROXYUSER")) != NULL ) {
			args_info->remuser_given = 1;
			args_info->user_arg = gengetopt_strdup (tmp);
			if( args_info->verbose_flag )
				message( "Found remote user '%s' in env variable REMPROXYPASS.\n", args_info->remuser_arg);
		}
	}
	if ( args_info->rempass_arg == NULL ) {
		if ( (tmp = getenv("REMPROXYPASS")) != NULL ) {
			args_info->rempass_given = 1;
			args_info->user_arg = gengetopt_strdup (tmp);
			if( args_info->verbose_flag )
				message( "Found remote password in env variable REMPROXYPASS.\n" );
		}
	}

	if ( args_info->proxy_arg == NULL ) {
		if ( ((tmp = getenv("http_proxy")) != NULL) || ((tmp = getenv("HTTP_PROXY")) != NULL) ) {
			int r;
			char * temp;
			temp = malloc( 56+1 );
			r = sscanf( tmp, "http://%56[^/]/", temp );
//			message( "r = '%d'\ntemp = '%s'\n", r, temp);

			args_info->proxy_given = 1;
			args_info->proxy_arg = gengetopt_strdup (temp);
			if( args_info->verbose_flag )
				message( "Proxy info found using env variable HTTP_PROXY (%s).\n", args_info->proxy_arg);
		}
	}

	if (! args_info->proxy_given && ! args_info->dest_given ) {
		clear_args ();
//		cmdline_parser_print_help ();
		message( "No proxy or destination given, exiting\nUse '--help' flag for usage info\n" );
		exit(1);
	}

	if (args_info->proxy_given ) {
		char * phost;
		int pport;

		phost = malloc( 50+1 );

		r = sscanf( args_info->proxy_arg, "%50[^:]:%5u", phost, &pport );
		if ( r == 2 ) {
			args_info->proxyhost_arg = phost;
			args_info->proxyport_arg = pport;
			args_info->proxyhost_given = 1;
			args_info->proxyport_given = 1;
		} else {
			message( "parse_cmdline: could not find your proxy hostname/ip (%s)\n", args_info->proxy_arg );
			missing_required_options++;
		}
	}

	/* Parse -P/--proxyauth information */
	if (args_info->proxyauth_given ) {
		char *puser = NULL;
		char *ppass = NULL;

		puser = malloc( 24+1 );
		ppass = malloc( 24+1 );

		r = sscanf( args_info->proxyauth_arg, "%24[^:]:%24s", puser, ppass );
		if ( r == 2 ) {
			args_info->user_arg = puser;
			args_info->pass_arg = ppass;
			args_info->user_given = 1;
			args_info->pass_given = 1;
		} else if ( r == 1 ) {
			args_info->user_arg = args_info->proxyauth_arg;
			args_info->user_given = 1;
		} else {
			message( "parse_cmdline: could not find your proxy auth user/pass\n" );
			missing_required_options++;
		}
	}

	/* Parse -R/--remproxyauth information */
	if (args_info->remproxyauth_given ) {
		char *ruser = NULL;
		char *rpass = NULL;

		ruser = malloc( 24+1 );
		rpass = malloc( 24+1 );

		r = sscanf( args_info->remproxyauth_arg, "%24[^:]:%24s", ruser, rpass );
		if ( r == 2 ) {
			args_info->remuser_arg = ruser;
			args_info->rempass_arg = rpass;
			args_info->remuser_given = 1;
			args_info->rempass_given = 1;
		} else if ( r == 1 ) {
			args_info->remuser_arg = args_info->remproxyauth_arg;
			args_info->remuser_given = 1;
		} else {
			message( "parse_cmdline: could not find your proxy auth user/pass\n" );
			missing_required_options++;
		}
	}
	if ( missing_required_options )
		exit(1);

	return 0;
}
Esempio n. 12
0
int
main(int argc, char **argv)
{
	struct commandline cmd;

	(void) memset((char *) &cmd, 0, sizeof(struct commandline));
	clear_args();
	if (!parseargs(argc, argv, &cmd))
		usage();

	if (cmd.cflag || cmd.hflag || cmd.lflag || cmd.tflag || cmd.sflag ||
		cmd.mflag || cmd.nflag || cmd.Ssflag || cmd.Scflag) {
		checkfiles(cmd.infile, cmd.outfile);
	} else
		checkfiles(cmd.infile, NULL);

	if (cmd.cflag) {
		c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile);
	} else if (cmd.hflag) {
		h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile);
	} else if (cmd.lflag) {
		l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile);
	} else if (cmd.sflag || cmd.mflag || (cmd.nflag)) {
		s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND,
			cmd.outfile, cmd.mflag, cmd.nflag);
	} else if (cmd.tflag) {
		t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile);
	} else if (cmd.Ssflag) {
		svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND, cmd.outfile);
	} else if (cmd.Scflag) {
		clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND, cmd.outfile);
	} else {
		/* the rescans are required, since cpp may effect input */
		c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c");
		reinitialize();
		h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h");
		reinitialize();
		l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c");
		reinitialize();
		if (inetdflag || !tirpcflag)
			s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND,
				"_svc.c", cmd.mflag, cmd.nflag);
		else
			s_output(allnc, allnv, cmd.infile, "-DRPC_SVC",
				EXTEND, "_svc.c", cmd.mflag, cmd.nflag);
		if (tblflag) {
			reinitialize();
			t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i");
		}
		if (allfiles) {
			reinitialize();
			svc_output(cmd.infile, "-DRPC_SERVER", EXTEND, "_server.c");
		}
		if (allfiles) {
			reinitialize();
			clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND, "_client.c");
		}
	}
	exit(nonfatalerrors);
	/* NOTREACHED */
}
Esempio n. 13
0
int main(int argc, char *argv[], char *envp[])
{
	read_config(); //read the config file
	char c; //reading one letter at time here
	
	//building a command line which will eventually get parsed
	line = (char *)malloc(sizeof(char) * 100); 
	memset(line,0,100);
	char *cmd = (char *)malloc(sizeof(char) * 100); //the program (command w/o args)
	char *printBuff = (char *)malloc(sizeof(char)*100); //a printing buffer (for use with raw tty)
	
	//holder for history if stuff is typed, then history is used to go back to typed stuff
	char *historyHold = (char *)malloc(sizeof(char)*100); 
	path = (char*)malloc(sizeof(char)*100);
	fullPath = (char*)malloc(sizeof(char)*100);
	memset(printBuff,0,100);
	memset(historyHold,0,100);
	memset(cmd,0,100);
	signal(SIGINT, handle_sig); //register interrupt signal (for CTRL+C)
	int promptLen; //making sure we dont backspace the prompt
	int fromHistory = 0; //a type of check to see if our line is from history (not user typed)
	
	if(fork() == 0) {
		execve("/usr/bin/clear", argv, envp); //simply clear the screen
		exit(1);
	}
	else {
		wait(NULL); //wait to clear screen
	}
	get_path(); //gets the 2dir path for prompt
	tty_raw_mode();//set terminal into raw mode	
	sprintf(printBuff,"%s:%s",path,PROMPT); //build print buff
	promptLen = strlen(printBuff);
	curPos = promptLen; //leave a space
	write(1,printBuff,promptLen); //print initial prompt
	memset(printBuff,0,100); //clear printBuff
	clear_args(); //just get any initial crap out
	
	/* MAIN LOOP */
	while(1) {
		read(0,&c,1); //read 1 character from stdin
		if(((c >= 32) && c!=127) || c == 10) { 
			//here, we only want to process characters that are
			//"readable" (or enter). special characters will be
			//handled differently
			tabPressNo = 0; //they didnt press tab
			write(1,&c,1); //write char (echo is off for raw mode)
			++curPos;
			switch(c) {
				case '\n': //end of the line (enter was pressed after input)
					if(line[0] == '\0') { 
						//they didnt type anything
						sprintf(printBuff,"%s:%s",path,PROMPT);
						write(1,printBuff,promptLen); 
					} 
					else if(strcmp(line,"exit")==0) {
						printf("\n"); //for niceness
						quit_raw_mode(); //play nice and restore term state
						return 0; //quit if they type "exit"
					}
					else { //prepare to actually process						
						strncat(line,"\0",1);
						if(line[0] != '!') {
							add_history(line); //add command to history
						}	
						int pipe = 0;
						int separ = check_separ(line);
						if(!separ){
							pipe = check_pipe(line);					
						}
						if(!separ && !pipe){ //try to execute the command if there werent pipes or semicolons
							parse_args(line); //build array of arguments
							strcpy(cmd, args[0]); //cmd = program to run
							execute(cmd);
							clear_args(); //resets all arg array strings
						}
						c = '\0';
						memset(cmd, 0, 100); //clear the cmd array
						//reprint prompt
						sprintf(printBuff,"%s:%s",path,PROMPT);
						promptLen = strlen(printBuff);
						curPos = promptLen;
						write(1,printBuff,promptLen);						
					}
					memset(line,0,100); //clear line array
					memset(historyHold,0,100);//clear history hold
					break;
				default: strncat(line, &c, 1);//build the line
					break;
			}
		}
		else if(c == 8) {
			//backspace pressed
			if(curPos > promptLen) {
				backspace(); //backspace until we reach prompt
				line[strlen(line)-1] = 0; //thank god this finally works
				--curPos;
			}
		}
		else if(c == 27) {
			//the user pressed some sort of
			//escape sequence
			char c1;
			char c2;
			read(0,&c1,1);
			read(0,&c2,1);
			
			//ok, we have the two parts of the 
			//escape sequence in c1 and c2
			if(c1 == 91 && c2 == 65) {
				//this is the escape for the up arrow
				//which we want to use for history 
				//browsing
				char *tmpLine;
				tmpLine = prev_history();
				if(tmpLine != 0) {
					if(line[0] != '\0' && fromHistory==0) {
						//store what user currently has typed (if anything)
						memset(historyHold,0,100);
						strncpy(historyHold,line,strlen(line)); 
					}
					clear_line(strlen(line)); //clears whatever is at the prompt
					memset(line,0,100);
					strncpy(line,tmpLine,strlen(tmpLine)); //copy this command
					free(tmpLine); //play nice
					write(1,line,strlen(line)); //write old command
					fromHistory = 1; //current line has been replaced by history
					curPos = strlen(line) + promptLen; //so we know where are
				}
			}
			else if(c1 == 91 && c2 == 66) {
				//this is the escape for the down arrow
				//which should make us go "forward"
				//in history (if we are back in it)
				char *tmpLine;
				tmpLine = next_history(); //get the next history
				if(tmpLine != 0) {
					//next_history gave us a line
					clear_line(strlen(line)); //clear old line from screen
					memset(line,0,100); //clear old line in mem
					strncpy(line,tmpLine,strlen(tmpLine)); //copy new line to old line
					write(1,line,strlen(line)); //write new line to screen
					curPos = strlen(line) + promptLen; //update pos
					free(tmpLine);
				}
				else if(historyHold[0] != '\0') {
					//if we dont have a next_line, lets see if
					//we had some buffer before browsing history
					clear_line(strlen(line));
					memset(line,0,100);					
					strncpy(line,historyHold,strlen(historyHold));
					write(1,line,strlen(line));
					curPos = strlen(line) +promptLen;
					fromHistory = 0; //back to user typed
				}
				else {
					//it was blank before history was browsed
					clear_line(strlen(line));
					memset(line,0,100);
					curPos = promptLen;
				}
			}
		}
		else if(c == '\t') {
			//tab press. should i dare try to do tab
			//completion? i guess...
			
			//if this is the 2nd time in a row pressing tab
			//they want a listing of everything that can be
			//completed
			if(tabPressNo) {
				//print everything in tabHold
				tabPressNo = 0;
				if(tabCompHold[0] != NULL) {
					int i = 1;
					char *x = tabCompHold[0];
					char *tmp = (char*)malloc(sizeof(char)*100);
					memset(tmp,0,100);
					write(1,"\n",1);
					while(x != NULL) {
						sprintf(tmp,"%s\t",x);
						write(1,tmp,strlen(tmp));
						memset(tmp,0,100);
						x = tabCompHold[i];
						++i;
					}
					write(1,"\n",1);
					//reprint prompt
					sprintf(printBuff,"%s:%s",path,PROMPT);
					promptLen = strlen(printBuff);
					curPos = promptLen + strlen(line);
					write(1,printBuff,promptLen);
					//write the line again
					write(1,line,strlen(line));
					clear_tab_hold();
				}
			} else {
				//otherwise just let tab_complete
				//print a single completion
				char *tabcomp;
				tabcomp = tab_complete(line);
				if(tabcomp != NULL) {
					//tab comp found a single thing, so
					//lets just complete it
					int i = 1;
					char c = tabcomp[0];
					while(c!='\0') {
						write(1,&c,1);
						strncat(line,&c,1);
						c = tabcomp[i];
						++i;
					}
					curPos += strlen(tabcomp); //set our new position
					free(tabcomp);
				}
				++tabPressNo;
			}
		}
		else if(c == '\177') {
			//other form of backspace
			if(curPos > promptLen) {
			backspace(); //backspace until we reach prompt
			line[strlen(line)-1] = 0; //thank god this finally works
			--curPos;
			}			
		}
		memset(printBuff,0,100); //clear printing buffer
	}
	printf("\n"); //for niceness
	quit_raw_mode(); //so we dont get stuck in it
	return 0; //goodbye
}
Esempio n. 14
0
int
cmdline_parser (int argc, char * const *argv, struct gengetopt_args_info *args_info)
{
  int c;	/* Character of the parsed option.  */
  int missing_required_options = 0;

  args_info->help_given = 0 ;
  args_info->version_given = 0 ;
  args_info->from_given = 0 ;
  args_info->to_given = 0 ;
  args_info->output_given = 0 ;
  args_info->algorithm_given = 0 ;
  args_info->char_given = 0 ;
  args_info->sort_given = 0 ;
  args_info->time_given = 0 ;
  args_info->freq_given = 0 ;
  args_info->m1_given = 0 ;
#define clear_args() { \
  args_info->from_arg = gengetopt_strdup("UTF-8") ;\
  args_info->to_arg = gengetopt_strdup("UTF-8") ;\
  args_info->output_arg = NULL; \
  args_info->algorithm_arg = 2 ;\
  args_info->char_flag = 0;\
  args_info->sort_flag = 0;\
  args_info->time_flag = 0;\
  args_info->freq_arg = 1 ;\
  args_info->m1_arg = 1 ;\
}

  clear_args();

  args_info->inputs = NULL;
  args_info->inputs_num = 0;

  optarg = 0;
  optind = 1;
  opterr = 1;
  optopt = '?';

  while (1)
    {
      int option_index = 0;
      char *stop_char;

      static struct option long_options[] = {
        { "help",	0, NULL, 'h' },
        { "version",	0, NULL, 'V' },
        { "from",	1, NULL, 'F' },
        { "to",	1, NULL, 'T' },
        { "output",	1, NULL, 'o' },
        { "algorithm",	1, NULL, 'a' },
        { "char",	0, NULL, 'c' },
        { "sort",	0, NULL, 's' },
        { "time",	0, NULL, 't' },
        { "freq",	1, NULL, 'f' },
        { "m1",	1, NULL, 'm' },
        { NULL,	0, NULL, 0 }
      };

      stop_char = 0;
      c = getopt_long (argc, argv, "hVF:T:o:a:cstf:m:", long_options, &option_index);

      if (c == -1) break;	/* Exit from `while (1)' loop.  */

      switch (c)
        {
        case 'h':	/* Print help and exit.  */
          clear_args ();
          cmdline_parser_print_help ();
          exit (EXIT_SUCCESS);

        case 'V':	/* Print version and exit.  */
          clear_args ();
          cmdline_parser_print_version ();
          exit (EXIT_SUCCESS);

        case 'F':	/* input stream encoding (for character ngram only).  */
          if (args_info->from_given)
            {
              fprintf (stderr, "%s: `--from' (`-F') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->from_given = 1;
          args_info->from_arg = gengetopt_strdup (optarg);
          break;

        case 'T':	/* output stream encoding (for character ngram only).  */
          if (args_info->to_given)
            {
              fprintf (stderr, "%s: `--to' (`-T') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->to_given = 1;
          args_info->to_arg = gengetopt_strdup (optarg);
          break;

        case 'o':	/* write output to file,use stdout if omitted.  */
          if (args_info->output_given)
            {
              fprintf (stderr, "%s: `--output' (`-o') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->output_given = 1;
          args_info->output_arg = gengetopt_strdup (optarg);
          break;

        case 'a':	/* using Nth reduction algorithm.  */
          if (args_info->algorithm_given)
            {
              fprintf (stderr, "%s: `--algorithm' (`-a') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->algorithm_given = 1;
          args_info->algorithm_arg = strtol (optarg,&stop_char,0);
          break;

        case 'c':	/* enter char gram mode, default is word ngram model.  */
          if (args_info->char_given)
            {
              fprintf (stderr, "%s: `--char' (`-c') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->char_given = 1;
          args_info->char_flag = !(args_info->char_flag);
          break;

        case 's':	/* sort result.  */
          if (args_info->sort_given)
            {
              fprintf (stderr, "%s: `--sort' (`-s') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->sort_given = 1;
          args_info->sort_flag = !(args_info->sort_flag);
          break;

        case 't':	/* show time cost by reduction algorithm on stderr (not including I/O).  */
          if (args_info->time_given)
            {
              fprintf (stderr, "%s: `--time' (`-t') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->time_given = 1;
          args_info->time_flag = !(args_info->time_flag);
          break;

        case 'f':	/* frequence threshold needed in algorithm 1,2,4.  */
          if (args_info->freq_given)
            {
              fprintf (stderr, "%s: `--freq' (`-f') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->freq_given = 1;
          args_info->freq_arg = strtol (optarg,&stop_char,0);
          break;

        case 'm':	/* minimum n-gram need in algorithm 4.  */
          if (args_info->m1_given)
            {
              fprintf (stderr, "%s: `--m1' (`-m') option given more than once\n", CMDLINE_PARSER_PACKAGE);
              clear_args ();
              exit (EXIT_FAILURE);
            }
          args_info->m1_given = 1;
          args_info->m1_arg = strtol (optarg,&stop_char,0);
          break;


        case 0:	/* Long option with no short option */

        case '?':	/* Invalid option.  */
          /* `getopt_long' already printed an error message.  */
          exit (EXIT_FAILURE);

        default:	/* bug: option not considered.  */
          fprintf (stderr, "%s: option unknown: %c\n", CMDLINE_PARSER_PACKAGE, c);
          abort ();
        } /* switch */
    } /* while */


  if ( missing_required_options )
    exit (EXIT_FAILURE);

  if (optind < argc)
    {
      int i = 0 ;
  
      args_info->inputs_num = argc - optind ;
      args_info->inputs = 
        (char **)(malloc ((args_info->inputs_num)*sizeof(char *))) ;
      while (optind < argc)
        args_info->inputs[ i++ ] = gengetopt_strdup (argv[optind++]) ; 
    }
  
  return 0;
}