Пример #1
0
Файл: ckl.c Проект: Kami/ckl
int main(int argc, char *const *argv)
{
  int mode = MODE_SEND_MSG;
  int c;
  int rv;
  const char *detail = NULL;
  const char *usermsg = NULL;
  ckl_conf_t *conf = calloc(1, sizeof(ckl_conf_t));

  curl_global_init(CURL_GLOBAL_ALL);

  while ((c = getopt(argc, argv, "hVslm:d:")) != -1) {
    switch (c) {
      case 'V':
        show_version();
        break;
      case 'h':
        show_help();
        break;
      case 'l':
        mode = MODE_LIST;
        break;
      case 'd':
        mode = MODE_DETAIL;
        detail = optarg;
        break;
      case 'm':
        usermsg = optarg;
        break;
      case 's':
        conf->script_mode = 1;
        break;
      case '?':
        ckl_error_out("See -h for correct options");
        break;
    }
  }

  rv = ckl_conf_init(conf);

  if (rv < 0) {
    ckl_error_out("conf_init failed");
  }

  switch (mode) {
    case MODE_SEND_MSG:
      rv = do_send_msg(conf, usermsg);
      break;
    case MODE_LIST:
      rv = do_list(conf);
      break;
    case MODE_DETAIL:
      rv = do_detail(conf, detail);
      break;
  }

  ckl_conf_free(conf);

  curl_global_cleanup();

  return rv;
}
Пример #2
0
int main(int argc, const char *argv[])
{
    try
    {
        CmdArgParser parser(argc, argv);
        parser.setHeader("Archive Export version " ARCH_VERSION_TXT ", "
                         EPICS_VERSION_STRING
                         ", built " __DATE__ ", " __TIME__ "\n\n");
        parser.setArgumentsInfo("<index file> {channel}");
        CmdArgFlag   be_verbose (parser, "verbose", "Verbose mode");
        CmdArgString pattern    (parser, "match", "<reg. exp.>",
                                 "Channel name pattern");
        CmdArgFlag   do_list    (parser, "list", "List all channels");
        CmdArgFlag   do_info    (parser, "info", "Time-range info on channels");
        CmdArgString start_time (parser, "start", "<time>",
                                 "Format: \"mm/dd/yyyy[ hh:mm:ss[.nano-secs]]\"");
        CmdArgString end_time   (parser, "end", "<time>", "(exclusive)");
        CmdArgFlag   status_text(parser, "text",
                                 "Include text column for status/severity (default)");
        CmdArgFlag   no_status_text(parser, "no_text",
                                 "Exclude text column for status/severity");
        CmdArgString output     (parser,
                                 "output", "<file>", "Output to file");
        CmdArgDouble plotbin    (parser,
                                 "plotbin", "<seconds>",
                                 "Bin the raw data for plotting");
        CmdArgDouble average    (parser,
                                 "average", "<seconds>", "average values");
        CmdArgDouble linear     (parser,
                                 "linear", "<seconds>",
                                 "Interpolate values linearly");
        CmdArgString format_txt (parser,
                                 "format", "<decimal|engineering|exponential>",
                                 "Use specific format for numbers");
        CmdArgInt    prec       (parser,
                                 "precision", "<int>", "Precision of numbers");
        CmdArgFlag   GNUPlot    (parser,
                                 "gnuplot", "Generate GNUPlot command file");
        CmdArgFlag   image      (parser,
                                 "Gnuplot", "Generate GNUPlot output for Image");
        CmdArgFlag   raw_time   (parser, "raw_time",
                                 "Include columns for EPICS time stamp");
        CmdArgFlag   millisecs  (parser, "millisecs",
                                 "Truncate time to millisecs in spreadsheet dump.");
        // defaults
        prec.set(-1);
        if (! parser.parse())
            return -1;
        if (parser.getArguments().size() < 1)
        {
            parser.usage();
            return -1;
        }
        precision = prec;
        if (!strncmp(format_txt.get().c_str(), "d", 1))
            format = RawValue::DECIMAL;
        else if (!strncmp(format_txt.get().c_str(), "en", 2))
            format = RawValue::ENGINEERING;
        else if (!strncmp(format_txt.get().c_str(), "ex", 2))
            format = RawValue::EXPONENTIAL;
        else if (format_txt.get().length() > 0)
        {
            fprintf(stderr, "Unknown format string '%s'\n", format_txt.get().c_str());
            return -1;
        }   
        verbose = be_verbose;
        only_millisecs = millisecs;
        // Start/end time
        AutoPtr<epicsTime> start, end;
        stdString txt;
        if (start_time.get().length() > 0)
        {
            start = new epicsTime;
            if (!string2epicsTime(start_time.get(), *start))
            {
                fprintf(stderr, "Parse error for start time '%s'\n",
                        start_time.get().c_str());
                start = 0;
                parser.usage();
                return -1;
            }
            if (verbose)
                printf("Using start time %s\n", epicsTimeTxt(*start, txt));
        }
        if (end_time.get().length() > 0)
        {
            end = new epicsTime();
            if (!string2epicsTime(end_time.get(), *end))
            {
                fprintf(stderr, "Parse error for end time '%s'\n",
                        end_time.get().c_str());
                end = 0;
                parser.usage();
                return -1;
            }
            if (verbose)
                printf("Using end time   %s\n", epicsTimeTxt(*end, txt));
        }
        if (start && end && *start > *end)
        {   // Could simply swap start and end, but assume the user is
            // confused and should rethink the request.
            fprintf(stderr, "start time is greater than end time.\n");
            return -1;
        }
  
        // Index name
        stdString index_name = parser.getArgument(0);
        // Channel names
        stdVector<stdString> names;
        if (parser.getArguments().size() > 1)
        {
            if (! pattern.get().empty())
            {
                fputs("Pattern from '-m' switch is ignored\n"
                      "since a list of channels was also provided.\n", stderr);
            }
            // first argument was directory file name, skip that:
            for (size_t i=1; i<parser.getArguments().size(); ++i)
                names.push_back(parser.getArgument(i));
        }
        if ((GNUPlot || image) && output.get().length() == 0)
        {
    
            fprintf(stderr, "The -gnuplot/Gnuplot options require "
                    "an -output file\n");
            return -1;    
        }
        // How?
        ReaderFactory::How how = ReaderFactory::Raw;
        double delta = 0.0;
        if (double(plotbin) > 0.0)
        {
            how = ReaderFactory::Plotbin;
            delta = double(plotbin);
        }
        else if (double(average) > 0.0)
        {
            how = ReaderFactory::Average;
            delta = double(average);
        }
        else if (double(linear) > 0.0)
        {
            how = ReaderFactory::Linear;
            delta = double(linear);
        }
        // Open index
        AutoIndex index;
        index.open(index_name.c_str());
        if (verbose)
            printf("Opened index '%s'\n", index_name.c_str());
        if (do_info  &&  names.size()<=0  &&  pattern.get().length()<=0)
            do_list.set(); // otherwise it'd be a NOP
        if (names.size() <= 0 &&
            (do_list  ||  pattern.get().length() > 0))
            get_names_for_pattern(index, names, pattern);
        if (do_info)
            list_channels(index, names, true);
        else if (do_list)
            list_channels(index, names, false);
        else if (names.size() > 0)
        {
            if (GNUPlot || image)
                dump_gnuplot(index, names, start, end,
                             how, delta, output, image);
            else
                dump_spreadsheet(index, names, start, end,
                                 raw_time, !no_status_text, how, delta,
                                 output);
        }
        index.close();
    }
    catch (GenericException &e)
    {
        fprintf(stderr, "Error:\n%s\n", e.what());
        return -1;
    } 
    return 0;
}
Пример #3
0
int main(int argc, char** argv)
{
	
	string_map* parameters = parse_parameters(argc, argv);

	opkg_conf *conf = load_conf((char*)get_string_map_element(parameters, "config"));

	char* run_type                   = get_string_map_element(parameters, "run-type");
	int force_overwrite_other_files  = get_string_map_element(parameters, "force-overwrite")         != NULL ? 1 : 0;
	int force_overwrite_configs      = get_string_map_element(parameters, "force-overwrite-configs") != NULL ? 1 : 0;
	int force_depends                = get_string_map_element(parameters, "force-depends")           != NULL ? 1 : 0;
	int force_reinstall              = get_string_map_element(parameters, "force-reinstall")         != NULL ? 1 : 0;

	int remove_orphaned_depends      = get_string_map_element(parameters, "autoremove")                    != NULL ? REMOVE_ALL_ORPHANED_DEPENDENCIES : REMOVE_NO_ORPHANED_DEPENDENCIES;
	remove_orphaned_depends          = get_string_map_element(parameters, "autoremove-same-destination")   != NULL ? REMOVE_ORPHANED_DEPENDENCIES_IN_SAME_DEST : remove_orphaned_depends;

	char* install_root               = get_string_map_element(parameters, "install-destination");
	install_root                     = install_root == NULL ? strdup("root") : install_root;

	char* link_root                  = get_string_map_element(parameters, "link-destination");
	char* tmp_root                   = get_string_map_element(parameters, "tmp_dir");
	tmp_root                         = tmp_root == NULL ? strdup("/tmp") : tmp_root;
	string_map* pkgs                 = get_string_map_element(parameters, "package-list");
	
	char* format_str                 = get_string_map_element(parameters, "output-format");
	int format                       = OUTPUT_HUMAN_READABLE;
	if(format_str != NULL)
	{
		format = strcmp(format_str, "json") == 0 ? OUTPUT_JSON : format;
		format = strcmp(format_str, "js") == 0 || strcmp(format_str, "javascript") == 0 ? OUTPUT_JAVASCRIPT : format;
	}


	


	if(strcmp(run_type, "install") == 0)
	{
		do_install(conf, pkgs, install_root, link_root, 0, force_overwrite_configs, force_overwrite_other_files, force_reinstall, tmp_root);
	}
	else if(strcmp(run_type, "remove") == 0)
	{
		do_remove(conf, pkgs, !force_overwrite_configs, remove_orphaned_depends, force_depends, 1, tmp_root);
	}
	else if(strcmp(run_type, "upgrade") == 0)
	{
		do_upgrade(conf, pkgs, !force_overwrite_configs, install_root, link_root, tmp_root);
	}
	else if(strcmp(run_type, "update") == 0)
	{
		update(conf);
	}
	else if((strcmp(run_type, "list") == 0) || strcmp(run_type, "list-installed") == 0 || strcmp(run_type, "list_installed") == 0)
	{
		do_list(conf, parameters, format);
	}
	else if(strcmp(run_type, "dest-info") == 0 || strcmp(run_type, "dest_info") == 0)
	{
		do_print_dest_info(conf, format);
	}
	else if(strcmp(run_type, "info") == 0)
	{
		do_print_info(conf, parameters, install_root, format);
	}

	return(0);

}
Пример #4
0
int main(int argc, char *argv[]){
    int c;
    u_info user_info;
    const char* action = argv[1];
     user_info.fconf = NULL ;
     user_info.pwd =NULL;
     user_info.gid = 0 ;
     user_info.uid = 0 ;
     user_info.home =NULL;

     if (argc < 2) {
        help();
    }
    
      opterr = 0;
      while ((c = getopt(argc, argv, ":l:u:d:g:f:")) != -1) {
      
        switch(c) {
        case 'l':{
          user_info.login= optarg;
     
          break;
          }
          
        case 'u':{
         user_info.uid = (uid_t)strtoul(optarg, NULL, 10);
         
            break;
            }
        case 'd':{
         user_info.home = optarg;
     
            break;
            }
        case 'g':{
            user_info.gid =(gid_t) strtoul(optarg, NULL, 10);     
           
            break;
            }
        case 'f':{
          user_info.fconf = optarg;
          break;
          }
          
        case '?':
                 help();
           
        }
    } /*end while*/ 
    
     
  if(user_info.fconf == NULL)
         user_info.fconf = ENV_CONFIG_FILE;    
       
     
    if (strcasecmp(action, "useradd") == 0) {
           
         if(do_check_user(&user_info)){
             printf("User already exists ...\n");
             return 0;
          }              
          do_useradd(&user_info);
           
           
        }
     else if (strcasecmp(action, "usermod") == 0) {
             do_usermod(&user_info);
      
        }        
     else if (strcasecmp(action, "userdel") == 0) {

          if(!(do_check_user(&user_info))){
             printf("This user does not exist ...\n");
             return 0;
          } 
          do_userdel(&user_info);

        }        
     else if (strcasecmp(action, "passwd") == 0) {
             do_passwd(&user_info);
        } 
        
     else if (strcasecmp(action, "show") == 0) {
           do_show(&user_info);
 
     }  

     else if (strcasecmp(action, "list") == 0) {
          do_list(&user_info);
    
    } else {
        help();
    }
        
return 0;
}
Пример #5
0
/*! \brief LIST command handler
 *
 * \param source_p Pointer to allocated Client struct from which the message
 *                 originally comes from.  This can be a local or remote client.
 * \param parc     Integer holding the number of supplied arguments.
 * \param parv     Argument vector where parv[0] .. parv[parc-1] are non-NULL
 *                 pointers.
 * \note Valid arguments for this command are:
 *      - parv[0] = command
 *      - parv[1] = channel name/list options
 */
static int
m_list(struct Client *source_p, int parc, char *parv[])
{
  do_list(source_p, parv[1]);
  return 0;
}
Пример #6
0
void dump_list(const simple_list *list)
{
	do_list(list, list_print2, NULL);
}
Пример #7
0
int do_list(
    char *full_path,
    char *start,
    int fs_id,
    struct options *opts)
{
    int i = 0, printed_dot_info = 0;
    int ret = -1;
    int pvfs_dirent_incount;
    char *name = NULL, *cur_file = NULL;
    PVFS_handle cur_handle;
    PVFS_sysresp_lookup lk_response;
    PVFS_sysresp_readdirplus rdplus_response;
    PVFS_sysresp_getattr getattr_response;
    PVFS_credentials credentials;
    PVFS_object_ref ref;
    PVFS_ds_position token;
    uint64_t dir_version = 0;
    double begin = 0., end;
    subdir *current, *head = NULL, *tail = NULL;

    name = start;

    memset(&lk_response,0,sizeof(PVFS_sysresp_lookup));
    PVFS_util_gen_credentials(&credentials);

    if (opts->list_recursive || opts->num_starts > 1)
    {
        printf("%s%s:\n",full_path,start);
    }

    ret = PVFS_sys_lookup(fs_id, name, &credentials,
                        &lk_response, PVFS2_LOOKUP_LINK_NO_FOLLOW, NULL);
    if(ret < 0)
    {
        PVFS_perror("PVFS_sys_lookup", ret);
        return -1;
    }

    ref.handle = lk_response.ref.handle;
    ref.fs_id = fs_id;
    pvfs_dirent_incount = MAX_NUM_DIRENTS;

    memset(&getattr_response,0,sizeof(PVFS_sysresp_getattr));
    if (PVFS_sys_getattr(ref, PVFS_ATTR_SYS_ALL,
                         &credentials, &getattr_response, NULL) == 0)
    {
        if ((getattr_response.attr.objtype == PVFS_TYPE_METAFILE) ||
            (getattr_response.attr.objtype == PVFS_TYPE_SYMLINK) ||
            ((getattr_response.attr.objtype == PVFS_TYPE_DIRECTORY) &&
             (opts->list_directory)))
        {
            char segment[128] = {0};
            PVFS_sysresp_getparent getparent_resp;
            PINT_remove_base_dir(name, segment, 128);
            if (strcmp(segment,"") == 0)
            {
                snprintf(segment,128,"/");
            }

            if (getattr_response.attr.objtype == PVFS_TYPE_DIRECTORY)
            {
                if (PVFS_sys_getparent(ref.fs_id, name, &credentials,
                                       &getparent_resp, NULL) == 0)
                {
                    print_dot_and_dot_dot_info_if_required(
                        getparent_resp.parent_ref);
                }
            }

            if (opts->list_long)
            {
                print_entry_attr(ref.handle, segment,
                                 &getattr_response.attr, opts);
            }
            else
            {
                print_entry(segment, ref.handle, ref.fs_id, 
                        NULL,
                        0,
                        opts);
            }
            return 0;
        }
    }

    if (do_timing)
        begin = Wtime();
    token = 0;
    do
    {
        memset(&rdplus_response, 0, sizeof(PVFS_sysresp_readdirplus));
        ret = PVFS_sys_readdirplus(
                ref, (!token ? PVFS_READDIR_START : token),
                pvfs_dirent_incount, &credentials,
                (opts->list_long) ? 
                PVFS_ATTR_SYS_ALL : PVFS_ATTR_SYS_ALL_NOSIZE,
                &rdplus_response,
                NULL);
        if(ret < 0)
        {
            PVFS_perror("PVFS_sys_readdir", ret);
            return -1;
        }

        if (dir_version == 0)
        {
            dir_version = rdplus_response.directory_version;
        }
        else if (opts->list_verbose)
        {
            if (dir_version != rdplus_response.directory_version)
            {
                fprintf(stderr, "*** directory changed! listing may "
                        "not be correct\n");
                dir_version = rdplus_response.directory_version;
            }
        }

        if (!printed_dot_info)
        {
            /*
              the list_all option prints files starting with .;
              the almost_all option skips the '.', '..' printing
            */
            print_dot_and_dot_dot_info_if_required(ref);
            printed_dot_info = 1;
        }

        for(i = 0; i < rdplus_response.pvfs_dirent_outcount; i++)
        {
            cur_file = rdplus_response.dirent_array[i].d_name;
            cur_handle = rdplus_response.dirent_array[i].handle;

            print_entry(cur_file, cur_handle, fs_id,
                    &rdplus_response.attr_array[i],
                    rdplus_response.stat_err_array[i],
                    opts);

            PVFS_sys_attr *attr = &rdplus_response.attr_array[i];
            if(attr->objtype == PVFS_TYPE_DIRECTORY && opts->list_recursive)
            {
                int path_len = strlen(start) + strlen(cur_file) + 1;
                current = (subdir *) malloc(sizeof(subdir));

                /* Prevent duplicate slashes in path */
                if(start[strlen(start)-1] == '/')
                {
                    current->path = (char *) malloc(path_len);
                    snprintf(current->path,path_len,"%s%s",start,cur_file);
                }
                else
                {
                    current->path = (char *) malloc(path_len + 1);
                    snprintf(current->path,path_len+1,"%s/%s",start,cur_file);
                }

                /* Update linked list of subdirectories to recurse */
                current->next = NULL;
                if(!head)
                {
                    head = current;
                    tail = current;
                }
                else
                {
                    tail->next = current;
                    tail = current;
                }
            }
        }
        token = rdplus_response.token;

        if (rdplus_response.pvfs_dirent_outcount)
        {
            free(rdplus_response.dirent_array);
            rdplus_response.dirent_array = NULL;
            free(rdplus_response.stat_err_array);
            rdplus_response.stat_err_array = NULL;
            for (i = 0; i < rdplus_response.pvfs_dirent_outcount; i++) {
                if (rdplus_response.attr_array)
                {
                    PVFS_util_release_sys_attr(&rdplus_response.attr_array[i]);
                }
            }
            free(rdplus_response.attr_array);
            rdplus_response.attr_array = NULL;
        }

    } while(rdplus_response.pvfs_dirent_outcount == pvfs_dirent_incount);
    if (do_timing) {
        end = Wtime();
        printf("PVFS_sys_readdirplus took %g msecs\n", 
                (end - begin));
    }

    if (rdplus_response.pvfs_dirent_outcount)
    {
        free(rdplus_response.dirent_array);
        rdplus_response.dirent_array = NULL;
        free(rdplus_response.stat_err_array);
        rdplus_response.stat_err_array = NULL;
        for (i = 0; i < rdplus_response.pvfs_dirent_outcount; i++) {
            if (rdplus_response.attr_array)
            {
                PVFS_util_release_sys_attr(&rdplus_response.attr_array[i]);
            }
        }
        free(rdplus_response.attr_array);
        rdplus_response.attr_array = NULL;
    }

    if (opts->list_recursive)
    {
        current = head;
        while(current)
        {
            printf("\n");
            do_list(full_path,current->path,fs_id,opts);
            current = current->next;
            free(head->path);
            free(head);
            head = current;
        }
    }
    return 0;
}
Пример #8
0
int
main(int argc, char **argv)
{
	rndctl_t rctl;
	int ch, cmd, lflag, mflag, sflag;
	u_int32_t type;
	char name[16];
	const char *filename = NULL;

	rctl.mask = 0;
	rctl.flags = 0;

	cmd = 0;
	lflag = 0;
	mflag = 0;
	sflag = 0;
	type = 0xff;

	while ((ch = getopt(argc, argv, "CES:L:celt:d:s")) != -1) {
		switch (ch) {
		case 'C':
			rctl.flags |= RND_FLAG_NO_COLLECT;
			rctl.mask |= RND_FLAG_NO_COLLECT;
			mflag++;
			break;
		case 'E':
			rctl.flags |= RND_FLAG_NO_ESTIMATE;
			rctl.mask |= RND_FLAG_NO_ESTIMATE;
			mflag++;
			break;
		case 'L':
			if (cmd != 0)
				usage();
			cmd = 'L';
			filename = optarg;
			break;
		case 'S':
			if (cmd != 0)
				usage();
			cmd = 'S';
			filename = optarg;
			break;
		case 'c':
			rctl.flags &= ~RND_FLAG_NO_COLLECT;
			rctl.mask |= RND_FLAG_NO_COLLECT;
			mflag++;
			break;
		case 'e':
			rctl.flags &= ~RND_FLAG_NO_ESTIMATE;
			rctl.mask |= RND_FLAG_NO_ESTIMATE;
			mflag++;
			break;
		case 'l':
			lflag++;
			break;
		case 't':
			if (cmd != 0)
				usage();
			cmd = 't';

			type = find_type(optarg);
			break;
		case 'd':
			if (cmd != 0)
				usage();
			cmd = 'd';

			type = 0xff;
			strlcpy(name, optarg, sizeof(name));
			break;
		case 's':
			sflag++;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	/*
	 * No leftover non-option arguments.
	 */
	if (argc > 0)
		usage();

	/*
	 * Save.
	 */
	if (cmd == 'S') {
		do_save(filename);
		exit(0);
	}

	/*
	 * Load.
	 */
	if (cmd == 'L') {
		do_load(filename);
		exit(0);
	}

	/*
	 * Cannot list and modify at the same time.
	 */
	if ((lflag != 0 || sflag != 0) && mflag != 0)
		usage();

	/*
	 * Bomb out on no-ops.
	 */
	if (lflag == 0 && mflag == 0 && sflag == 0)
		usage();

	/*
	 * If not listing, we need a device name or a type.
	 */
	if (lflag == 0 && cmd == 0 && sflag == 0)
		usage();

	/*
	 * Modify request.
	 */
	if (mflag != 0) {
		rctl.type = type;
		strncpy(rctl.name, name, sizeof(rctl.name));
		do_ioctl(&rctl);

		exit(0);
	}

	/*
	 * List sources.
	 */
	if (lflag != 0)
		do_list(cmd == 0, type, name);

	if (sflag != 0)
		do_stats();

	exit(0);
}
Пример #9
0
int main(int argc, char *argv[])
{
	int rc;
	int opcount = 0;
	int insert_count = 0;
	int delete_count = 0;
	int ncount;
	int done = 0;
	char command[COMMAND + 1];
	int error;

	t = cp_multimap_create_by_option(COLLECTION_MODE_NOSYNC | 
								     COLLECTION_MODE_COPY |
					                 COLLECTION_MODE_DEEP, 
									 Employee_name, 
								     (cp_compare_fn) strcmp, 
									 (cp_copy_fn) Employee_dup, free);
	if (t == NULL)
	{
		perror("create");
		exit(1);
	}

	number_index = 
		cp_multimap_create_index(t, CP_UNIQUE, Employee_number, numcmp, &rc);
	if (number_index == NULL)
	{
		fprintf(stderr, "received error %d\n", rc);
		exit(rc);
	}

	title_index = 
		cp_multimap_create_index(t, CP_MULTIPLE, Employee_title, 
		                         (cp_compare_fn) strcmp, &rc);
	if (title_index == NULL)
	{
		fprintf(stderr, "received error %d\n", rc);
		exit(rc);
	}

	print_command_summary(argv[0]);
	while (!done)
	{
		error = 1;
		printf("> ");
		fgets(command, COMMAND, stdin);
		ltrim(command);
		chomp(command);
		if (strlen(command) == 0) continue;
		if (strcmp(command, "q") == 0 || strcmp(command, "Q") == 0) break;
		if (command[1] == 0x20 || command[1] == '\0')
		{
			error = 0;
			switch (tolower(command[0]))
			{
				case 'a': do_add(command); break;
				case 'd': do_delete(command); break;
				case 'e': do_edit(command); break;
				case 'h': print_command_summary(argv[0]); break;
				case 'k': do_key(command); break;
				case 'l': do_list(command); break;
				default: error = 1;
			}
		}
		if (error)
			printf("unrecognized command: [%s]. Enter 'h' for a list of commands or 'q' to quit.\n", command);
	}

	cp_multimap_destroy(t);
	return 0;
}
Пример #10
0
void CommandParser::executeCommand(int cmd){
	switch(cmd){
		case WRI  :  toAbsolute(first_arg);
					 do_wri(first_arg);     break;
		case LIST :  toAbsolute(first_arg);
					 do_list(first_arg);        break;
		case SHOW :  toAbsolute(first_arg);
					 do_show(first_arg);    break;
		case APP  :  toAbsolute(first_arg);
					 do_app(first_arg);        break;
		case CD   :  do_cd();               break;
		case HELP :  if (strlen(first_arg) == 0)
						do_helpd();
					 else
						do_help(first_arg);
					 break;
		case MKFS :  do_mkfs();             break;
		case REN  :  toAbsolute(first_arg);
					 do_ren(first_arg , second_arg);
					 break;
		case FINFO:  toAbsolute(first_arg);
					 do_info(first_arg);
					 break;
		case LINK :  toAbsolute(first_arg);
					 toAbsolute(second_arg);
					 do_link(first_arg , second_arg);
					 break;
		case QUIT :  do_quit();break;
		case CP   :  toAbsolute(first_arg);
					 toAbsolute(second_arg);
					 do_cp(first_arg , second_arg);
					 break;
		case LOAD :  do_load();
					 break;
		case ULOAD:     do_uload();
					 break;
		case RF   :  toAbsolute(first_arg);
					 do_rf(first_arg);
					 break;
		case RMD  :  toAbsolute(first_arg);
					 do_rmd(first_arg);
					 break;
		case MKD  :  toAbsolute(first_arg);
					 do_mkd(first_arg);
					 break;
		case CHOWN : toAbsolute(first_arg);
					 do_chown(first_arg,second_arg);
					 break ;
		case CHPERM : toAbsolute(first_arg);
					  do_chperm(first_arg,second_arg);
					  break;
		case ADDUSER :
					  do_adduser() ;
					  break;
		case CLS     :
					  clrscr();
					  break;
		case REBOOT  :
					 //
					  break;
		default:
					 if ( strlen(command) )
						 vd_puts("Invalid Command\n");
	}
}
Пример #11
0
int ftp_process_request(struct ftp_session* session, char *buf)
{
	int  fd;
	struct timeval tv;
	fd_set readfds;
	char filename[256];
	int  numbytes;
	char *sbuf;
	char *parameter_ptr, *ptr;
	rt_uint32_t addr_len = sizeof(struct sockaddr_in);
	struct sockaddr_in local, pasvremote;

	sbuf =(char *)rt_malloc(FTP_BUFFER_SIZE);

	tv.tv_sec=3, tv.tv_usec=0;
	local.sin_family=PF_INET;
	local.sin_addr.s_addr=INADDR_ANY;

	/* remove \r\n */
	ptr = buf;
	while (*ptr)
	{
		if (*ptr == '\r' || *ptr == '\n') *ptr = 0;
		ptr ++;
	}

	/* get request parameter */
	parameter_ptr = strchr(buf, ' '); if (parameter_ptr != NULL) parameter_ptr ++;

	// debug:
	rt_kprintf("%s requested: \"%s\"\n", inet_ntoa(session->remote.sin_addr), buf);

	//
	//-----------------------
	if(str_begin_with(buf, "USER")==0)
	{
		rt_kprintf("%s sent login \"%s\"\n", inet_ntoa(session->remote.sin_addr), parameter_ptr);
		// login correct
		if(strcmp(parameter_ptr, "anonymous") == 0)
		{
			session->is_anonymous = RT_TRUE;
			rt_sprintf(sbuf, "331 Anonymous login OK send e-mail address for password.\r\n", parameter_ptr);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else if (strcmp(parameter_ptr, FTP_USER) == 0)
		{
			session->is_anonymous = RT_FALSE;		
			rt_sprintf(sbuf, "331 Password required for %s\r\n", parameter_ptr);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else
		{
			// incorrect login
			rt_sprintf(sbuf, "530 Login incorrect. Bye.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);
			return -1;
		}
		return 0;
	}
	else if(str_begin_with(buf, "PASS")==0)
	{
		rt_kprintf("%s sent password \"%s\"\n", inet_ntoa(session->remote.sin_addr), parameter_ptr);
		if (strcmp(parameter_ptr, FTP_PASSWORD)==0 ||
			session->is_anonymous == RT_TRUE)
		{
			// password correct
			rt_sprintf(sbuf, "230 User logged in\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);			
			return 0;
		}

		// incorrect password
		rt_sprintf(sbuf, "530 Login or Password incorrect. Bye!\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		rt_free(sbuf);		
		return -1;
	}
	else if(str_begin_with(buf, "LIST")==0  )
	{
		memset(sbuf,0,FTP_BUFFER_SIZE);
		rt_sprintf(sbuf, "150 Opening Binary mode connection for file list.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		do_list(session->currentdir, session->pasv_sockfd);
		closesocket(session->pasv_sockfd);
		session->pasv_active = 0;
		rt_sprintf(sbuf, "226 Transfert Complete.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "NLST")==0 )
	{
		memset(sbuf, 0, FTP_BUFFER_SIZE);
		rt_sprintf(sbuf, "150 Opening Binary mode connection for file list.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		do_simple_list(session->currentdir, session->pasv_sockfd);
		closesocket(session->pasv_sockfd);
		session->pasv_active = 0;
		rt_sprintf(sbuf, "226 Transfert Complete.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "PWD")==0 || str_begin_with(buf, "XPWD")==0)
	{
		rt_sprintf(sbuf, "257 \"%s\" is current directory.\r\n", session->currentdir);
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "TYPE")==0)
	{
		// Ignore it
		if(strcmp(parameter_ptr, "I")==0)
		{
			rt_sprintf(sbuf, "200 Type set to binary.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else
		{
			rt_sprintf(sbuf, "200 Type set to ascii.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
	}
	else if(str_begin_with(buf, "PASV")==0)
	{
		int dig1, dig2;
		int sockfd;
		char optval='1';

		session->pasv_port = 10000;
		session->pasv_active = 1;
		local.sin_port=htons(session->pasv_port);
		local.sin_addr.s_addr=INADDR_ANY;

		dig1 = (int)(session->pasv_port/256);
		dig2 = session->pasv_port % 256;

		FD_ZERO(&readfds);
		if((sockfd=socket(PF_INET, SOCK_STREAM, 0))==-1)
		{
			rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			goto err1;
		}
		if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))==-1)
		{
			rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			goto err1;
		}
		if(bind(sockfd, (struct sockaddr *)&local, addr_len)==-1)
		{
			rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			goto err1;
		}
		if(listen(sockfd, 1)==-1)
		{
			rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			goto err1;
		}
		rt_kprintf("Listening %d seconds @ port %d\n", tv.tv_sec, session->pasv_port);
		rt_sprintf(sbuf, "227 Entering passive mode (%d,%d,%d,%d,%d,%d)\r\n", 127, 0, 0, 1, dig1, dig2);
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		FD_SET(sockfd, &readfds);
		select(0, &readfds, 0, 0, &tv);
		if(FD_ISSET(sockfd, &readfds))
		{
			if((session->pasv_sockfd = accept(sockfd, (struct sockaddr*)&pasvremote, &addr_len))==-1)
			{
				rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
				send(session->sockfd, sbuf, strlen(sbuf), 0);
				goto err1;
			}
			else
			{
				rt_kprintf("Got Data(PASV) connection from %s\n", inet_ntoa(pasvremote.sin_addr));
				session->pasv_active = 1;
				closesocket(sockfd);
			}
		}
		else
		{
err1:
			closesocket(session->pasv_sockfd);
			session->pasv_active = 0;
			rt_free(sbuf);
			return 0;
		}
	}
	else if (str_begin_with(buf, "RETR")==0)
	{
		int file_size;

		strcpy(filename, buf + 5);

		build_full_path(session, parameter_ptr, filename, 256);
		file_size = ftp_get_filesize(filename);
		if (file_size == -1)
		{
			rt_sprintf(sbuf, "550 \"%s\" : not a regular file\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			session->offset=0;
			rt_free(sbuf);			
			return 0;
		}

		fd = open(filename, O_RDONLY, 0);
		if (fd < 0)
		{
			rt_free(sbuf);
			return 0;
		}

		if(session->offset>0 && session->offset < file_size)
		{
			lseek(fd, session->offset, SEEK_SET);
			rt_sprintf(sbuf, "150 Opening binary mode data connection for partial \"%s\" (%d/%d bytes).\r\n",
				filename, file_size - session->offset, file_size);
		}
		else
		{
			rt_sprintf(sbuf, "150 Opening binary mode data connection for \"%s\" (%d bytes).\r\n", filename, file_size);
		}
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		while((numbytes = read(fd, sbuf, FTP_BUFFER_SIZE))>0)
		{
			send(session->pasv_sockfd, sbuf, numbytes, 0);
		}
		rt_sprintf(sbuf, "226 Finished.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		close(fd);
		closesocket(session->pasv_sockfd);
	}
	else if (str_begin_with(buf, "STOR")==0)
	{
		if(session->is_anonymous == RT_TRUE)
		{
			rt_sprintf(sbuf, "550 Permission denied.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);
			return 0;
		}

		build_full_path(session, parameter_ptr, filename, 256);

		fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0);
		if(fd < 0)
		{
			rt_sprintf(sbuf, "550 Cannot open \"%s\" for writing.\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);
			return 0;
		}
		rt_sprintf(sbuf, "150 Opening binary mode data connection for \"%s\".\r\n", filename);
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		FD_ZERO(&readfds);
		FD_SET(session->pasv_sockfd, &readfds);
		rt_kprintf("Waiting %d seconds for data...\n", tv.tv_sec);
		while(select(session->pasv_sockfd+1, &readfds, 0, 0, &tv)>0 )
		{
			if((numbytes=recv(session->pasv_sockfd, sbuf, FTP_BUFFER_SIZE, 0))>0)
			{
				write(fd, sbuf, numbytes);
			}
			else if(numbytes==0)
			{
				close(fd);
				closesocket(session->pasv_sockfd);
				rt_sprintf(sbuf, "226 Finished.\r\n");
				send(session->sockfd, sbuf, strlen(sbuf), 0);
				break;
			}
			else if(numbytes==-1)
			{
				close(fd);
				closesocket(session->pasv_sockfd);
				rt_free(sbuf);
				return -1;
			}
		}
		closesocket(session->pasv_sockfd);
	}
	else if(str_begin_with(buf, "SIZE")==0)
	{
		int file_size;

		build_full_path(session, parameter_ptr, filename, 256);

		file_size = ftp_get_filesize(filename);
		if( file_size == -1)
		{
			rt_sprintf(sbuf, "550 \"%s\" : not a regular file\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else
		{
			rt_sprintf(sbuf, "213 %d\r\n", file_size);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
	}
	else if(str_begin_with(buf, "MDTM")==0)
	{
		rt_sprintf(sbuf, "550 \"/\" : not a regular file\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "SYST")==0)
	{
		rt_sprintf(sbuf, "215 %s\r\n", "RT-Thread RTOS");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "CWD")==0)
	{
		build_full_path(session, parameter_ptr, filename, 256);

		rt_sprintf(sbuf, "250 Changed to directory \"%s\"\r\n", filename);
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		strcpy(session->currentdir, filename);
		rt_kprintf("Changed to directory %s", filename);
	}
	else if(str_begin_with(buf, "CDUP")==0)
	{
		rt_sprintf(filename, "%s/%s", session->currentdir, "..");

		rt_sprintf(sbuf, "250 Changed to directory \"%s\"\r\n", filename);
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		strcpy(session->currentdir, filename);
		rt_kprintf("Changed to directory %s", filename);
	}
	else if(str_begin_with(buf, "PORT")==0)
	{
		int i;
		int portcom[6];
		char tmpip[100];

		i=0;
		portcom[i++]=atoi(strtok(parameter_ptr, ".,;()"));
		for(;i<6;i++)
			portcom[i]=atoi(strtok(0, ".,;()"));
		rt_sprintf(tmpip, "%d.%d.%d.%d", portcom[0], portcom[1], portcom[2], portcom[3]);

		FD_ZERO(&readfds);
		if((session->pasv_sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1)
		{
			rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			closesocket(session->pasv_sockfd);
			session->pasv_active = 0;
			rt_free(sbuf);	
			return 0;
		}
		pasvremote.sin_addr.s_addr=inet_addr(tmpip);
		pasvremote.sin_port=htons(portcom[4] * 256 + portcom[5]);
		pasvremote.sin_family=PF_INET;
		if(connect(session->pasv_sockfd, (struct sockaddr *)&pasvremote, addr_len)==-1)
		{
			// is it only local address?try using gloal ip addr
			pasvremote.sin_addr=session->remote.sin_addr;
			if(connect(session->pasv_sockfd, (struct sockaddr *)&pasvremote, addr_len)==-1)
			{
				rt_sprintf(sbuf, "425 Can't open data connection.\r\n");
				send(session->sockfd, sbuf, strlen(sbuf), 0);
				closesocket(session->pasv_sockfd);
				rt_free(sbuf);				
				return 0;
			}
		}
		session->pasv_active=1;
		session->pasv_port = portcom[4] * 256 + portcom[5];
		rt_kprintf("Connected to Data(PORT) %s @ %d\n", tmpip, portcom[4] * 256 + portcom[5]);
		rt_sprintf(sbuf, "200 Port Command Successful.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "REST")==0)
	{
		if(atoi(parameter_ptr)>=0)
		{
			session->offset=atoi(parameter_ptr);
			rt_sprintf(sbuf, "350 Send RETR or STOR to start transfert.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
	}
	else if(str_begin_with(buf, "MKD")==0)
	{
		if (session->is_anonymous == RT_TRUE)
		{
			rt_sprintf(sbuf, "550 Permission denied.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);			
			return 0;
		}

		build_full_path(session, parameter_ptr, filename, 256);

		if(mkdir(filename, 0) == -1)
		{
			rt_sprintf(sbuf, "550 File \"%s\" exists.\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else
		{
			rt_sprintf(sbuf, "257 directory \"%s\" successfully created.\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
	}
	else if(str_begin_with(buf, "DELE")==0)
	{
		if (session->is_anonymous == RT_TRUE)
		{
			rt_sprintf(sbuf, "550 Permission denied.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);
			return 0;
		}

		build_full_path(session, parameter_ptr, filename, 256);

		if(unlink(filename)==0)
			rt_sprintf(sbuf, "250 Successfully deleted file \"%s\".\r\n", filename);
		else
		{
			rt_sprintf(sbuf, "550 Not such file or directory: %s.\r\n", filename);
		}
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	else if(str_begin_with(buf, "RMD")==0)
	{
		if (session->is_anonymous == RT_TRUE)
		{
			rt_sprintf(sbuf, "550 Permission denied.\r\n");
			send(session->sockfd, sbuf, strlen(sbuf), 0);
			rt_free(sbuf);			
			return 0;
		}
		build_full_path(session, parameter_ptr, filename, 256);

		if(unlink(filename) == -1)
		{
			rt_sprintf(sbuf, "550 Directory \"%s\" doesn't exist.\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
		else
		{
			rt_sprintf(sbuf, "257 directory \"%s\" successfully deleted.\r\n", filename);
			send(session->sockfd, sbuf, strlen(sbuf), 0);
		}
	}
	
	else if(str_begin_with(buf, "QUIT")==0)
	{
		rt_sprintf(sbuf, "221 Bye!\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
		rt_free(sbuf);		
		return -1;
	}
	else
	{
		rt_sprintf(sbuf, "502 Not Implemented.\r\n");
		send(session->sockfd, sbuf, strlen(sbuf), 0);
	}
	rt_free(sbuf);	
	return 0;
}
Пример #12
0
int main(int argc,char **argv) {
	const char *s_geometry = NULL;
	const char *s_command = NULL;
	const char *s_image = NULL;
	const char *s_entry = NULL;
	const char *s_start = NULL;
	const char *s_type = NULL;
	const char *s_num = NULL;
	uint32_t start=0,num=0;
	int i,ret=1,entry=-1,type=-1;

	for (i=1;i < argc;) {
		const char *a = argv[i++];

		if (*a == '-') {
			do { a++; } while (*a == '-');

			if (!strcmp(a,"geometry")) {
				s_geometry = argv[i++];
			}
			else if (!strcmp(a,"image")) {
				s_image = argv[i++];
			}
			else if (!strcmp(a,"entry")) {
				s_entry = argv[i++];
			}
			else if (!strcmp(a,"c")) {
				s_command = argv[i++];
			}
			else if (!strcmp(a,"start")) {
				s_start = argv[i++];
			}
			else if (!strcmp(a,"type")) {
				s_type = argv[i++];
			}
			else if (!strcmp(a,"num")) {
				s_num = argv[i++];
			}
			else {
				fprintf(stderr,"Unknown switch '%s'\n",a);
				return 1;
			}
		}
		else {
			fprintf(stderr,"Unexpected arg '%s'\n",a);
			return 1;
		}
	}

	if (s_command == NULL) {
		fprintf(stderr,"mbredit -c <command> [options] ...\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"--geometry <C/H/S>          Specify geometry of the disk image\n");
		fprintf(stderr,"--image <path>              Disk image path\n");
		fprintf(stderr,"--entry <x>                 Partition entry\n");
		fprintf(stderr,"--start <x>                 Starting (LBA) sector\n");
		fprintf(stderr,"--num <x>                   Number of (LBA) sectors\n");
		fprintf(stderr,"--type <x>                  Partition type code\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"-c dump                     Dump the sector containing the MBR\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"-c list                     Print the contents of the partition table\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"-c create                   Create a new partition table\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"-c remove                   Remove entry\n");
		fprintf(stderr,"\n");

		fprintf(stderr,"-c editloc                  Edit entry, change location and type\n");
		fprintf(stderr,"\n");
		return 1;
	}

	if (s_image == NULL) {
		fprintf(stderr,"No image provided\n");
		return 1;
	}

	if (s_entry != NULL)
		entry = atoi(s_entry);

	if (s_start != NULL)
		start = (uint32_t)strtoul(s_start,NULL,0);
	if (s_num != NULL)
		num = (uint32_t)strtoul(s_num,NULL,0);
	if (s_type != NULL)
		type = (int)strtol(s_type,NULL,0);

	if (s_geometry != NULL) {
		diskimage_use_chs = 1;
		if (int13cnv_parse_chs_geometry(&diskimage_chs,s_geometry)) {
			fprintf(stderr,"Failed to parse C/H/S geometry\n");
			return 1;
		}
	}
	else {
		diskimage_chs.cylinders = 16384;
		diskimage_chs.sectors = 63;
		diskimage_chs.heads = 255;
		diskimage_use_chs = 0;
	}

	assert(sizeof(diskimage_sector) >= LIBPARTMBR_SECTOR_SIZE);
	assert(libpartmbr_sanity_check());

	if (!strcmp(s_command,"create") || !strcmp(s_command,"remove") ||
		!strcmp(s_command,"editloc"))
		diskimage_fd = open(s_image,O_RDWR|O_BINARY|O_CREAT,0644);
	else
		diskimage_fd = open(s_image,O_RDONLY|O_BINARY);

	if (diskimage_fd < 0) {
		fprintf(stderr,"Failed to open disk image, error=%s\n",strerror(errno));
		return 1;
	}
	{
		/* make sure it's a file */
		struct stat st;
		if (_polyfill_fstat(diskimage_fd,&st) || !S_ISREG(st.st_mode)) {
			fprintf(stderr,"Image is not a file\n");
			return 1;
		}
	}
	if (_polyfill_lseek(diskimage_fd,0,SEEK_SET) != 0 || read(diskimage_fd,diskimage_sector,LIBPARTMBR_SECTOR_SIZE) != LIBPARTMBR_SECTOR_SIZE) {
		fprintf(stderr,"Failed to read MBR\n");
		return 1;
	}

	if (!strcmp(s_command,"create"))
		return do_create();

	if (!strcmp(s_command,"dump"))
		return do_dump();

	if (libpartmbr_state_probe(&diskimage_state,diskimage_sector)) {
		fprintf(stderr,"Doesn't look like MBR\n");
		return 1;
	}
	printf("MBR partition type: %s\n",libpartmbr_type_to_string(diskimage_state.type));

	if (!strcmp(s_command,"list"))
		ret = do_list(0);
	else if (!strcmp(s_command,"elist"))
		ret = do_list(1);
	else if (!strcmp(s_command,"remove"))
		ret = do_remove(entry);
	else if (!strcmp(s_command,"editloc"))
		ret = do_editloc(entry,start,num,type);
	else
		fprintf(stderr,"Unknown command '%s'\n",s_command);

	close(diskimage_fd);
	diskimage_fd = -1;
	return ret;
}
Пример #13
0
int process_line(ai::PL::KnowledgeBase &kb, int interactive, char *buf, std::istream &in, std::ostream &out)
{
    if(strncmp(buf, "tell", 4) == 0)
    {
        do_tell(kb, interactive, buf, in, out);
    }
    else if(strncmp(buf, "ask2", 4) == 0)
    {
        do_ask(kb, interactive, buf, in, out, "ask2");
    }
    else if(strncmp(buf, "dpll", 4) == 0)
    {
        do_ask(kb, interactive, buf, in, out, "dpll");
    }
    else if(strncmp(buf, "ask", 3) == 0)
    {
        do_ask(kb, interactive, buf, in, out, "ask");
    }
    else if(strncmp(buf, "list", 4) == 0)
    {
        do_list(kb, interactive, buf, in, out);
    }
    else if(strncmp(buf, "cnf", 3) == 0)
    {
        do_cnf(kb, interactive, buf, in, out);
    }
    else if(strncmp(buf, "quit", 4) == 0)
    {
        return 1;
    }
    else if(strncmp(buf, "load", 4) == 0)
    {
        do_load(kb, interactive, buf, in, out);
    }
    else if(strncmp(buf, "help", 4) == 0)
    {
        out << "known commands" << std::endl
            << "help  - this message" << std::endl
            << "tell  - prompt for new statement" << std::endl
            << "ask   - prompt for statement to check for entailment" << std::endl
            << "ask2  - prompt for statement to check for entailment (pruned)" << std::endl
            << "dpll  - prompt for statement to check for entailment (dpll)" << std::endl
            << "list  - display known statements" << std::endl
            << "cnf   - display known statements in CNF" << std::endl
            << "load  - load statements from file" << std::endl
            << "quit  - end session" << std::endl;
    }
    else if(strncmp(buf, "#", 1) == 0)
    {
        // comment, skip it
    }
    else if(strlen(buf) == 0)
    {
        // empty line, skip it
    }
    else
    {
        out << "unknown command.  use help to list known commands." << std::endl;
        out << buf << std::endl;
    }
    return 0;
}
Пример #14
0
/*
** mo_list
**      parv[0] = sender prefix
**      parv[1] = channel
*/
static void
m_list(struct Client *client_p, struct Client *source_p,
        int parc, char *parv[])
{
  do_list(source_p, parc, parv);
}
Пример #15
0
int main(int argc, char **argv)
{
    int ret = -1, i = 0;
    char pvfs_path[MAX_NUM_PATHS][PVFS_NAME_MAX];
    PVFS_fs_id fs_id_array[MAX_NUM_PATHS] = {0};
    const PVFS_util_tab* tab;
    struct options* user_opts = NULL;
    char current_dir[PVFS_NAME_MAX] = {0};
    int found_one = 0;

    process_name = argv[0];

    user_opts = parse_args(argc, argv);
    if (!user_opts)
    {
	fprintf(stderr, "Error: failed to parse command line "
                "arguments.\n");
 	usage(argc, argv);
	return(-1);
    }

    tab = PVFS_util_parse_pvfstab(NULL);
    if (!tab)
    {
        fprintf(stderr, "Error: failed to parse pvfstab.\n");
        return(-1);
    }

    for(i = 0; i < MAX_NUM_PATHS; i++)
    {
        memset(pvfs_path[i],0,PVFS_NAME_MAX);
    }

    ret = PVFS_sys_initialize(GOSSIP_NO_DEBUG);
    if (ret < 0)
    {
	PVFS_perror("PVFS_sys_initialize", ret);
	return(-1);
    }

    /* initialize each file system that we found in the tab file */
    for(i = 0; i < tab->mntent_count; i++)
    {
	ret = PVFS_sys_fs_add(&tab->mntent_array[i]);
	if (ret == 0)
        {
	    found_one = 1;
        }
    }

    if (!found_one)
    {
	fprintf(stderr, "Error: could not initialize any file systems "
                "from %s\n", tab->tabfile_name);
	PVFS_sys_finalize();
	return(-1);
    }

    if (user_opts->num_starts == 0)
    {
	snprintf(current_dir,PVFS_NAME_MAX,"%s/",
		 tab->mntent_array[0].mnt_dir);
	user_opts->start[0] = current_dir;
	user_opts->num_starts = 1;
    }

    for(i = 0; i < user_opts->num_starts; i++)
    {
	ret = PVFS_util_resolve(user_opts->start[i],
	    &fs_id_array[i], pvfs_path[i], PVFS_NAME_MAX);
	if ((ret == 0) && (pvfs_path[i][0] == '\0'))
	{
            strcpy(pvfs_path[i], "/");
	}

	if (ret < 0)
	{
	    fprintf(stderr, "Error: could not find file system "
                    "for %s in pvfstab\n", user_opts->start[i]);
	    return(-1);
	}
    }

    for(i = 0; i < user_opts->num_starts; i++)
    {
        char *substr = strstr(user_opts->start[i],pvfs_path[i]);
        char *index = user_opts->start[i];
        char *search = substr; 
        int j = 0;

        /* Keep the mount path info to mimic /bin/ls output */
        if( strncmp(pvfs_path[i],"/",strlen(pvfs_path[i])) )
        {
            /* Get last matching substring */
            while (search) 
            {
                substr = search;
                search = strstr(++search,pvfs_path[i]);
            }
        }
        else /* Root directory case has nothing to match */
        {
            substr = &user_opts->start[i][strlen(user_opts->start[i])-1];
        }

        while ((index != substr) && (substr != NULL))
        {
            index++;
            j++;
        }
        user_opts->start[i][j] = '\0';

        do_list(user_opts->start[i], pvfs_path[i], fs_id_array[i], user_opts);

        if (user_opts->num_starts > 1)
        {
            printf("\n");
        }
    }

    PVFS_sys_finalize();
    free(user_opts);

    return(ret);
}
Пример #16
0
static int
do_list(struct list_options *opt, const char *keytab_str)
{
    krb5_error_code ret;
    krb5_keytab keytab;
    krb5_keytab_entry entry;
    krb5_kt_cursor cursor;
    rtbl_t table;

    /* XXX specialcase the ANY type */
    if(strncasecmp(keytab_str, "ANY:", 4) == 0) {
	int flag = 0;
	char buf[1024];
	keytab_str += 4;
	ret = 0;
	while (strsep_copy((const char**)&keytab_str, ",", 
			   buf, sizeof(buf)) != -1) {
	    if(flag)
		printf("\n");
	    if(do_list(opt, buf))
		ret = 1;
	    flag = 1;
	}
	return ret;
    }

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if (ret) {
	krb5_warn(context, ret, "resolving keytab %s", keytab_str);
	return ret;
    }

    ret = krb5_kt_start_seq_get(context, keytab, &cursor);
    if(ret) {
	krb5_warn(context, ret, "krb5_kt_start_seq_get %s", keytab_str);
	krb5_kt_close(context, keytab);
	return ret;
    }

    printf ("%s:\n\n", keytab_str);
	
    table = rtbl_create();
    rtbl_add_column_by_id(table, 0, "Vno", RTBL_ALIGN_RIGHT);
    rtbl_add_column_by_id(table, 1, "Type", 0);
    rtbl_add_column_by_id(table, 2, "Principal", 0);
    if (opt->timestamp_flag)
	rtbl_add_column_by_id(table, 3, "Date", 0);
    if(opt->keys_flag)
	rtbl_add_column_by_id(table, 4, "Key", 0);
    rtbl_set_separator(table, "  ");

    while((ret = krb5_kt_next_entry(context, keytab, &entry, &cursor)) == 0){
	char buf[1024], *s;

	snprintf(buf, sizeof(buf), "%d", entry.vno);
	rtbl_add_column_entry_by_id(table, 0, buf);

	ret = krb5_enctype_to_string(context, 
				     entry.keyblock.keytype, &s);
	if (ret != 0) {
	    snprintf(buf, sizeof(buf), "unknown (%d)", entry.keyblock.keytype);
	    rtbl_add_column_entry_by_id(table, 1, buf);
	} else {
	    rtbl_add_column_entry_by_id(table, 1, s);
	    free(s);
	}

	krb5_unparse_name_fixed(context, entry.principal, buf, sizeof(buf));
	rtbl_add_column_entry_by_id(table, 2, buf);

	if (opt->timestamp_flag) {
	    krb5_format_time(context, entry.timestamp, buf, 
			     sizeof(buf), FALSE);
	    rtbl_add_column_entry_by_id(table, 3, buf);
	}
	if(opt->keys_flag) {
	    int i;
	    s = malloc(2 * entry.keyblock.keyvalue.length + 1);
	    if (s == NULL) {
		krb5_warnx(context, "malloc failed");
		ret = ENOMEM;
		goto out;
	    }
	    for(i = 0; i < entry.keyblock.keyvalue.length; i++)
		snprintf(s + 2 * i, 3, "%02x", 
			 ((unsigned char*)entry.keyblock.keyvalue.data)[i]);
	    rtbl_add_column_entry_by_id(table, 4, s);
	    free(s);
	}
	krb5_kt_free_entry(context, &entry);
    }
    ret = krb5_kt_end_seq_get(context, keytab, &cursor);
    rtbl_format(table, stdout);

out:
    rtbl_destroy(table);

    krb5_kt_close(context, keytab);
    return ret;
}
Пример #17
0
int main(int argc,char *argv[])
{
    char zipfilename[MAXFILENAME]= {0};
    char filename_to_extract[MAXFILENAME]= {0};
    const char *password=NULL;
    char filename_try[MAXFILENAME+16] = "";
    int i;
    int ret_value=0;
    int opt_do_list=0;
    int opt_do_extract=1;
    int opt_do_extract_withoutpath=0;
    int opt_overwrite=0;
    int opt_extractdir=0;
    char dirname[MAXFILENAME]= {0};
    unzFile uf=NULL;

    do_banner();
    if (argc==1)
    {
        do_help();
        return 0;
    }
    else
    {
        for (i=1; i<argc; i++)
        {
            if ((*argv[i])=='-')
            {
                const char *p=argv[i]+1;

                while ((*p)!='\0')
                {
                    char c=*(p++);;
                    if ((c=='l') || (c=='L'))
                        opt_do_list = 1;
                    if ((c=='v') || (c=='V'))
                        opt_do_list = 1;
                    if ((c=='x') || (c=='X'))
                        opt_do_extract = 1;
                    if ((c=='e') || (c=='E'))
                        opt_do_extract = opt_do_extract_withoutpath = 1;
                    if ((c=='o') || (c=='O'))
                        opt_overwrite=1;
                    if ((c=='d') || (c=='D'))
                    {
                        opt_extractdir=1;
                        strcat(dirname,__DIR__);
                        strcat(dirname,"/");
                        strcat(dirname,argv[i+1]);
                    }

                    if (((c=='p') || (c=='P')) && (i+1<argc))
                    {
                        password=argv[i+1];
                        i++;
                    }
                }
            }
            else
            {
                if (!strlen(zipfilename))
                {
                    strcat(zipfilename,__DIR__);
                    strcat(zipfilename,"/");
                    strcat(zipfilename,argv[i]);
                }
                else if ((!strlen(filename_to_extract)) && (!opt_extractdir))
                {
                    strcat(filename_to_extract,__DIR__);
                    strcat(filename_to_extract,"/");
                    strcat(filename_to_extract,argv[i]);
                }
            }
        }
    }

    if (strlen(zipfilename))
    {

#        ifdef USEWIN32IOAPI
        zlib_filefunc64_def ffunc;
#        endif

        strncpy(filename_try, zipfilename,MAXFILENAME-1);
        /* strncpy doesnt append the trailing NULL, of the string is too long. */
        filename_try[ MAXFILENAME ] = 0;

#        ifdef USEWIN32IOAPI
        fill_win32_filefunc64A(&ffunc);
        uf = unzOpen2_64(zipfilename,&ffunc);
#        else
        uf = unzOpen64(zipfilename);
#        endif
        if (uf==NULL)
        {
            strcat(filename_try,".zip");
#            ifdef USEWIN32IOAPI
            uf = unzOpen2_64(filename_try,&ffunc);
#            else
            uf = unzOpen64(filename_try);
#            endif
        }
    }

    if (uf==NULL)
    {
        printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
        return 1;
    }
    printf("%s opened\n",filename_try);

    if (opt_do_list==1)
        ret_value = do_list(uf);
    else if (opt_do_extract==1)
    {
        chdir(__DIR__);
#ifdef _WIN32
        if (opt_extractdir && _chdir(dirname))
#else
        if (opt_extractdir && chdir(dirname))
#endif
        {
            printf("Error changing into %s, aborting\n", dirname);
            exit(-1);
        }

        if (!strlen(filename_to_extract))
            ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
        else
            ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
    }

    unzClose(uf);

    return ret_value;
}
Пример #18
0
/*
 *  Transfer the relevant data from the kernel and module unwind_table
 *  structures to the local_unwind_table structures.
 */
static int
populate_local_tables(ulong root, char *buf)
{
	struct list_data list_data, *ld;
	int i, cnt;
	ulong *table_list;
	ulong vaddr;
	struct local_unwind_table *tp;

        ld = &list_data;
        BZERO(ld, sizeof(struct list_data));
        ld->start = root;
        ld->member_offset = OFFSET(unwind_table_link);
	ld->flags = RETURN_ON_LIST_ERROR;
	if (CRASHDEBUG(1))
        	ld->flags |= VERBOSE;

	hq_open();
        cnt = do_list(ld);
	if (cnt == -1) {
		error(WARNING, "UNWIND: failed to gather unwind_table list");
		return 0;
	}
        table_list = (ulong *)GETBUF(cnt * sizeof(ulong));
	cnt = retrieve_list(table_list, cnt);
	hq_close();

	if (!(local_unwind_tables = 
	    malloc(sizeof(struct local_unwind_table) * cnt))) {
		error(WARNING, "cannot malloc unwind_table space (%d tables)\n",
			cnt);
		FREEBUF(table_list);
		return 0;
	}

	for (i = 0; i < cnt; i++, tp++) {

                if (!readmem(table_list[i], KVADDR, buf,
                    SIZE(unwind_table), "unwind_table",
                    RETURN_ON_ERROR|QUIET)) {
			error(WARNING, "cannot read unwind_table\n");
			goto failed;
		}

		tp = &local_unwind_tables[i];

		/*
		 *  Copy the required table info for find_table().
		 */
        	BCOPY(buf + OFFSET(unwind_table_core),
                	(char *)&tp->core.pc, sizeof(ulong)*2);
        	BCOPY(buf + OFFSET(unwind_table_init),
                	(char *)&tp->init.pc, sizeof(ulong)*2);
        	BCOPY(buf + OFFSET(unwind_table_size),
                	(char *)&tp->size, sizeof(ulong));

		/*
		 *  Then read the DWARF CFI data.
		 */
		vaddr = ULONG(buf + OFFSET(unwind_table_address));

		if (!(tp->address = malloc(tp->size))) {
			error(WARNING, "cannot malloc unwind_table space\n");
			goto failed;
			break;
		}
                if (!readmem(vaddr, KVADDR, tp->address,
                    tp->size, "DWARF CFI data", RETURN_ON_ERROR|QUIET)) {
			error(WARNING, "cannot read unwind_table data\n");
			goto failed;
		}
	}

	unwind_tables_cnt = cnt;

	if (CRASHDEBUG(7))
		dump_local_unwind_tables();

failed:

	FREEBUF(table_list);
	return unwind_tables_cnt;
}
Пример #19
0
/*
 *	The function "mon()" is the dialog user interface, called
 *	from the simulation just after program start.
 */
void mon(void)
{
	register int eoj = 1;
	static char cmd[LENCMD];

	tcgetattr(0, &old_term);

	if (x_flag) {
		if (do_getfile(xfn) == 0)
			do_go("");
	}
	while (eoj) {
		next:
		printf(">>> ");
		fflush(stdout);
		if (fgets(cmd, LENCMD, stdin) == NULL) {
			putchar('\n');
			goto next;
		}
		switch (*cmd) {
		case '\n':
			do_step();
			break;
		case 't':
			do_trace(cmd + 1);
			break;
		case 'g':
			do_go(cmd + 1);
			break;
		case 'd':
			do_dump(cmd + 1);
			break;
		case 'l':
			do_list(cmd + 1);
			break;
		case 'm':
			do_modify(cmd +	1);
			break;
		case 'f':
			do_fill(cmd + 1);
			break;
		case 'v':
			do_move(cmd + 1);
			break;
		case 'x':
			do_reg(cmd + 1);
			break;
		case 'p':
			do_port(cmd + 1);
			break;
		case 'b':
			do_break(cmd + 1);
			break;
		case 'h':
			do_hist(cmd + 1);
			break;
		case 'z':
			do_count(cmd + 1);
			break;
		case 'c':
			do_clock();
			break;
		case 's':
			do_show();
			break;
		case '?':
			do_help();
			break;
		case 'r':
			do_getfile(cmd + 1);
			break;
		case '!':
			do_unix(cmd + 1);
			break;
		case 'q':
			eoj = 0;
			break;
		default:
			puts("what??");
			break;
		}
	}
}
Пример #20
0
int main(int argc, char *argv[])
{
    const char *action;
    char *file = NULL;
    char *dbfile = NULL;
    PWInfo pwinfo;
    int fodder;
    int ret = 0;
    int with_chroot = 1;
    int with_mkdb = 0;
        
    if (argc < 2) {
        help();
    }

#ifdef HAVE_SETLOCALE
# ifdef LC_MESSAGES
    (void) setlocale(LC_MESSAGES, "");
# endif
# ifdef LC_CTYPE
    (void) setlocale(LC_CTYPE, "");
# endif
# ifdef LC_COLLATE
    (void) setlocale(LC_COLLATE, "");
# endif
#endif    

    pwinfo.pwd = NULL;
    pwinfo.gecos = NULL;
    pwinfo.home = NULL;
    pwinfo.allow_local_ip = pwinfo.deny_local_ip = NULL;
    pwinfo.allow_client_ip = pwinfo.deny_client_ip = NULL;        
    pwinfo.has_bw_dl = 0;
    pwinfo.has_bw_ul = 0;
    pwinfo.has_quota_files = 0;
    pwinfo.has_quota_size = 0;
    pwinfo.has_ul_ratio = 0;
    pwinfo.has_dl_ratio = 0;
    pwinfo.has_time = 0;
    pwinfo.time_begin = pwinfo.time_end = 0U;
    pwinfo.has_per_user_max = 0;
    pwinfo.per_user_max = 0U;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
    pwinfo.uid = (uid_t) 42U;
    pwinfo.gid = (gid_t) 42U;
#else
    pwinfo.uid = (uid_t) 0U;
    pwinfo.gid = (gid_t) 0U;
#endif
    
    argv++;
    argc--;
    action = *argv;
    if (argc > 1) {
        argv++;
        argc--;
        pwinfo.login = *argv;
    } else {
        pwinfo.login = NULL;
    }
    filter_pw_line_sep(pwinfo.login);
    while ((fodder =
            getopt(argc, argv, 
                   "c:d:D:f:F:g:hi:I:mn:N:q:Q:r:R:t:T:u:y:z:")) != -1) {
        switch(fodder) {
        case 'c' : {
            if ((pwinfo.gecos = strdup(optarg)) == NULL) {
                no_mem();
            }
            filter_pw_line_sep(pwinfo.gecos);
            break;
        }
        case 'D' :
            with_chroot = 0;
        case 'd' : {
            char *optarg_copy;
            size_t sizeof_home;
            size_t optarg_len;
            
            if ((optarg_copy = strdup(optarg)) == NULL) {
                no_mem();
            }
            again:
            optarg_len = strlen(optarg_copy);
            if (optarg_len < (size_t) 1U) {
                fprintf(stderr, "home directory is missing\n");
                exit(EXIT_FAILURE);
            }
            if (optarg_copy[optarg_len - 1U] == '/') {
                optarg_len--;
                optarg_copy[optarg_len] = 0;
                goto again;
            }
            sizeof_home = optarg_len + sizeof "/./";
            if ((pwinfo.home = malloc(sizeof_home)) == NULL) {
                no_mem();
            }
            snprintf(pwinfo.home, sizeof_home, "%s%s", optarg_copy,
                     with_chroot != 0 ? "/./" : "");
            filter_pw_line_sep(pwinfo.home);            
            break;
        }
        case 'f' : {
            if ((file = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }
        case 'F' : {
            if ((dbfile = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }
        case 'g' : {
            struct group *gr;
            
            if (pwinfo.gid > (gid_t) 0 && pwinfo.uid <= (uid_t) 0) {
                fprintf(stderr, "You already gave a gid\n");
                exit(EXIT_FAILURE);
            }                
            if ((gr = getgrnam(optarg)) != NULL) {
                pwinfo.gid = gr->gr_gid;
            } else {
                pwinfo.gid = (gid_t) strtoul(optarg, NULL, 10);
            }            
            break;
        }
        case 'h' : {
            help();
            /* doesn't return */
        }
        case 'i' : {
            if ((pwinfo.allow_local_ip = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }
        case 'I' : {
            if ((pwinfo.deny_local_ip = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }
        case 'm' : {
            with_mkdb = 1;
            break;
        }
        case 'n' : {
            if (*optarg == 0) {
                pwinfo.has_quota_files = -1;
            } else {
                pwinfo.quota_files = strtoull(optarg, NULL, 10);
                pwinfo.has_quota_files = 1;
            }
            break;
        }
        case 'N' : {
            if (*optarg == 0) {
                pwinfo.has_quota_size = -1;
            } else {
                pwinfo.quota_size = strtoull(optarg, NULL, 10) * 
                    (1024ULL * 1024ULL);
                pwinfo.has_quota_size = 1;
            }
            break;
        }
        case 'q' : {
            if (*optarg == 0) {
                pwinfo.has_ul_ratio = -1;
            } else {
                pwinfo.ul_ratio = (unsigned int) strtoul(optarg, NULL, 10);
                if (pwinfo.ul_ratio < 1U) {
                    fprintf(stderr, "Illegal upload ratio\n");
                    exit(EXIT_FAILURE);
                }
                pwinfo.has_ul_ratio = 1;
            }
            break;
        }            
        case 'Q' : {
            if (*optarg == 0) {
                pwinfo.has_dl_ratio = -1;
            } else {
                pwinfo.dl_ratio = (unsigned int) strtoul(optarg, NULL, 10);
                if (pwinfo.dl_ratio < 1U) {
                    fprintf(stderr, "Illegal download ratio\n");
                    exit(EXIT_FAILURE);
                }            
                pwinfo.has_dl_ratio = 1;
            }
            break;
        }
        case 'r' : {
            if ((pwinfo.allow_client_ip = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }
        case 'R' : {
            if ((pwinfo.deny_client_ip = strdup(optarg)) == NULL) {
                no_mem();
            }
            break;
        }            
        case 't' : {
            if (*optarg == 0) {
                pwinfo.has_bw_dl = -1;
            } else {
                if ((pwinfo.bw_dl = strtoul(optarg, NULL, 10)) > 0UL) {
                    pwinfo.bw_dl *= 1024UL;                    
                    pwinfo.has_bw_dl = 1;
                }
            }
            break;
        }
        case 'T' : {
            if (*optarg == 0) {
                pwinfo.has_bw_ul = -1;
            } else {
                if ((pwinfo.bw_ul = strtoul(optarg, NULL, 10)) > 0UL) {
                    pwinfo.bw_ul *= 1024UL;
                    pwinfo.has_bw_ul = 1;
                }
            }
            break;
        }            
        case 'u' : {
            struct passwd *pw;                
            
            if (pwinfo.uid > (uid_t) 0) {
                fprintf(stderr, "You already gave an uid\n");
                exit(EXIT_FAILURE);
            }
            if ((pw = getpwnam(optarg)) != NULL) {
                pwinfo.uid = pw->pw_uid;
                if (pwinfo.gid <= (gid_t) 0) {
                    pwinfo.gid = pw->pw_gid;
                }
            } else {
                pwinfo.uid = (uid_t) strtoul(optarg, NULL, 10);
            }
            break;
        }
    case 'y' : {
        if ((pwinfo.per_user_max = (unsigned int) strtoul(optarg, NULL, 10)) <= 0U) {
                pwinfo.has_per_user_max = -1;
            } else {
                pwinfo.has_per_user_max = 1;
            }
        break;
    }
        case 'z' : {
            if (sscanf(optarg, "%u-%u", 
                       &pwinfo.time_begin, &pwinfo.time_end) == 2 &&
                pwinfo.time_begin < 2360 && (pwinfo.time_begin % 100) < 60 &&
                pwinfo.time_end < 2360 && (pwinfo.time_end % 100) < 60) {
                pwinfo.has_time = 1;
            } else if (*optarg != 0) {
                fprintf(stderr, "Time should be given as hhmm-hhmm\n"
                        "Example : 0900-1800 (9 am to 6 pm)\n");
                exit(EXIT_FAILURE);                    
            } else {
                pwinfo.has_time = -1;
            }
            break;
        }
        case '?' :
            help();
        }
    }
    if (file == NULL) {
        char *file_;
        
        if ((file_ = getenv(ENV_DEFAULT_PW_FILE)) != NULL && *file_ != 0) {
            file = file_;
        } else if ((file = strdup(DEFAULT_PW_FILE)) == NULL) {
            no_mem();
        }
    }
    (void) umask(0177);
    init_zrand();
    if (strcasecmp(action, "useradd") == 0) {
        ret = do_useradd(file, &pwinfo);
        if (with_mkdb != 0) {
            ret |= do_mkdb(dbfile, file);
        }
    } else if (strcasecmp(action, "usermod") == 0) {
        ret = do_usermod(file, &pwinfo);
        if (with_mkdb != 0) {
            ret |= do_mkdb(dbfile, file);
        }        
    } else if (strcasecmp(action, "userdel") == 0) {
        ret = do_userdel(file, &pwinfo);
        if (with_mkdb != 0) {
            ret |= do_mkdb(dbfile, file);
        }        
    } else if (strcasecmp(action, "passwd") == 0) {
        ret = do_passwd(file, &pwinfo);
        if (with_mkdb != 0) {
            ret |= do_mkdb(dbfile, file);
        }        
    } else if (strcasecmp(action, "show") == 0) {
        ret = do_show(file, &pwinfo);
    } else if (strcasecmp(action, "mkdb") == 0) {
        ret = do_mkdb(pwinfo.login, file);
    } else if (strcasecmp(action, "list") == 0) {
        ret = do_list(file);
    } else {
        ret = PW_ERROR_UNEXPECTED_ERROR;
        help();
    }
               
    return ret;
}
Пример #21
0
/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];
    
	
    char received_cmd;
	char editted_filename[100];
	 char Copied_filename[100];
    //Send some messages to the client
    //message = "Greetings! I am your connection handler\n";
    //write(sock , message , strlen(message));
     
    //message = "Now type something and i shall repeat what you type \n";
    //write(sock , message , strlen(message));
     
    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {


////////////////recv C cmd	
		if(strcmp ( client_message,"C")==0 )
		{
			received_cmd='C';//it means we have to do  C  cmd exec later.
		

			//memset(client_message,0,sizeof(client_message));

			strcpy(client_message,"What's the name of your new file?\n");

			//Send the message back to client
			if(write(sock , client_message , strlen(client_message))<0)
			{
				 puts("Send failed");
				 return 1;
			}
			memset(client_message,0,sizeof(client_message));
		}

///////////////recv C end




////////////////recv R cmd

		else if(strcmp (client_message,"R")==0)
		{
			received_cmd='R';//it means we have to do  R  cmd exec later.
			strcpy(client_message,"Which file do you want to delete?\n");
			//Send the message back to client
	

			if(write(sock , client_message , strlen(client_message))<0)
			{
						    puts("Send failed");
						    return 1;
			}
			memset(client_message,0,sizeof(client_message));
		
		
 		


		}




///////////////recv R end
	
///////////////recv L cmd
		else if(strcmp (client_message,"L")==0)
		{
			received_cmd='L';//it means we have to do  L  cmd exec later.
			
			
			strcpy(client_message,"The followings are the files created on server side.\n");
			//call ls
			do_list(client_message);
	
			strcat(client_message,"The aboves are the files created on server side.\n");
	
			
 			//Send the message back to client
			if(write(sock , client_message , strlen(client_message))<0)
			{
						    puts("Send failed");
						    return 1;
			}
			memset(client_message,0,sizeof(client_message));

		}





///////////////recv L end

///////////////recv D cmd

	else if(strcmp (client_message,"D")==0)
	{
		received_cmd='D';//it means we have to do  D  cmd exec later.
		strcpy(client_message,"Which file do you want to download?\n");
		//Send the message back to client
		if(write(sock , client_message , strlen(client_message))<0)
		{
			puts("Send failed");
			return 1;
		}

		memset(client_message,0,sizeof(client_message));
		
		
		
 		


	}









/////////////////end recv D cmd

//////////////////recv E cmd


		else if(strcmp (client_message,"E")==0)
		{
			received_cmd='E';//it means we have to do  E  cmd exec later.
			strcpy(client_message,"Which file do you want to edit in \"vi\"?\n");
			
			if(write(sock , client_message, strlen(client_message)) < 0)
				{
				    puts("Send failed");
				    return 1;
				}
				
				memset(client_message,0,sizeof(client_message));
				

		}
		
		
		else if(strcmp (client_message,"Copy")==0)
		{
			received_cmd='P';//it means we have to do  Copy  cmd exec later.
			strcpy(client_message,"Which file do you want to copy?\n");
			//Send the message back to client
	

			if(write(sock , client_message , strlen(client_message))<0)
			{
						    puts("Send failed");
						    return 1;
			}
			memset(client_message,0,sizeof(client_message));
		
		
 		


		}










//////////////////////////end recv E cmd

///////////////////////////recv write editted content into file

//get the editted content and write them to the file.
			else if(strcmp (client_message,"Read file after editted in vi.")==0)
			{
				strcpy(client_message,"Ok send your file.");
				if(write(sock , client_message , strlen(client_message))<0)
				{
						    puts("Send failed");
						    return 1;
				}
				memset(client_message,0,sizeof(client_message));
				
				received_cmd='e';
				


			}

///////////////////////////end  writing editted content into file







////////////////////////////////client send a file name according to the previous command.

	else
	{
///////////////recv C cmd
		if(received_cmd=='C')
		{
				
				//int file_exist;
				//printf("this is new file info before check %s \n",client_message);
				//if the this file doesn't exist on server side,
		
			    create_file(client_message);
				
				
	
				
				
        			
				//Send the message back to client
				if(write(sock , client_message , strlen(client_message))<0)
				{
						    puts("Send failed");
						    return 1;
				}
				memset(client_message,0,sizeof(client_message));
				//printf("this is new file info %s \n",client_message);
				

				received_cmd=' ';
				
				

 		}
/////////////////////end creating new file exec


/////////////////////recv removing file cmd 
		//remove an existing file
		else if(received_cmd=='R')
		{
				
				
				
				
				if(do_remove(client_message)==0)
				{
					strcat(client_message," has been deleted!\n");
				}
				
				else 
					strcat(client_message," does not exist or can't be deleted!\n");
				
	
				
				
				if(write(sock , client_message, strlen(client_message)) < 0)
				{
				    puts("Send failed");
				    return 1;
				}
				
				memset(client_message,0,sizeof(client_message));
				
				received_cmd=' ';

 		}

///////////////////////////end exec removing file

//////////////////////////exec Download cmd

		else if(received_cmd=='D')
		{
				//if_file_exist
				int exist_or_not;
			    if(exist_or_not=whether_file_exist(client_message)==0)
				{
					//read the content of the file which user wants to download.
					 read_file_content(client_message);
					 

				}
				//download error :if the file does not exist.
				else
				{
					strcpy(client_message," does not exist!\n");
					printf("this is D result: %s ",client_message);
				        
				}
				//return the file content or the download error msg.
				if(write(sock , client_message, strlen(client_message)) < 0)
				{
				    puts("Send failed");
				    return 1;
				}
				
				memset(client_message,0,sizeof(client_message));
				
				received_cmd=' ';


 		}







////////////////////////end exec Download cmd

/////////////////////////recv Edit cmd

		else if(received_cmd=='E')
		{
				//To record the editted_filename because we have to store the editted content back to it.
				strcpy(editted_filename,client_message);
				//received_cmd='B';
				received_cmd=' ';
				//if_file_exists
				
				printf("Edit file name: %s",editted_filename);
				int exist_or_not;
				//if file exists
			    if(exist_or_not=whether_file_exist(client_message)==0)
				{
					//read the content of the file which user wants to download.
					 read_file_content(client_message);
					 

				}
					//download error :if the file does not exist.
					else
					{
						strcpy(client_message,"File does not exist.You can't edit it\n");
							
					}
				
				
				
				
				//return the file content or the download error msg.
				if(write(sock , client_message, strlen(client_message)) < 0)
				{
				    puts("Send failed");
				    return 1;
				}
				
				memset(client_message,0,strlen(client_message));
				

				

				
				

		}
		
		
		
		
		/////to write the editted content back to the file on server side.
		
		else if(received_cmd=='e')
		{
			
			//get the editted content and write them to the file.
			write_editted_content_to_file(editted_filename,client_message);
			printf("this is editted content form client %s\n",client_message);
			printf("write_editted_content_to_file %s ",editted_filename);
			
			
			memset(client_message,0,sizeof(client_message));
			received_cmd=' ';
			
		}
///////////////////////end exec E cmd



////////////////////////exec Copy cmd

		else if(received_cmd=='P')
		{
				
				//int file_exist;
				//printf("this is new file info before check %s \n",client_message);
				//if the this file doesn't exist on server side,
				int exist_or_not;
			    if(exist_or_not=whether_file_exist(client_message)==0)
				{
					strcpy(Copied_filename,client_message);
					strcpy(client_message,"What's the name of your new file which is the copy of ");
					strcat(client_message,Copied_filename);
				}
					else
					{
						
						strcat(client_message," doesn't exist! You can't copy it.\n");
						
					}
				
				
        			
				//Send the message back to client
				if(write(sock , client_message , strlen(client_message))<0)
				{
						    puts("Send failed");
						    return 1;
				}
				memset(client_message,0,sizeof(client_message));
				//printf("this is new file info %s \n",client_message);
				

				received_cmd='p';
				
				

 		}

		else if(received_cmd=='p')
		{
			copy_file(Copied_filename, client_message);
			
			strcat(client_message," has been created by coping from ");
			strcat(client_message,Copied_filename);
			
			//Send the message back to client
				if(write(sock , client_message , strlen(client_message))<0)
				{
						    puts("Send failed");
						    return 1;
				}
				memset(client_message,0,sizeof(client_message));
				//printf("this is new file info %s \n",client_message);
				
			
			
			received_cmd=' ';
			
		}









////////////////////////end Copy cmd exec
















///////////////////////////recv trash cmd
		else
		{
			printf("illegal cmd before send %s \n",client_message);
			//strcat( client_message," is created!\n");

				
				strcpy(client_message,"This command doesn't exist!\n");
				if(write(sock , client_message, strlen(client_message)) < 0)
				{
				    puts("Send failed");
				    return 1;
				}
				printf("illegal cmd %s \n",client_message);			
				
				memset(client_message,0,sizeof(client_message));
				
				received_cmd=' ';
			
			
		}
///////////////////////////end exec trash cmd

	}
	

	//memset(client_message,0,sizeof(client_message));
  }
     
    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }
         
    //Free the socket pointer
    free(socket_desc);
     
    return 0;
}