Пример #1
0
/*!
  Main function

  Based on arguments to main, either
  \list
    \o access files
    \o send an internet message
    \o write one simple file
  \endlist
*/
int main( int argc, char *argv[] )
{
    int fd;
    printf( "%s (PID %d) running", argv[0], getpid() );
    if ( argc > 1 )
    {
        const char *ptr = argv[1];
        while ( *ptr && isdigit( *ptr++ )) {}
        if ( *ptr == '\0' )
            send_message( atoi( argv[1] ), argc > 2 ? argv[2] : NULL,
                        argc > 3 ? argv[3] : NULL );
        else
            process_files( argv+1, argc-1 );
    }
    else
    {
        printf( "Open and write \"test.txt\"" );
        fd = open( "test.txt", O_WRONLY | O_CREAT, S_IWUSR );
        if ( fd == -1 )
            fatal( (char*)strerror( errno ));
        write( fd, SIMPLE_MESSAGE, strlen( SIMPLE_MESSAGE ));
        close( fd );
    }
    return 0;
}
Пример #2
0
int main(int argc, char * argv[])
{
        unsigned int plateform_id;
        if(argc < 2) {
                fprintf(stderr, "You need to provide a <platform id> "
                        "<directoy>. Use make print_cl_infos "
                        "to discover your platform and device id.\n");
                exit(EXIT_FAILURE);
        }
        plateform_id = atoi(argv[1]);

        list_t *files = list_files(argv[3]);
        clinfo_t *clinfo = clinfo_init(KERNEL_PATH, KERNEL_FUNCTION
                        , plateform_id);
        list_t *results = process_files(clinfo, files, 0.01f);

        list_t *current = results;
        while(current) {
                list_t *subcurrent = current->value;
                while(subcurrent) {
                        printf("\"%s\"\n", subcurrent->value);
                        subcurrent = subcurrent->next;
                }
                printf("\n");
                current = current->next;
        }

        return 0;
}
Пример #3
0
void build_share(char *fname, FILE *fp, FILE *fpo) {
	assert(fname);
	assert(fp);
	assert(fpo);

	process_files(fname, fp, "/usr/share", share_callback);

	if (share_out == NULL)
		fprintf(fpo, "blacklist /usr/share\n");
	else
		filedb_print(share_out, "whitelist ", fpo);
}
Пример #4
0
void build_var(char *fname, FILE *fp, FILE *fpo) {
	assert(fname);
	assert(fp);
	assert(fpo);

	process_files(fname, fp, "/var", var_callback);

	if (var_out == NULL)
		fprintf(fpo, "blacklist /var\n");
	else
		filedb_print(var_out, "whitelist ", fpo);
}
Пример #5
0
void compress(int argc, char **argv, int verb) {
	int i, size;
	IS is;
	Dllist dir_list, DLLnode;
	JRB inode, JRBnode, paths, links;
	void *buf;
	tar *t;
	
	links = make_jrb();
	dir_list = new_dllist();
	inode = make_jrb();
	JRBnode = make_jrb();
	paths = make_jrb();

	for(i = 2; i < argc; i++){
		process_files(dir_list, inode, paths, argv[i], links);
	}

	dll_traverse(DLLnode, dir_list){
		process_files(dir_list, inode, paths, jval_s(DLLnode->val),links);
	}
Пример #6
0
void RelaxEngine::prepareFiles(CopyList &filesList, const QStringList &pathsToScan,
                               const QList<FilterPair> &pair)
{
    QString a_path;
    QStringList founds;
    foreach(a_path, pathsToScan){
        if(scanNested){
            get_nested_files(a_path, founds);
        }else{
            shallowWalk(a_path, founds);
        }
    }
    process_files(founds, filesList, pair);
}
Пример #7
0
int main(int argc, char **argv){
	char *keyfilename, *outputfilename;
	char **files;
	FILE *keyfile;
	char error = 0;
	if(argc < 5 || ((argc -1)%2) != 0){
		usage(argv[0]);
		exit(-1);
	}
	keyfilename = argv[1];
	outputfilename = argv[2];
	
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OPENSSL_config(NULL);


	if(NULL == (keyfile = fopen(keyfilename, "r"))){
		print_error("main", "unable to open private key", keyfilename);
		exit(-1);
	}
	if(NULL == (private_key = PEM_read_PrivateKey(keyfile, NULL, NULL, NULL))){
		print_error("main", "reading private key file. File in PEM format?", keyfilename);
		error = 1; goto error;
	}
	if(NULL == (outputfile = fopen(outputfilename, "w"))){
		print_error("main", "unable to open output file", outputfilename);
		exit(-1);
	}


	files = argv+3;
	process_files(files, argc - 3);
	
	error:
	CONF_modules_free();
	EVP_cleanup();
	ERR_free_strings();
	
	if(keyfile) fclose(keyfile);
	if(outputfile) fclose(outputfile);
	if(error)
		return -1;
	return 0;
}
//Check on a queue and do something specific...
//If qtype == 0, directories, 
//qtype ==1, files
void queue_checker(queue_t * queue, 
unsigned int num_items, 
unsigned int qtype, 
queue_t * other_queue, 
unsigned int * num_found, 
char * to_find)
{
	//Alright, let's check if there something in here
	if(queue_empty(queue))
	{
		//Empty, done here.
		return;
	}
	else
	{
		//Queue not empty
		//Try to pull off some items
		
		unsigned int items_got = 0;
		queue_t * tmp_items = get_items(queue, num_items, &items_got);
		
		//Did we get some items?
		if(items_got > 0)
		{
			//Do the specfic task for these items, with specific args
			if(qtype == 0)
			{
				//Dirs
				//printf("%d got dir items\n", items_got);
				process_dirs(tmp_items, other_queue, queue);
			}
			else
			{
				//Files
				//printf("%d got file items\n", items_got);
				process_files(tmp_items, num_found, to_find);
			}
		}
		else
		{
			//No items gotten, done here
			return;
		}
	}
}
Пример #9
0
void build_etc(char *fname, FILE *fp, FILE *fpo) {
	assert(fname);
	assert(fp);
	assert(fpo);

	process_files(fname, fp, "/etc", etc_callback);

	fprintf(fpo, "private-etc ");
	if (etc_out == NULL)
		fprintf(fpo, "none\n");
	else {
		FileDB *ptr = etc_out;
		while (ptr) {
			fprintf(fpo, "%s,", ptr->fname);
			ptr = ptr->next;
		}
		fprintf(fpo, "\n");
	}
}
Пример #10
0
/*-----------------------------------------------------------------------------
*   Parse command line, set options, including opts.files with list of
*	input files, including parsing of '@' lists
*----------------------------------------------------------------------------*/
void parse_argv( int argc, char *argv[] )
{
    int arg;

    init_module();

    if ( argc == 1 )
        exit_copyright();				/* exit if no arguments */

    process_options( &arg, argc, argv );	/* process all options, set arg to next */

    if ( arg >= argc )
        error_no_src_file();			/* no source file */

    if ( opts.verbose )
        display_options();				/* display status messages of select assembler options */

    if ( ! get_num_errors() )
        process_files( arg, argc, argv );	/* process each source file */
}
Пример #11
0
void build_dev(char *fname, FILE *fp, FILE *fpo) {
	assert(fname);
	assert(fp);
	assert(fpo);

	process_files(fname, fp, "/dev", dev_callback);

	if (dev_out == NULL)
		fprintf(fpo, "private-dev\n");
	else {
		fprintf(fpo, "\n");
		fprintf(fpo, "# private-dev\n");
		fprintf(fpo, "# This is the list of devices accessed (on top of regular private-dev devices:\n");
		fprintf(fpo, "# ");
		FileDB *ptr = dev_out;
		while (ptr) {
			fprintf(fpo, "%s,", ptr->fname);
			ptr = ptr->next;
		}
		fprintf(fpo, "\n");
	}
}
Пример #12
0
void build_tmp(char *fname, FILE *fp, FILE *fpo) {
	assert(fname);
	assert(fp);
	assert(fpo);

	process_files(fname, fp, "/tmp", tmp_callback);

	if (tmp_out == NULL)
		fprintf(fpo, "private-tmp\n");
	else {
		fprintf(fpo, "\n");
		fprintf(fpo, "# private-tmp\n");
		fprintf(fpo, "# File accessed in /tmp directory:\n");
		fprintf(fpo, "# ");
		FileDB *ptr = tmp_out;
		while (ptr) {
			fprintf(fpo, "%s,", ptr->fname);
			ptr = ptr->next;
		}
		printf("\n");
	}
}
Пример #13
0
/**
 * RHash program entry point.
 *
 * @param argc number of program arguments including the program path
 * @param argv program arguments
 * @return the program exit code, zero on success and 1 on error
 */
int main(int argc, char *argv[])
{
	i18n_initialize(); /* initialize locale and translation */

	memset(&rhash_data, 0, sizeof(rhash_data));
	rhash_data.out = stdout; /* set initial output streams */
	rhash_data.log = stderr; /* can be altered by options later */

	init_hash_info_table();

	read_options(argc, argv); /* load config and parse command line options */
	prev_sigint_handler = signal(SIGINT, ctrl_c_handler); /* install SIGINT handler */
	rhash_library_init();

	/* in benchmark mode just run benchmark and exit */
	if(opt.mode & MODE_BENCHMARK) {
		unsigned flags = (opt.flags & OPT_BENCH_RAW ? RHASH_BENCHMARK_CPB | RHASH_BENCHMARK_RAW : RHASH_BENCHMARK_CPB);
		if((opt.flags & OPT_BENCH_RAW) == 0) {
			fprintf(rhash_data.out, _("%s v%s benchmarking...\n"), PROGRAM_NAME, VERSION);
		}
		rhash_run_benchmark(opt.sum_flags, flags, rhash_data.out);
		rsh_exit(0);
	}

	if(opt.n_files == 0) {
		if(argc > 1) {
			log_warning(_("no files/directories were specified at command line\n"));
		}

		/* print short usage help */
		log_msg(_("Usage: %s [OPTION...] <FILE>...\n\n"
			"Run `%s --help' for more help.\n"), CMD_FILENAME, CMD_FILENAME);
		rsh_exit(0);
	}

	/* setup printf formating string */
	rhash_data.printf_str = opt.printf_str;

	if(opt.template_file) {
		if(!load_printf_template()) rsh_exit(2);
	} else if(!rhash_data.printf_str && !(opt.mode & (MODE_CHECK | MODE_CHECK_EMBEDDED))) {
		/* initialize printf output format according to '--<hashname>' options */
		init_printf_format( (rhash_data.template_text = rsh_str_new()) );
		rhash_data.printf_str = rhash_data.template_text->str;

		if(opt.flags & OPT_VERBOSE) {
			char* str = rsh_strdup(rhash_data.printf_str);
			log_msg(_("Format string is: %s\n"), str_trim(str));
			free(str);
		}
	}

	if(rhash_data.printf_str) {
		rhash_data.print_list = parse_print_string(rhash_data.printf_str, &opt.sum_flags);
	}

	preprocess_files();
	process_files();

	options_destroy(&opt);
	rhash_destroy(&rhash_data);
	return (rhash_data.error_flag ? 1 : 0);
}
Пример #14
0
int main(int argc, char** argv)
{
    try {
        int c;
        // int digit_optind = 0;

        while (1) {
            // int this_option_index = optind ? optind : 1;
            int option_index = 0;
            static struct option long_options[] = {
                { "help",    no_argument, nullptr, 0 },
                { "version", no_argument, nullptr, 0 },
                { 0,         0,           nullptr, 0 }
            };

            c = getopt_long(argc, argv, "", long_options, &option_index);
            if (c == -1)
                break;

            switch (c) {
            case 0:
                if (std::strncmp(long_options[option_index].name, "help", strlen("help")) == 0)
                    print_help(argv[0]);
                if (std::strncmp(long_options[option_index].name, "version", strlen("version")) == 0)
                    print_version(argv[0]);
                break;

            case '?':
            default:
                print_usage(argv[0]);
                break;
            }
        }

        // no paths specified to process, so let the user know we need at least one
        if (optind >= argc)
            print_usage(argv[0]);

        // collect all the files from the paths specified by the user
        String_Bag paths_to_process;
        while (optind < argc)
            paths_to_process.push_back(argv[optind++]);
        std::cerr << "Paths to process " << paths_to_process.size() << '\n';
        File_Bag files = get_files_to_process(paths_to_process);
        std::cerr << "Files found " << files.size() << '\n';

        // write the hashes to our database
        sqlite_db db = open_or_create_db();
        process_files(files, db);
        auto rv = db.close();
        if (rv != SQLITE_OK)
            throw std::runtime_error(db.errmsg());
    }
    catch (os_error& ex) {
        std::cerr << argv[0] << ": os error " << ex.err() << " - " << ex.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }
    catch (std::runtime_error& ex) {
        std::cerr << argv[0] << ": " << ex.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }
    catch (std::exception& ex) {
        std::cerr << argv[0] << ": unknown error - " << ex.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
Пример #15
0
/**
 * RHash program entry point.
 *
 * @param argc number of program arguments including the program path
 * @param argv program arguments
 * @return the program exit code, zero on success and 1 on error
 */
int main(int argc, char *argv[])
{
	find_file_options search_opt;
	timedelta_t timer;
	int sfv;

	i18n_initialize(); /* initialize locale and translation */

	memset(&rhash_data, 0, sizeof(rhash_data));
	rhash_data.out = stdout; /* set initial output streams */
	rhash_data.log = stderr; /* can be altered by options later */
	rhash_data.search_opt = &search_opt;

	init_hash_info_table();

	read_options(argc, argv); /* load config and parse command line options */
	prev_sigint_handler = signal(SIGINT, ctrl_c_handler); /* install SIGINT handler */
	rhash_library_init();

	/* in benchmark mode just run benchmark and exit */
	if(opt.mode & MODE_BENCHMARK) {
		unsigned flags = (opt.flags & OPT_BENCH_RAW ? RHASH_BENCHMARK_CPB | RHASH_BENCHMARK_RAW : RHASH_BENCHMARK_CPB);
		if((opt.flags & OPT_BENCH_RAW) == 0) {
			fprintf(rhash_data.out, _("%s v%s benchmarking...\n"), PROGRAM_NAME, VERSION);
		}
		rhash_run_benchmark(opt.sum_flags, flags, rhash_data.out);
		rsh_exit(0);
	}

	if(opt.n_files == 0) {
		if(argc > 1) {
			log_warning(_("no files/directories were specified at command line\n"));
		}

		/* print short usage help */
		log_msg(_("Usage: %s [OPTION...] <FILE>...\n\n"
			"Run `%s --help' for more help.\n"), CMD_FILENAME, CMD_FILENAME);
		rsh_exit(0);
	}

	/* setup printf formating string */
	rhash_data.printf_str = opt.printf_str;

	if(opt.template_file) {
		if(!load_printf_template()) rsh_exit(2);
	} else if(!rhash_data.printf_str && !(opt.mode & (MODE_CHECK | MODE_CHECK_EMBEDDED))) {
		/* initialize printf output format according to '--<hashname>' options */
		init_printf_format( (rhash_data.template_text = rsh_str_new()) );
		rhash_data.printf_str = rhash_data.template_text->str;

		if(opt.flags & OPT_VERBOSE) {
			char* str = rsh_strdup(rhash_data.printf_str);
			log_msg(_("Format string is: %s\n"), str_trim(str));
			free(str);
		}
	}

	if(rhash_data.printf_str) {
		rhash_data.print_list = parse_print_string(rhash_data.printf_str, &opt.sum_flags);
	}

	memset(&search_opt, 0, sizeof(search_opt));
	search_opt.max_depth = (opt.flags & OPT_RECURSIVE ? opt.find_max_depth : 0);
	search_opt.options = FIND_SKIP_DIRS;
	search_opt.call_back = find_file_callback;

	if((sfv = (opt.fmt == FMT_SFV && !opt.mode))) {
		print_sfv_banner(rhash_data.out);
	}

	/* pre-process files */
	if(sfv || opt.bt_batch_file) {
		/* note: errors are not reported on pre-processing */
		search_opt.call_back_data = (void*)1;
		process_files((const char**)opt.files, opt.n_files, &search_opt);

		fflush(rhash_data.out);
	}

	/* measure total processing time */
	rhash_timer_start(&timer);
	rhash_data.processed = 0;

	/* process files */
	search_opt.options |= FIND_LOG_ERRORS;
	search_opt.call_back_data = (void*)0;
	process_files((const char**)opt.files, opt.n_files, &search_opt);

	if((opt.mode & MODE_CHECK_EMBEDDED) && rhash_data.processed > 1) {
		print_check_stats();
	}

	if(!rhash_data.interrupted)
	{
		if(opt.bt_batch_file && rhash_data.rctx) {
			rhash_final(rhash_data.rctx, 0);
			save_torrent_to(opt.bt_batch_file, rhash_data.rctx);
		}

		if((opt.flags & OPT_SPEED) &&
			!(opt.mode & (MODE_CHECK | MODE_UPDATE)) &&
			rhash_data.processed > 1) {
			double time = rhash_timer_stop(&timer);
			print_time_stats(time, rhash_data.total_size, 1);
		}
	} else {
		/* check if interruption was not reported yet */
		if(rhash_data.interrupted == 1) report_interrupted();
	}

	options_destroy(&opt);
	rhash_destroy(&rhash_data);

	/* return non-zero error code if error occurred */
	return (rhash_data.error_flag ? 1 :
		search_opt.errors_count ? 2 :
		rhash_data.interrupted ? 3 : 0);
}
Пример #16
0
int sed_main(int argc UNUSED_PARAM, char **argv)
{
	unsigned opt;
	llist_t *opt_e, *opt_f;
	char *opt_i;

#if ENABLE_LONG_OPTS
	static const char sed_longopts[] ALIGN1 =
		/* name             has_arg             short */
		"in-place\0"        Optional_argument   "i"
		"regexp-extended\0" No_argument         "r"
		"quiet\0"           No_argument         "n"
		"silent\0"          No_argument         "n"
		"expression\0"      Required_argument   "e"
		"file\0"            Required_argument   "f";
#endif

	INIT_G();

	/* destroy command strings on exit */
	if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);

	/* Lie to autoconf when it starts asking stupid questions. */
	if (argv[1] && strcmp(argv[1], "--version") == 0) {
		puts("This is not GNU sed version 4.0");
		return 0;
	}

	/* do normal option parsing */
	opt_e = opt_f = NULL;
	opt_i = NULL;
	/* -i must be first, to match OPT_in_place definition */
	/* -E is a synonym of -r:
	 * GNU sed 4.2.1 mentions it in neither --help
	 * nor manpage, but does recognize it.
	 */
	opt = getopt32long(argv, "^"
			"i::rEne:*f:*"
			"\0" "nn"/*count -n*/,
			sed_longopts,
			&opt_i, &opt_e, &opt_f,
			&G.be_quiet); /* counter for -n */
	//argc -= optind;
	argv += optind;
	if (opt & OPT_in_place) { // -i
		die_func = cleanup_outname;
	}
	if (opt & (2|4))
		G.regex_type |= REG_EXTENDED; // -r or -E
	//if (opt & 8)
	//	G.be_quiet++; // -n (implemented with a counter instead)
	while (opt_e) { // -e
		add_cmd_block(llist_pop(&opt_e));
	}
	while (opt_f) { // -f
		char *line;
		FILE *cmdfile;
		cmdfile = xfopen_stdin(llist_pop(&opt_f));
		while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
			add_cmd(line);
			free(line);
		}
		fclose_if_not_stdin(cmdfile);
	}
	/* if we didn't get a pattern from -e or -f, use argv[0] */
	if (!(opt & 0x30)) {
		if (!*argv)
			bb_show_usage();
		add_cmd_block(*argv++);
	}
	/* Flush any unfinished commands. */
	add_cmd("");

	/* By default, we write to stdout */
	G.nonstdout = stdout;

	/* argv[0..(argc-1)] should be names of file to process. If no
	 * files were specified or '-' was specified, take input from stdin.
	 * Otherwise, we process all the files specified. */
	G.input_file_list = argv;
	if (!argv[0]) {
		if (opt & OPT_in_place)
			bb_error_msg_and_die(bb_msg_requires_arg, "-i");
		argv[0] = (char*)bb_msg_standard_input;
		/* G.last_input_file = 0; - already is */
	} else {
		goto start;

		for (; *argv; argv++) {
			struct stat statbuf;
			int nonstdoutfd;
			sed_cmd_t *sed_cmd;

			G.last_input_file++;
 start:
			if (!(opt & OPT_in_place)) {
				if (LONE_DASH(*argv)) {
					*argv = (char*)bb_msg_standard_input;
					process_files();
				}
				continue;
			}

			/* -i: process each FILE separately: */

			if (stat(*argv, &statbuf) != 0) {
				bb_simple_perror_msg(*argv);
				G.exitcode = EXIT_FAILURE;
				G.current_input_file++;
				continue;
			}
			G.outname = xasprintf("%sXXXXXX", *argv);
			nonstdoutfd = xmkstemp(G.outname);
			G.nonstdout = xfdopen_for_write(nonstdoutfd);
			/* Set permissions/owner of output file */
			/* chmod'ing AFTER chown would preserve suid/sgid bits,
			 * but GNU sed 4.2.1 does not preserve them either */
			fchmod(nonstdoutfd, statbuf.st_mode);
			fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);

			process_files();
			fclose(G.nonstdout);
			G.nonstdout = stdout;

			if (opt_i) {
				char *backupname = xasprintf("%s%s", *argv, opt_i);
				xrename(*argv, backupname);
				free(backupname);
			}
			/* else unlink(*argv); - rename below does this */
			xrename(G.outname, *argv); //TODO: rollback backup on error?
			free(G.outname);
			G.outname = NULL;

			/* Fix disabled range matches and mangled ",+N" ranges */
			for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
				sed_cmd->beg_line = sed_cmd->beg_line_orig;
				sed_cmd->end_line = sed_cmd->end_line_orig;
			}
		}
		/* Here, to handle "sed 'cmds' nonexistent_file" case we did:
		 * if (G.current_input_file[G.current_input_file] == NULL)
		 *	return G.exitcode;
		 * but it's not needed since process_files() works correctly
		 * in this case too. */
	}

	process_files();

	return G.exitcode;
}
Пример #17
0
int sed_main(int argc UNUSED_PARAM, char **argv)
{
	unsigned opt;
	llist_t *opt_e, *opt_f;
	char *opt_i;

#if ENABLE_LONG_OPTS
	static const char sed_longopts[] ALIGN1 =
		/* name             has_arg             short */
		"in-place\0"        Optional_argument   "i"
		"regexp-extended\0" No_argument         "r"
		"quiet\0"           No_argument         "n"
		"silent\0"          No_argument         "n"
		"expression\0"      Required_argument   "e"
		"file\0"            Required_argument   "f";
#endif

	int status = EXIT_SUCCESS;

	INIT_G();

	/* destroy command strings on exit */
	if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);

	/* Lie to autoconf when it starts asking stupid questions. */
	if (argv[1] && strcmp(argv[1], "--version") == 0) {
		puts("This is not GNU sed version 4.0");
		return 0;
	}

	/* do normal option parsing */
	opt_e = opt_f = NULL;
	opt_i = NULL;
	opt_complementary = "e::f::" /* can occur multiple times */
	                    "nn"; /* count -n */

	IF_LONG_OPTS(applet_long_options = sed_longopts);

	/* -i must be first, to match OPT_in_place definition */
	opt = getopt32(argv, "i::rne:f:", &opt_i, &opt_e, &opt_f,
			    &G.be_quiet); /* counter for -n */
	//argc -= optind;
	argv += optind;
	if (opt & OPT_in_place) { // -i
		atexit(cleanup_outname);
	}
	if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
	//if (opt & 0x4) G.be_quiet++; // -n
	while (opt_e) { // -e
		add_cmd_block(llist_pop(&opt_e));
	}
	while (opt_f) { // -f
		char *line;
		FILE *cmdfile;
		cmdfile = xfopen_for_read(llist_pop(&opt_f));
		while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
			add_cmd(line);
			free(line);
		}
		fclose(cmdfile);
	}
	/* if we didn't get a pattern from -e or -f, use argv[0] */
	if (!(opt & 0x18)) {
		if (!*argv)
			bb_show_usage();
		add_cmd_block(*argv++);
	}
	/* Flush any unfinished commands. */
	add_cmd("");

	/* By default, we write to stdout */
	G.nonstdout = stdout;

	/* argv[0..(argc-1)] should be names of file to process. If no
	 * files were specified or '-' was specified, take input from stdin.
	 * Otherwise, we process all the files specified. */
	if (argv[0] == NULL) {
		if (opt & OPT_in_place)
			bb_error_msg_and_die(bb_msg_requires_arg, "-i");
		add_input_file(stdin);
	} else {
		int i;

		for (i = 0; argv[i]; i++) {
			struct stat statbuf;
			int nonstdoutfd;
			FILE *file;
			sed_cmd_t *sed_cmd;

			if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
				add_input_file(stdin);
				process_files();
				continue;
			}
			file = fopen_or_warn(argv[i], "r");
			if (!file) {
				status = EXIT_FAILURE;
				continue;
			}
			add_input_file(file);
			if (!(opt & OPT_in_place)) {
				continue;
			}

			/* -i: process each FILE separately: */

			G.outname = xasprintf("%sXXXXXX", argv[i]);
			nonstdoutfd = xmkstemp(G.outname);
			G.nonstdout = xfdopen_for_write(nonstdoutfd);

			/* Set permissions/owner of output file */
			fstat(fileno(file), &statbuf);
			/* chmod'ing AFTER chown would preserve suid/sgid bits,
			 * but GNU sed 4.2.1 does not preserve them either */
			fchmod(nonstdoutfd, statbuf.st_mode);
			fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);

			process_files();
			fclose(G.nonstdout);
			G.nonstdout = stdout;

			if (opt_i) {
				char *backupname = xasprintf("%s%s", argv[i], opt_i);
				xrename(argv[i], backupname);
				free(backupname);
			}
			/* else unlink(argv[i]); - rename below does this */
			xrename(G.outname, argv[i]); //TODO: rollback backup on error?
			free(G.outname);
			G.outname = NULL;

			/* Re-enable disabled range matches */
			for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
				sed_cmd->beg_line = sed_cmd->beg_line_orig;
			}
		}
		/* Here, to handle "sed 'cmds' nonexistent_file" case we did:
		 * if (G.current_input_file >= G.input_file_count)
		 *	return status;
		 * but it's not needed since process_files() works correctly
		 * in this case too. */
	}
	process_files();

	return status;
}
Пример #18
0
static int ls(char **args, int num)
{
     char **found_files;
     int num_found = 0, total = 0;
     int status = 0;
     int retval;

#if defined(__APPLE__) && defined(__MACH__)
     add_error_table(&et_del_error_table);
#else
     initialize_del_error_table();
#endif
     
     if ((retval = initialize_tree())) {
	  error("initialize_tree");
	  return retval;
     }
     
     for ( ; num; num--) {
       if ((retval = get_the_files(args[num - 1], &num_found,
				   &found_files))) {
	 error(args[num - 1]);
	 status = retval;
	 continue;
       }

	  if (num_found) {
	       num_found = process_files(found_files, num_found);
	       if (num_found < 0) {
		    error("process_files");
		    status = error_code;
		    continue;
	       }
	       total += num_found;
	  }
	  else {
	       /* What we do at this point depends on exactly what the
	        * filename is.  There are several possible conditions:
		* 1. The filename has no wildcards in it, which means that
		*    if we couldn't find it, that means it doesn't
		*    exist.  Print a not found error.
		* 2. Filename is an existing directory, with no deleted
		*    files in it.  Print nothing.
		* 3. Filename doesn't exist, and there are wildcards in
		*    it.  Print "no match".
		* None of these are considered error conditions, so we
		* don't set the error flag.
		*/
	       if (no_wildcards(args[num - 1])) {
		    if (! directory_exists(args[num - 1])) {
			 set_error(ENOENT);
			 error(args[num - 1]);
			 status = error_code;
			 continue;
		    }
	       }
	       else {
		    set_error(DELETE_ENOMATCH);
		    error(args[num - 1]);
		    status = error_code;
		    continue;
	       }
	  }
     }
     if (total) {
	  if (list_files()) {
	       error("list_files");
	       return error_code;
	  }
     }
     if (yield) {
       char *friendly = space_to_friendly(space_total);
       printf("\nTotal space taken up by file%s: %s\n",
	      (total == 1 ? "" : "s"), friendly);
       free(friendly);
     }
     return status;
}
Пример #19
0
int sed_main(int argc ATTRIBUTE_UNUSED, char **argv)
{
	enum {
		OPT_in_place = 1 << 0,
	};
	unsigned opt;
	llist_t *opt_e, *opt_f;
	int status = EXIT_SUCCESS;

	INIT_G();

	/* destroy command strings on exit */
	if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);

	/* Lie to autoconf when it starts asking stupid questions. */
	if (argv[1] && !strcmp(argv[1], "--version")) {
		puts("This is not GNU sed version 4.0");
		return 0;
	}

	/* do normal option parsing */
	opt_e = opt_f = NULL;
	opt_complementary = "e::f::" /* can occur multiple times */
	                    "nn"; /* count -n */
	opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
			    &G.be_quiet); /* counter for -n */
	//argc -= optind;
	argv += optind;
	if (opt & OPT_in_place) { // -i
		atexit(cleanup_outname);
	}
	if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
	//if (opt & 0x4) G.be_quiet++; // -n
	while (opt_e) { // -e
		add_cmd_block(llist_pop(&opt_e));
	}
	while (opt_f) { // -f
		char *line;
		FILE *cmdfile;
		cmdfile = xfopen(llist_pop(&opt_f), "r");
		while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
			add_cmd(line);
			free(line);
		}
		fclose(cmdfile);
	}
	/* if we didn't get a pattern from -e or -f, use argv[0] */
	if (!(opt & 0x18)) {
		if (!*argv)
			bb_show_usage();
		add_cmd_block(*argv++);
	}
	/* Flush any unfinished commands. */
	add_cmd("");

	/* By default, we write to stdout */
	G.nonstdout = stdout;

	/* argv[0..(argc-1)] should be names of file to process. If no
	 * files were specified or '-' was specified, take input from stdin.
	 * Otherwise, we process all the files specified. */
	if (argv[0] == NULL) {
		if (opt & OPT_in_place)
			bb_error_msg_and_die(bb_msg_requires_arg, "-i");
		add_input_file(stdin);
		process_files();
	} else {
		int i;
		FILE *file;

		for (i = 0; argv[i]; i++) {
			struct stat statbuf;
			int nonstdoutfd;

			if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
				add_input_file(stdin);
				process_files();
				continue;
			}
			file = fopen_or_warn(argv[i], "r");
			if (!file) {
				status = EXIT_FAILURE;
				continue;
			}
			if (!(opt & OPT_in_place)) {
				add_input_file(file);
				continue;
			}

			G.outname = xasprintf("%sXXXXXX", argv[i]);
			nonstdoutfd = mkstemp(G.outname);
			if (-1 == nonstdoutfd)
				bb_perror_msg_and_die("cannot create temp file %s", G.outname);
			G.nonstdout = fdopen(nonstdoutfd, "w");

			/* Set permissions of output file */

			fstat(fileno(file), &statbuf);
			fchmod(nonstdoutfd, statbuf.st_mode);
			add_input_file(file);
			process_files();
			fclose(G.nonstdout);

			G.nonstdout = stdout;
			/* unlink(argv[i]); */
			xrename(G.outname, argv[i]);
			free(G.outname);
			G.outname = NULL;
		}
		if (G.input_file_count > G.current_input_file)
			process_files();
	}

	return status;
}
Пример #20
0
int main(int argc, char** argv)
{
	SETTINGS settings;
	int      option_index = 1,
	         ret,
	         i,
	         bits;

#ifdef _WIN32
 	char     CmdDir[MAX_PATH];
 	char     *p;
#endif

	memset(&settings, 0, sizeof(settings));
	settings.first_file = 1;
	settings.radio = 1;
	settings.clip_prev = 1;
	settings.outbitwidth = 16;
	settings.format = WAV_NO_FMT;

#ifdef _WIN32
	/* Is this good enough? Or do we need to consider multi-byte codepages as 
	* well? 
	*/
	SetConsoleOutputCP(GetACP());

	GetModuleFileName(NULL, CmdDir, MAX_PATH);
	p = strrchr(CmdDir, '\\') + 1;
	p[0] = '\0';
#endif

	while ((ret = getopt_long(argc, argv, ARG_STRING, long_options, &option_index)) != -1) {
		switch(ret) {
			case 0:
				if (!strcmp(long_options[option_index].name, "force")) {
					settings.force = 1;
				}
				else if (!strcmp(long_options[option_index].name, "undo-gain")) {
					settings.undo = 1;
				}
				else {
					fprintf(stderr, "Internal error parsing command line options\n");
					exit(1);
				}
				break;
			case 'h':
				usage();
				exit(0);
				break;
			case 'a':
				settings.audiophile = 1;
				break;
			case 'r':
				settings.radio = 1;
				break;
			case 'q':
				settings.adc = 1;
				break;
			case 'p':
				settings.no_offset = 1;
				break;
			case 'c':
				settings.apply_gain = 0;
				break;
			case 'x':
				settings.scale = 1;
				break;
			case 'y':
				settings.apply_gain = 1;
				settings.scale = 0;
				break;
			case 'w':
				settings.write_chunk = 1;
				break;
			case 's':
				settings.fast = 1;
				break;
			case 'o':
				settings.std_out = 1;
				break;
#ifdef ENABLE_RECURSIVE
			case 'z':
				settings.recursive = 1;
				break;
#endif
			case 'l':
				write_to_log = 1;
#ifdef _WIN32
				strcpy(log_file_name, CmdDir);
				strcat(log_file_name, LOG_NAME);
#else
				strcpy(log_file_name, LOG_NAME);
#endif
				break;
			case 'f':
				write_to_log = 1;
				strcpy(log_file_name, optarg);
				break;
			case 'n':
				settings.clip_prev = 0;
				break;
			case 'd':
				settings.need_to_process = 1;
				settings.dithering = 1;
   				if(sscanf(optarg, "%d", &settings.shapingtype) != 1) {
	    				fprintf(stderr, "Warning: dither type %s not recognised, using default\n", optarg);
		    			break;
				}
				if (settings.shapingtype == 0)
					settings.dithering = 0;
				else if (settings.shapingtype == 1)
					settings.shapingtype = 0;
				else if (settings.shapingtype == 2)
					settings.shapingtype = 1;
				else if (settings.shapingtype == 3)
					settings.shapingtype = 2;
				else if (settings.shapingtype == 4)
					settings.shapingtype = 3;
				break;
			case 't':
				settings.limiter = 1;
				break;
			case 'g':
   				if(sscanf(optarg, "%lf", &settings.man_gain) != 1) {
	    				fprintf(stderr, "Warning: manual gain %s not recognised, ignoring\n", optarg);
					break;
				}
				if(settings.man_gain < -20.0) {
	    				fprintf(stderr, "Warning: manual gain %s is out of range, "
					                 "applying gain of -20.0dB\n", optarg);
					settings.man_gain = -20.0;
				}
				else if(settings.man_gain > 12.0) {
	    				fprintf(stderr, "Warning: manual gain %s is out of range, "
					                 "applying gain of +12.0dB\n", optarg);
					settings.man_gain = 12.0;
				}
				break;
			case 'b':
				settings.need_to_process = 1;
   				if(sscanf(optarg, "%d", &bits) != 1) {
	    				fprintf(stderr, "Warning: output format %s not recognised, using default\n", optarg);
		    			break;
				}
				if (bits == 1) {
					settings.outbitwidth = 8;
					settings.format = WAV_FMT_8BIT;
		    			break;
				}
				else if (bits == 2) {
					settings.outbitwidth = 16;
					settings.format = WAV_FMT_16BIT;
		    			break;
				}
				else if (bits == 3) {
					settings.outbitwidth = 24;
					settings.format = WAV_FMT_24BIT;
		    			break;
				}
				else if (bits == 4) {
					settings.outbitwidth = 32;
					settings.format = WAV_FMT_32BIT;
		    			break;
				}
				else if (bits == 5) {
					settings.outbitwidth = 32;
					settings.format = WAV_FMT_FLOAT;
		    			break;
				}
				else if (bits == 6) {
					settings.outbitwidth = 16;
					settings.format = WAV_FMT_AIFF;
		    			break;
				}
				else {
	    				fprintf(stderr, "Warning: output format %s not recognised, using default\n", optarg);
					break;
				}
				break;
#ifdef _WIN32
			case 'e': {
				char *p;
				int k;
				char * lpPart[MAX_PATH]={NULL};

				settings.cmd = (char *) malloc(1024*8); /* 8Kb is XP's limit */
				if (settings.cmd == NULL) {
					fprintf(stderr, "Failed to allocate memory for cmd...\n");
					return 1;
				}

				p = settings.cmd;

				k = GetFullPathName(argv[optind - 1], 1024*8, p, lpPart);
				k = GetShortPathName(p, p, MAX_PATH);
				if (k == 0) {
					p += sprintf (p, "%s", argv[optind - 1]);
				} else {
					p += k;
				}

				for (k = optind; k < argc; ++k) {
					p += sprintf(p, " \"%s\"", argv[k]);
				}

				argc = optind;
				break;
			}
#endif
		}
	}
	if (settings.undo == 1) {
		settings.write_chunk = 0;
		settings.no_offset = 1;
	}

	if (optind >= argc) {
		fprintf(stderr, _("No files specified.\n"));
		usage();
		return EXIT_SUCCESS;
	}

	if (write_to_log) {
		write_log("Command line:\n\t");
		for(i = 0; i < argc; i++)
			write_log("%s ",  argv[i]);
		write_log("\n");
	}

	if (!strcmp(argv[optind], "-")) {
		double track_peak, track_gain;
		double dc_offset;
		double offset;
		if (!get_gain("-", &track_peak, &track_gain,
		              &dc_offset, &offset, &settings))
			return -1;
	}
	else {
		for (i = optind; i < argc; ++i) {
#ifdef ENABLE_RECURSIVE
			if (process_argument(argv[i], &settings) < 0) {
				free_list(settings.file_list);
				return EXIT_FAILURE;
			}
#else
			if (add_to_list(&settings.file_list, argv[i]) < 0)
				return EXIT_FAILURE;
#endif
		}

		/* Process files (perhaps remaining) in list */
		ret = process_files(settings.file_list, &settings, ".");
		free_list(settings.file_list);
		settings.file_list = NULL;
		if (settings.cmd) free(settings.cmd);
		settings.cmd = NULL;
	}

	return (ret < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
}
Пример #21
0
int main(int _argc,const char *_argv[]){

  cov_state     cvs[NUM_PROCS];
#if COMPUTE_NATHAN
  trans_ctx     ctx[NUM_PROCS];
  double        r[SUPPORT*SUPPORT]; /* maximum for 2d */
#else
  trans_ctx     *ctx=NULL;
#endif
  int           i;

#if BLOCKSIZE==4
  f=OD_FILTER_PARAMS4;
#elif BLOCKSIZE==8
  f=OD_FILTER_PARAMS8;
#elif BLOCKSIZE==16
  f=OD_FILTER_PARAMS16;
#else
# error "Need filter params for this block size."
#endif

  for(i=0;i<NUM_PROCS;i++){
#if USE_2D
    cov_init(&cvs[i],SUPPORT*SUPPORT);
#else
    cov_init(&cvs[i],SUPPORT);
#endif
  }

#if COMPUTE_NATHAN
  for(i=0;i<NUM_PROCS;i++){
#if USE_2D
    trans_data_init(&ctx[i].td,SUPPORT*SUPPORT);
#else
    trans_data_init(&ctx[i].td,SUPPORT);
#endif
  }
#endif

  OD_OMP_SET_THREADS(NUM_PROCS);
  process_files(ctx,cvs,_argc,_argv);

  for(i=1;i<NUM_PROCS;i++)
      cov_combine(&cvs[0],&cvs[i]);
  cov_compute(&cvs[0]);

#if COMPUTE_NATHAN
  for(i=1;i<NUM_PROCS;i++)
    trans_data_combine(&ctx[0].td,&ctx[i].td);
  trans_data_normalize(&ctx[0].td);
#endif

#if PRINT_COV
  {
    int i,j;
    fprintf(stdout,"collapsed_cov=\n");
    for(j=0;j<cvs[0].sz/SUPPORT;j++){
      for(i=0;i<SUPPORT;i++){
        fprintf(stdout,"%s  %- 12.6G",i>0?",":"",cvs[0].cov[j*SUPPORT+i]);
      }
      fprintf(stdout,"\n");
    }
  }
#endif

#if USE_2D
#if COMPUTE_NATHAN
  fprintf(stdout,"original cg=%-24.16G\n",
          cg_2d((double(*)[SUPPORT][SUPPORT][SUPPORT])ctx[0].td.cov,f));
  trans_data_collapse(&ctx[0].td,SUPPORT,r);
  fprintf(stdout,"collapse cg=%-24.16G\n",
          cg_2d_collapsed((double(*)[SUPPORT])r,f));
#endif
  fprintf(stdout,"monty cg=%-24.16G\n",
          cg_2d_collapsed((double(*)[SUPPORT])cvs[0].cov,f));
#else
#if COMPUTE_NATHAN
  fprintf(stdout,"original cg=%-24.16G\n",
          cg_1d((double (*)[SUPPORT])ctx[0].td.cov,f));
  trans_data_collapse(&ctx[0].td,1,r);
  fprintf(stdout,"collapse cg=%-24.16G\n",
          cg_1d_collapsed(r,f));
#endif
  fprintf(stdout,"monty cg=%-24.16G\n",
          cg_1d_collapsed(cvs[0].cov,f));
#endif

  for(i=0;i<NUM_PROCS;i++)
    cov_clear(&cvs[i]);

#if COMPUTE_NATHAN
  for(i=0;i<NUM_PROCS;i++)
    trans_data_clear(&ctx[i].td);
#endif

  return EXIT_SUCCESS;
}