Пример #1
0
int main (int argc, char **argv)
{
	int i;
	FILE *fd;

	--argc, ++argv;

	if (!argc){
		process_stream (stdin);
	}else{
		for (i=0; i < argc; ++i){
			fd = fopen (argv [i], "r");
			if (!fd){
				perror ("fopen(3) failed");
				exit (1);
			}

			process_stream (fd);
			fclose (fd);
		}
	}

	if (line_num >= 1)
		xputc ('\n', stdout);

	return 0;
}
Пример #2
0
int main(int argc, char* argv[])
{
	int port, ipaddress;
	
	if(argc == 1)
	{
		//
		if(!initialize_video_stream(NULL) || !initialize_ncurses())
			return 1;
	
		//
		process_stream(get_frame_from_video_stream, convert_and_render);
	
		//
		uninitialize_video_stream();
		uninitialize_ncurses();
	}
	else if(argc==2)
	{	
		//
		sscanf(argv[1], "%d", &port);
		
		//
		if(!initialize_ip_communication(NULL, port) || !initialize_ncurses())
			return 1;
	
		//
		process_stream(get_frame_over_ip, render);
	
		//
		uninitialize_ncurses();
		uninitialize_ip_communication();
	}
	else if(argc == 3)
	{
		//
		sscanf(argv[2], "%d", &port);
		
		//
		if(!initialize_ip_communication(argv[1], port) || !initialize_video_stream(NULL) || !initialize_ncurses())
			return 1;
	
		//
		process_stream(get_frame_from_video_stream, send_frame_over_ip);
	
		//
		uninitialize_video_stream();
		uninitialize_ncurses();
		uninitialize_ip_communication();
	}
	else
		return 1;

    //
    return 0;
}
Пример #3
0
/* Data initialization */
int
process_file(struct config *conf, char *file)
{
	int r;
	FILE *stream;

	if (!conf->keywords) {
		condlog(0, "No keywords alocated");
		return 1;
	}
	stream = fopen(file, "r");
	if (!stream) {
		condlog(0, "couldn't open configuration file '%s': %s",
			file, strerror(errno));
		return 1;
	}

	/* Stream handling */
	line_nr = 0;
	r = process_stream(conf, stream, conf->keywords, file);
	fclose(stream);
	//free_keywords(keywords);

	return r;
}
Пример #4
0
void diff (const char* keyfile, const char* filename)
{
	keys_t		keys;
	load_keys(keyfile, &keys);

	// Open the file
	std::ifstream	in(filename);
	if (!in) {
		perror(filename);
		std::exit(1);
	}
	in.exceptions(std::fstream::badbit);

	// Read the header to get the nonce and determine if it's actually encrypted
	char		header[22];
	in.read(header, 22);
	if (!in || in.gcount() != 22 || memcmp(header, "\0GITCRYPT\0", 10) != 0) {
		// File not encrypted - just copy it out to stdout
		std::cout.write(header, in.gcount()); // don't forget to include the header which we read!
		char	buffer[1024];
		while (in) {
			in.read(buffer, sizeof(buffer));
			std::cout.write(buffer, in.gcount());
		}
		return;
	}

	process_stream(in, std::cout, &keys.enc, reinterpret_cast<uint8_t*>(header + 10));
}
Пример #5
0
static int real_php_log_buffer(zval *msg_buffer, char *opt, int opt_len TSRMLS_DC)
{
    php_stream *stream = NULL;
    HashTable *ht;

#if PHP_VERSION_ID >= 70000
    zend_ulong num_key;
    zend_string *str_key;
    zval *entry;
#else
    zval **log;
#endif

    stream = process_stream(opt,opt_len TSRMLS_CC);

    if (stream == NULL)
    {
        return FAILURE;
    }

#if PHP_VERSION_ID >= 70000

    ht = HASH_OF(msg_buffer);
    ZEND_HASH_FOREACH_KEY_VAL(ht, num_key, str_key, entry)
    {
        zend_string *s = zval_get_string(entry);
        php_stream_write(stream, ZSTR_VAL(s), ZSTR_LEN(s));
        zend_string_release(s);
    }
Пример #6
0
/* Data initialization */
int
init_data(char *conf_file, void (*init_keywords) (void))
{
	int r;

	if (!keywords)
		keywords = vector_alloc();
	if (!keywords)
		return 1;
	stream = fopen(conf_file, "r");
	if (!stream) {
		syslog(LOG_WARNING, "Configuration file open problem");
		return 1;
	}

	/* Init Keywords structure */
	(*init_keywords) ();

/* Dump configuration *
  vector_dump(keywords);
  dump_keywords(keywords, 0);
*/

	/* Stream handling */
	r = process_stream(keywords);
	fclose(stream);
	//free_keywords(keywords);

	return r;
}
Пример #7
0
/*
 * Main
 */
int         main(int argc, char *argv[]) {
    config  cfg;

    memset(&cfg, 0, sizeof(cfg));
    fail_if_aes_ni_absent();
    set_configuration(&cfg, argc, argv);
    process_stream(&cfg);
    exit(EXIT_SUCCESS);
}
Пример #8
0
/* Process a single file, given its name.
 */
static void
process_named_file(const char *name) {
  FILE *f=fopen(name, "r");
  if (!f) { warn("%s", name); ++n_errors; }
  else {
    process_stream(f, name);
    if (ferror(f)) { warn("%s", name); ++n_errors; }
    fclose(f);
  }
}
Пример #9
0
void process_file(const std::string& name)
{
   current_file = name;
   std::ifstream is(name.c_str());
   if(is.bad())
   {
      std::cerr << "Unable to open file " << name << std::endl;
   }
   process_stream(is);
}
Пример #10
0
static void
process_file(const char *file)
{
	int rc;
	FILE *fp;

	/* Check for standard input. */
	if (file[0] == '-' && file[1] == '\0')
		(void) process_stream(stdin);

	/* Otherwise open the log file. */
	else {
		/* Handle re-opening of log file for -f option. */
		for (rc = -1; rc && (fp = fopen(file, "rb")) != NULL; ) {
			rc = process_stream(fp);
			(void) fclose(fp);
		}

 		if (fp == NULL)
			(void) fprintf(stderr, "%s: %s (%d)\n", file, strerror(errno), errno);
	}
}
Пример #11
0
/* Process a single file, given its name.
 */
static void
process_named_file(const char *name)
{
	FILE *f;

	if ((f = fopen(name, "r")) == NULL) {
		warn("%s", name);
		++n_errors;
	} else {
		process_stream(f, name);
		fclose(f);
	}
}
Пример #12
0
void
process_stream(vector_t *keywords_vec)
{
	int i;
	keyword_t *keyword_vec;
	char *str;
	char *buf;
	vector_t *strvec;
	vector_t *prev_keywords = current_keywords;
	current_keywords = keywords_vec;

	buf = zalloc(MAXBUF);
	while (read_line(buf, MAXBUF)) {
		strvec = alloc_strvec(buf);
		memset(buf,0, MAXBUF);

		if (!strvec)
			continue;

		str = vector_slot(strvec, 0);

		if (!strcmp(str, EOB) && kw_level > 0) {
			free_strvec(strvec);
			break;
		}

		for (i = 0; i < vector_size(keywords_vec); i++) {
			keyword_vec = vector_slot(keywords_vec, i);

			if (!strcmp(keyword_vec->string, str)) {
				if (keyword_vec->handler)
					(*keyword_vec->handler) (strvec);

				if (keyword_vec->sub) {
					kw_level++;
					process_stream(keyword_vec->sub);
					kw_level--;
					if (keyword_vec->sub_close_handler)
						(*keyword_vec->sub_close_handler) ();
				}
				break;
			}
		}

		free_strvec(strvec);
	}

	current_keywords = prev_keywords;
	free(buf);
	return;
}
Пример #13
0
int
process_stream(vector keywords)
{
	int i;
	int r = 0;
	struct keyword *keyword;
	char *str;
	char *buf;
	vector strvec;

	buf = MALLOC(MAXBUF);

	if (!buf)
		return 1;

	while (read_line(buf, MAXBUF)) {
		strvec = alloc_strvec(buf);
		memset(buf,0, MAXBUF);

		if (!strvec)
			continue;

		str = VECTOR_SLOT(strvec, 0);

		if (!strcmp(str, EOB) && kw_level > 0) {
			free_strvec(strvec);
			break;
		}

		for (i = 0; i < VECTOR_SIZE(keywords); i++) {
			keyword = VECTOR_SLOT(keywords, i);

			if (!strcmp(keyword->string, str)) {
				if (keyword->handler)
					r += (*keyword->handler) (strvec);

				if (keyword->sub) {
					kw_level++;
					r += process_stream(keyword->sub);
					kw_level--;
				}
				break;
			}
		}

		free_strvec(strvec);
	}

	FREE(buf);
	return r;
}
Пример #14
0
void read_conf_file(char *conf_file)
{
	FILE *stream;
	char *path;
	int ret;

	glob_t globbuf;

	globbuf.gl_offs = 0;
	glob(conf_file, 0, NULL, &globbuf);

	int i;
	for(i = 0; i < globbuf.gl_pathc; i++){
		log_message(LOG_INFO, "Opening file '%s'.", globbuf.gl_pathv[i]);
		stream = fopen(globbuf.gl_pathv[i], "r");
		if (!stream) {
			log_message(LOG_INFO, "Configuration file '%s' open problem (%s)..."
				       , globbuf.gl_pathv[i], strerror(errno));
			return;
		}
		current_stream = stream;
		current_conf_file = globbuf.gl_pathv[i];
		
		char prev_path[MAXBUF];
		path = getcwd(prev_path, MAXBUF);
		if (!path) {
			log_message(LOG_INFO, "getcwd(%s) error (%s)"
					    , prev_path, strerror(errno));
		}

		char *confpath = strdup(globbuf.gl_pathv[i]);
		dirname(confpath);
		ret = chdir(confpath);
		if (ret < 0) {
			log_message(LOG_INFO, "chdir(%s) error (%s)"
					    , confpath, strerror(errno));
		}
		free(confpath);
		process_stream(current_keywords);
		fclose(stream);

		ret = chdir(prev_path);
		if (ret < 0) {
			log_message(LOG_INFO, "chdir(%s) error (%s)"
					    , prev_path, strerror(errno));
		}
	}

	globfree(&globbuf);
}
Пример #15
0
// Decrypt contents of stdin and write to stdout
void smudge (const char* keyfile)
{
	keys_t		keys;
	load_keys(keyfile, &keys);

	// Read the header to get the nonce and make sure it's actually encrypted
	char		header[22];
	std::cin.read(header, 22);
	if (!std::cin || std::cin.gcount() != 22 || memcmp(header, "\0GITCRYPT\0", 10) != 0) {
		std::clog << "File not encrypted\n";
		std::exit(1);
	}

	process_stream(std::cin, std::cout, &keys.enc, reinterpret_cast<uint8_t*>(header + 10));
}
Пример #16
0
static void
read_conf_file(const char *conf_file)
{
	FILE *stream;
	char *path;
	int ret;
	glob_t globbuf;
	size_t i;
	int	res;
	struct stat stb;

	globbuf.gl_offs = 0;
	res = glob(conf_file, 0, NULL, &globbuf);

	if (res) {
		log_message(LOG_INFO, "Unable to find config file(s) '%s'.", conf_file);
		return;
	}

	for(i = 0; i < globbuf.gl_pathc; i++){
		log_message(LOG_INFO, "Opening file '%s'.", globbuf.gl_pathv[i]);
		stream = fopen(globbuf.gl_pathv[i], "r");
		if (!stream) {
			log_message(LOG_INFO, "Configuration file '%s' open problem (%s) - skipping"
				       , globbuf.gl_pathv[i], strerror(errno));
			continue;
		}

		/* Make sure what we have opened is a regular file, and not for example a directory */
		if (fstat(fileno(stream), &stb) ||
		    !S_ISREG(stb.st_mode)) {
			log_message(LOG_INFO, "Configuration file '%s' is not a regular file - skipping", globbuf.gl_pathv[i]);
			fclose(stream);
			continue;
		}

		current_stream = stream;
		current_conf_file = globbuf.gl_pathv[i];

		char prev_path[MAXBUF];
		path = getcwd(prev_path, MAXBUF);
		if (!path) {
			log_message(LOG_INFO, "getcwd(%s) error (%s)"
					    , prev_path, strerror(errno));
		}

		char *confpath = strdup(globbuf.gl_pathv[i]);
		dirname(confpath);
		ret = chdir(confpath);
		if (ret < 0) {
			log_message(LOG_INFO, "chdir(%s) error (%s)"
					    , confpath, strerror(errno));
		}
		free(confpath);
		process_stream(current_keywords, 0);
		fclose(stream);

		ret = chdir(prev_path);
		if (ret < 0) {
			log_message(LOG_INFO, "chdir(%s) error (%s)"
					    , prev_path, strerror(errno));
		}
	}

	globfree(&globbuf);
}
Пример #17
0
static void
process_stream(vector_t *keywords_vec, int need_bob)
{
	unsigned int i;
	keyword_t *keyword_vec;
	char *str;
	char *buf;
	vector_t *strvec;
	vector_t *prev_keywords = current_keywords;
	current_keywords = keywords_vec;
	int bob_needed = 0;
	size_t config_id_len = 0;
	char *buf_start;

	if (config_id)
		config_id_len = strlen(config_id);

	buf = MALLOC(MAXBUF);
	while (read_line(buf, MAXBUF)) {
		if (buf[0] == '@') {
			/* If the line starts '@', check the following word matches the system id */
			if (!config_id)
				continue;
			buf_start = strpbrk(buf, " \t");
			if ((size_t)(buf_start - (buf + 1)) != config_id_len ||
			    strncmp(buf + 1, config_id, config_id_len))
				continue;
		}
		else
			buf_start = buf;

		strvec = alloc_strvec(buf_start);
		memset(buf, 0, MAXBUF);

		if (!strvec)
			continue;

		str = vector_slot(strvec, 0);

		if (skip_sublevel == -1) {
			/* There wasn't a '{' on the keyword line */
			if (!strcmp(str, BOB)) {
				/* We've got the opening '{' now */
				skip_sublevel = 1;
				free_strvec(strvec);
				continue;
			}
			else {
				/* The skipped keyword doesn't have a {} block, so we no longer want to skip */
				skip_sublevel = 0;
			}
		}
		if (skip_sublevel) {
			for (i = 0; i < vector_size(strvec); i++) {
				str = vector_slot(strvec,i);
				if (!strcmp(str,BOB))
					skip_sublevel++;
				else if (!strcmp(str,EOB)) {
					if (--skip_sublevel == 0)
						break;
				}
			}

			free_strvec(strvec);
			continue;
		}

		if (need_bob) {
			need_bob = 0;
			if (!strcmp(str, BOB) && kw_level > 0) {
				free_strvec(strvec);
				continue;
			}
			else
				log_message(LOG_INFO, "Missing '{' at beginning of configuration block");
		}
		else if (!strcmp(str, BOB)) {
			log_message(LOG_INFO, "Unexpected '{' - ignoring");
			free_strvec(strvec);
			continue;
		}

		if (!strcmp(str, EOB) && kw_level > 0) {
			free_strvec(strvec);
			break;
		}

		for (i = 0; i < vector_size(keywords_vec); i++) {
			keyword_vec = vector_slot(keywords_vec, i);

			if (!strcmp(keyword_vec->string, str)) {
				if (!keyword_vec->active) {
					if (!strcmp(vector_slot(strvec, vector_size(strvec)-1), BOB))
						skip_sublevel = 1;
					else
						skip_sublevel = -1;
				}

				/* There is an inconsistency here. 'static_ipaddress' for example
				 * does not have sub levels, but needs a '{' */
				if (keyword_vec->sub) {
					/* Remove a trailing '{' */
					char *bob = vector_slot(strvec, vector_size(strvec)-1) ;
					if (!strcmp(bob, BOB)) {
						vector_unset(strvec, vector_size(strvec)-1);
						FREE(bob);
						bob_needed = 0;
					}
					else
						bob_needed = 1;
				}

				if (keyword_vec->handler)
					(*keyword_vec->handler) (strvec);

				if (keyword_vec->sub) {
					kw_level++;
					process_stream(keyword_vec->sub, bob_needed);
					kw_level--;
					if (keyword_vec->active && keyword_vec->sub_close_handler)
						(*keyword_vec->sub_close_handler) ();
				}
				break;
			}
		}

		if (i >= vector_size(keywords_vec))
			log_message(LOG_INFO, "Unknown keyword '%s'", str );

		free_strvec(strvec);
	}

	current_keywords = prev_keywords;
	FREE(buf);
	return;
}
Пример #18
0
//! process command line arguments and data
int ImportData::main(int argc, char* argv[])
{
    FieldSet::check_detect();

    // database connection to establish
    std::string opt_db_conninfo;

    //! parse command line parameters using SimpleOpt
    CSimpleOpt args(argc, argv, sopt_list);

    while (args.Next())
    {
        if (args.LastError() != SO_SUCCESS) {
            OUT(argv[0] << ": invalid command line argument '" << args.OptionText() << "'");
            return EXIT_FAILURE;
        }

        switch (args.OptionId())
        {
        case OPT_HELP: default:
            return print_usage(argv[0]);

        case OPT_FIRSTLINE:
            mopt_firstline = true;
            break;

        case OPT_ALL_LINES:
            mopt_all_lines = true;
            break;

        case OPT_VERBOSE:
            mopt_verbose++;
            break;

        case OPT_NO_DUPLICATE:
            mopt_noduplicates = true;
            break;

        case OPT_COLUMN_NUMBERS:
            mopt_colnums = true;
            break;

        case OPT_EMPTY_OKAY:
            mopt_empty_okay = true;
            break;

        case OPT_TEMPORARY_TABLE:
            mopt_temporary_table = true;
            break;

        case OPT_PERMANENT_TABLE:
            mopt_temporary_table = false;
            break;

        case OPT_DATABASE:
            opt_db_conninfo = args.OptionArg();
            break;
        }
    }

    // no table name given
    if (args.FileCount() == 0) {
        print_usage(argv[0]);
	return EXIT_FAILURE;
    }

    m_tablename = args.File(0);

    // maybe connect to database
    bool opt_dbconnect = false;
    if (!g_db)
    {
        if (!g_db_connect(opt_db_conninfo))
            OUT_THROW("Fatal: could not connect to a SQL database");
        opt_dbconnect = true;
    }

    // begin transaction
    g_db->execute("BEGIN");

    // process file commandline arguments
    if (args.FileCount())
    {
        // glob to expand wild cards in arguments

        int gflags = SG_GLOB_TILDE | SG_GLOB_ONLYFILE;
        if (mopt_empty_okay) gflags |= SG_GLOB_NOCHECK;

        CSimpleGlob glob(SG_GLOB_NODOT | SG_GLOB_NOCHECK);
        if (SG_SUCCESS != glob.Add(args.FileCount() - 1, args.Files() + 1)) {
            OUT_THROW("Error while globbing files");
            return EXIT_FAILURE;
        }

        for (int fi = 0; fi < glob.FileCount(); ++fi)
        {
            const char* fname = glob.File(fi);

            m_count = 0;
            std::ifstream in(fname);
            if (!in.good()) {
                if (mopt_empty_okay)
                    OUT("Error reading " << fname << ": " << strerror(errno));
                else
                    OUT_THROW("Error reading " << fname << ": " << strerror(errno));
            }
            else {
                process_stream(in);

                if (mopt_firstline) {
                    OUT("Imported " << m_count << " rows of data from " << fname);
                }
                else {
                    OUT("Cached " << m_count << " rows of data from " << fname);
                }
            }
        }
    }
    else // no file arguments -> process stdin
    {
        OUT("Reading data from stdin ...");

        process_stream(std::cin);
    }

    // process cached data lines
    if (!mopt_firstline)
    {
        m_count = m_total_count = 0;
        process_linedata();
    }

    // finish transaction
    g_db->execute("COMMIT");

    OUT("Imported in total " << m_total_count << " rows of data containing " << m_fieldset.count() << " fields each.");

    if (opt_dbconnect)
        g_db_free();

    return EXIT_SUCCESS;
}
Пример #19
0
static bool
read_conf_file(const char *conf_file)
{
	FILE *stream;
	glob_t globbuf;
	size_t i;
	int	res;
	struct stat stb;
	unsigned num_matches = 0;

	globbuf.gl_offs = 0;
	res = glob(conf_file, GLOB_MARK
#if HAVE_DECL_GLOB_BRACE
					| GLOB_BRACE
#endif
						    , NULL, &globbuf);

	if (res) {
		if (res == GLOB_NOMATCH)
			log_message(LOG_INFO, "No config files matched '%s'.", conf_file);
		else
			log_message(LOG_INFO, "Error reading config file(s): glob(\"%s\") returned %d, skipping.", conf_file, res);
		return true;
	}

	for (i = 0; i < globbuf.gl_pathc; i++) {
		if (globbuf.gl_pathv[i][strlen(globbuf.gl_pathv[i])-1] == '/') {
			/* This is a directory - so skip */
			continue;
		}

		log_message(LOG_INFO, "Opening file '%s'.", globbuf.gl_pathv[i]);
		stream = fopen(globbuf.gl_pathv[i], "r");
		if (!stream) {
			log_message(LOG_INFO, "Configuration file '%s' open problem (%s) - skipping"
				       , globbuf.gl_pathv[i], strerror(errno));
			continue;
		}

		/* Make sure what we have opened is a regular file, and not for example a directory or executable */
		if (fstat(fileno(stream), &stb) ||
		    !S_ISREG(stb.st_mode) ||
		    (stb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
			log_message(LOG_INFO, "Configuration file '%s' is not a regular non-executable file - skipping", globbuf.gl_pathv[i]);
			fclose(stream);
			continue;
		}

		num_matches++;

		current_stream = stream;

		int curdir_fd = -1;
		if (strchr(globbuf.gl_pathv[i], '/')) {
			/* If the filename contains a directory element, change to that directory */
			curdir_fd = open(".", O_RDONLY | O_DIRECTORY | O_PATH);

			char *confpath = strdup(globbuf.gl_pathv[i]);
			dirname(confpath);
			if (chdir(confpath) < 0)
				log_message(LOG_INFO, "chdir(%s) error (%s)", confpath, strerror(errno));
			free(confpath);
		}

		process_stream(current_keywords, 0);
		fclose(stream);

		/* If we changed directory, restore the previous directory */
		if (curdir_fd != -1) {
			if ((res = fchdir(curdir_fd)))
				log_message(LOG_INFO, "Failed to restore previous directory after include");
			close(curdir_fd);
			if (res)
				return true;
		}
	}

	globfree(&globbuf);

	if (!num_matches)
		log_message(LOG_INFO, "No config files matched '%s'.", conf_file);

	return false;
}
Пример #20
0
/* Here is perhaps the right place to mention that this code is
 * all in top-down order. Hence, |main| comes first.
 */
int
main(int argc, char *argv[])
{
	int ch;			/* used for |getopt| processing */

	(void)setlocale(LC_CTYPE, "");

	/* 1. Grok parameters. */
	while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) {
		switch (ch) {
		case 'c':
			centerP = 1;
			break;
		case 'd':
			sentence_enders = optarg;
			break;
		case 'l':
			output_tab_width
				= get_positive(optarg, "output tab width must be positive", 1);
			break;
		case 'm':
			grok_mail_headers = 1;
			break;
		case 'n':
			format_troff = 1;
			break;
		case 'p':
			allow_indented_paragraphs = 1;
			break;
		case 's':
			coalesce_spaces_P = 1;
			break;
		case 't':
			tab_width = get_positive(optarg, "tab width must be positive", 1);
			break;
		case 'w':
			goal_length = get_positive(optarg, "width must be positive", 1);
			max_length = goal_length;
			break;
		case '0': case '1': case '2': case '3': case '4': case '5':
		case '6': case '7': case '8': case '9':
			/* XXX  this is not a stylistically approved use of getopt() */
			if (goal_length == 0) {
				char *p;

				p = argv[optind - 1];
				if (p[0] == '-' && p[1] == ch && !p[2])
					goal_length = get_positive(++p, "width must be nonzero", 1);
				else
					goal_length = get_positive(argv[optind]+1,
							"width must be nonzero", 1);
				max_length = goal_length;
			}
			break;
		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	argc -= optind;
	argv += optind;

	/* [ goal [ maximum ] ] */
	if (argc > 0 && goal_length == 0 &&
	    (goal_length = get_positive(*argv,"goal length must be positive", 0)) != 0) {
		--argc;
		++argv;
		if (argc > 0 && (max_length = get_positive(*argv,"max length must be positive", 0)) != 0) {
			--argc;
			++argv;
			if (max_length < goal_length)
				errx(EX_USAGE, "max length must be >= goal length");
		}
	}

	if (goal_length == 0)
		goal_length = 65;
	if (max_length == 0)
		max_length = goal_length+10;
	output_buffer = XMALLOC(max_length+1);	/* really needn't be longer */

	/* 2. Process files. */

	if (argc > 0) {
		while (argc-- > 0)
			process_named_file(*argv++);
	} else {
		process_stream(stdin, "standard input");
	}

	/* We're done. */
	return n_errors ? EX_NOINPUT : 0;

}
Пример #21
0
static int process_stream(struct sdp_stream_cell *s1, struct sdp_stream_cell *s2,
                          str *src, str *dst, unsigned char idx)
{
	int rc = 0, len;
	struct sdp_payload_attr *att = codec_matches[idx].att2;
	struct in_addr addr;

	if (s1->next && s2->next)
		rc = process_stream(s1->next, s2->next, src, dst, idx - 1);
	else if (s1->next || s2->next)
		LM_ERR("found different number of SDP streams - choosing min\n");

	/* check if attribute port must be rewritten */
	if (codec_matches[idx].status == SNGTC_ON) {

		LM_DBG("codec tc status: TC ON\n");

		len = s1->port.s - src->s;
		memcpy(dst->s + dst->len, src->s, len);
		dst->len += len;
		dst->len += sprintf(dst->s + dst->len, "%d",
		                    codec_matches[idx].reply->b.codec_udp_port);
		src->s += len + s1->port.len;
	} else
		LM_DBG("codec tc status: TC OFF\n");

	/* copy everything up to the rtp payload list (0 3 101 ...)  */
	len = s1->p_payload_attr[0]->rtp_payload.s - src->s;
	memcpy(dst->s + dst->len, src->s, len);
	dst->len += len;
	src->s += len;

	if (codec_matches[idx].status == SNGTC_ON) {

		dst->len += sprintf(dst->s + dst->len, "%.*s%s"
		                                       "c=IN IP4 ",
							att->rtp_payload.len, att->rtp_payload.s, CRLF);

		if (card_ip_a.s)
			dst->len += sprintf(dst->s + dst->len, "%.*s%s"
			                        "a=rtpmap:%.*s %.*s/%.*s",
			                        card_ip_a.len, card_ip_a.s, CRLF,
			                        att->rtp_payload.len, att->rtp_payload.s,
			                        att->rtp_enc.len,     att->rtp_enc.s,
			                        att->rtp_clock.len,   att->rtp_clock.s);
		else {
			addr.s_addr = ntohl(codec_matches[idx].reply->b.codec_ip);
			if (!inet_ntop(AF_INET, &addr, dst->s + dst->len, INET_ADDRSTRLEN)) {
				LM_ERR("Failed to convert IP from binary to string\n");
				return SNGTC_ERR;
			}

			while (dst->s[dst->len])
				dst->len++;

			dst->len += sprintf(dst->s + dst->len, "%s"
			                        "a=rtpmap:%.*s %.*s/%.*s", CRLF,
			                        att->rtp_payload.len, att->rtp_payload.s,
			                        att->rtp_enc.len,     att->rtp_enc.s,
			                        att->rtp_clock.len,   att->rtp_clock.s);
		}
	} else
		dst->len += sprintf(dst->s + dst->len, "%.*s%s"
		                    "a=rtpmap:%.*s %.*s/%.*s",
		                    att->rtp_payload.len, att->rtp_payload.s, CRLF,
		                    att->rtp_payload.len, att->rtp_payload.s,
		                    att->rtp_enc.len,     att->rtp_enc.s,
		                    att->rtp_clock.len,   att->rtp_clock.s);

	return rc;
}
Пример #22
0
/**
 * performs the following operations at 200 OK time (early neg <-> late neg):
 *
 * - alters the callee's 200 OK message (adds the final decided codec)
 * - alters the caller's SDP (in memory), so it can be attached @ ACK
 * - opens transcoding sessions on the card if necessary
 *
 * Note: assumes all streams are on corresponding positions in both SDPs
 */
static int process_session(struct sip_msg *msg, struct sngtc_info *info, str *src,
                           str *dst, struct sdp_session_cell *s1,
                           struct sdp_session_cell *s2)
{
	struct sdp_stream_cell *sm1, *sm2;
	struct sngtc_session_list *tc_session;
	struct sngtc_codec_request request;
	struct sngtc_codec_reply *reply = NULL;
	struct codec_pair pair;
	struct lump *lump, *nl;
	struct in_addr addr;
	int rc = 0, ret, tc_on = 0;
	int idx;
	char buf[INET_ADDRSTRLEN];
	str repl;

	if (s1->next && s2->next)
		rc = process_session(msg, info, src, dst, s1->next, s2->next);
	else if (s1->next || s2->next)
		LM_ERR("endpoints have a different number of SDP sessions"
		       " - choosing min number\n");

	if (rc != 0)
		goto out;

	tc_session = info->sessions;
	for (idx = MAX_STREAMS - 1, sm1 = s1->streams, sm2 = s2->streams; sm1 && sm2;
	     sm1 = sm1->next, sm2 = sm2->next, idx--) {

		ret = match_codecs(sm1, sm2, &pair);
		codec_matches[idx] = pair;

		switch (ret) {

		case SNGTC_OFF:

			LM_DBG("NO NEED FOR TRANSCODING\n");

			/* delete codecs from 200 OK; write endpoint A codec */
			/* ip and port stay the same */
			lump = remove_sdp_stream_attrs(msg, sm2);
			if (!lump) {
				LM_ERR("failed to clear sdp codecs\n");
				return SNGTC_SDP_ERR;
			}

			LM_DBG("sdp stream:\n");
			print_sdp_stream(sm2, L_DBG);

			ret = write_sdp_stream_attr(msg, lump, pair.att2, NULL);
			if (ret != 0) {
				LM_ERR("failed to write sdp stream codec\n");
				return ret;
			}

			break;

		case SNGTC_ON:

			tc_on = 1;

			if (is_processed(info))
				goto use_existing_sessions;

			LM_DBG("TRANSCODING ([%d] %.*s:%.*s <--> [%d] %.*s:%.*s)\n",
			       pair.tc1, s1->ip_addr.len, s1->ip_addr.s, sm1->port.len,
				   sm1->port.s, pair.tc2, s2->ip_addr.len, s2->ip_addr.s,
				   sm2->port.len, sm2->port.s);

			memset(&request, 0, sizeof(request));

			request.usr_priv = NULL;

			/* Codec, ms, IP and port for side A */
			request.a.codec_id = pair.tc1;
			request.a.ms = 0;
			sprintf(buf, "%.*s", s1->ip_addr.len, s1->ip_addr.s);
			ret = inet_pton(AF_INET, buf, &addr);
			if (ret != 1) {
				LM_ERR("failed to convert ip %s to binary form (%d)\n",
				       s1->ip_addr.s, ret);
				return SNGTC_ERR;
			}
			request.a.host_ip = htonl(addr.s_addr);
			request.a.host_netmask = (unsigned int)-1;
			if (str2int(&sm1->port, &request.a.host_udp_port) != 0)
				LM_ERR("Failed to parse integer stored in port str '%.*s'\n",
						sm1->port.len, sm1->port.s);

			/* Codec, ms, IP and port for side B */
			request.b.codec_id = pair.tc2;
			request.b.ms = 0;
			sprintf(buf, "%.*s", s2->ip_addr.len, s2->ip_addr.s);
			ret = inet_pton(AF_INET, buf, &addr);
			if (ret != 1) {
				LM_ERR("failed to convert ip %.*s to binary form (%d)\n",
				       s2->ip_addr.len, s2->ip_addr.s, ret);
				return SNGTC_ERR;
			}
			request.b.host_ip = htonl(addr.s_addr);
			request.b.host_netmask = (unsigned int)-1;
			if (str2int(&sm2->port, &request.b.host_udp_port) != 0)
				LM_ERR("Failed to parse integer stored in port str '%.*s'\n",
						sm2->port.len, sm2->port.s);

			LM_DBG("Transcoding request: %d:%d <--> %d:%d\n", request.a.host_ip,
			       request.a.host_udp_port, request.b.host_ip,
			       request.b.host_udp_port);

			reply = create_transcoding_session(&request, info);
			if (!reply) {
				LM_ERR("Failed to create a transcoding session on the card\n");
				return SNGTC_TC_ERR;
			}

use_existing_sessions:

			LM_DBG("NEW TC SESSION!\n");

			if (is_processed(info)) {
				reply = tc_session->reply;
				tc_session = tc_session->next;
			}

			codec_matches[idx].reply = reply;

			/**
			 * delete codecs from 200 OK
			 * write the common codec
			 * replace IP with ip of Sangoma card
			 * replace port with endpoint A newly opened port on card
			 */
			lump = remove_sdp_stream_attrs(msg, sm2);
			if (!lump) {
				LM_ERR("failed to clear sdp codecs\n");
				return SNGTC_SDP_ERR;
			}

			nl = del_lump(msg, s2->ip_addr.s - msg->buf, s2->ip_addr.len, 0);
			if (!nl) {
				LM_ERR("failed to add del lump\n");
				return SNGTC_ERR;
			}

			if (pkg_str_dup(&repl, &card_ip_b) != 0) {
				LM_ERR("failed to dup in pkg mem\n");
				return SNGTC_ERR;
			}

			if (!insert_new_lump_after(nl, repl.s, repl.len, HDR_OTHER_T)) {
				LM_ERR("failed to insert lump with codec result\n");
				return SNGTC_ERR;
			}

			if (replace_sdp_stream_port(msg, sm2,
			                            reply->a.codec_udp_port) != 0) {
				LM_ERR("failed to rewrite sdp stream port\n");
				return SNGTC_ERR;
			}

			if (write_sdp_stream_attr(msg, lump, pair.att1, reply) != 0) {
				LM_ERR("failed to write sdp stream codecs\n");
				return SNGTC_ERR;
			}

			break;

		case SNGTC_UNSUP_CODECS:

			LM_ERR("endpoints have no common codecs and at least one side "
			       "contains only unsupported Sangoma codecs\n");

			LM_ERR("caller:\n");
			print_sdp_stream(sm1, L_ERR);

			LM_ERR("callee:\n");
			print_sdp_stream(sm2, L_ERR);
			return SNGTC_SDP_ERR;

		case SNGTC_BAD_SDP:

			LM_ERR("received bogus sdp with no attributes\n");

			LM_ERR("caller:\n");
			print_sdp_stream(sm1, L_ERR);

			LM_ERR("callee:\n");
			print_sdp_stream(sm2, L_ERR);
			return SNGTC_SDP_ERR;
		}
	}

	if (tc_on) {
		LM_DBG("transcoding: ON\n");

		memcpy(dst->s + dst->len, src->s, s1->ip_addr.s - src->s);
		dst->len += s1->ip_addr.s - src->s;
		dst->len += sprintf(dst->s + dst->len, "%.*s",
		                    card_ip_a.len, card_ip_a.s);
		src->s += s1->ip_addr.s - src->s + s1->ip_addr.len;
	} else
		LM_DBG("transcoding: OFF\n");

	rc |= process_stream(s1->streams, s2->streams, src, dst, MAX_STREAMS - 1);
out:
	return rc;
}
Пример #23
0
/* Here is perhaps the right place to mention that this code is
 * all in top-down order. Hence, |main| comes first.
 */
int
main(int argc, char *argv[]) {
  int ch;			/* used for |getopt| processing */
  wchar_t *tmp;
  size_t len;
  const char *src;

  (void) setlocale(LC_CTYPE, "");

  /* 1. Grok parameters. */

  while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1)
  switch(ch) {
    case 'c':
      centerP = 1;
      format_troff = 1;
      continue;
    case 'd':
      src = optarg;
      len = mbsrtowcs(NULL, &src, 0, NULL);
      if (len == (size_t)-1)
        err(EX_USAGE, "bad sentence-ending character set");
      tmp = XMALLOC((len + 1) * sizeof(wchar_t));
      mbsrtowcs(tmp, &src, len + 1, NULL);
      sentence_enders = tmp;
      continue;
    case 'l':
      output_tab_width
        = get_nonnegative(optarg, "output tab width must be non-negative", 1);
      continue;
    case 'm':
      grok_mail_headers = 1;
      continue;
    case 'n':
      format_troff = 1;
      continue;
    case 'p':
      allow_indented_paragraphs = 1;
      continue;
    case 's':
      coalesce_spaces_P = 1;
      continue;
    case 't':
      tab_width = get_positive(optarg, "tab width must be positive", 1);
      continue;
    case 'w':
      goal_length = get_positive(optarg, "width must be positive", 1);
      max_length = goal_length;
      continue;
    case '0': case '1': case '2': case '3': case '4': case '5':
    case '6': case '7': case '8': case '9':
    /* XXX  this is not a stylistically approved use of getopt() */
      if (goal_length==0) {
        char *p;
        p = argv[optind - 1];
        if (p[0] == '-' && p[1] == ch && !p[2])
             goal_length = get_positive(++p, "width must be nonzero", 1);
        else
             goal_length = get_positive(argv[optind]+1,
                 "width must be nonzero", 1);
        max_length = goal_length;
      }
      continue;
    case 'h': default:
      fprintf(stderr,
"usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
"             [-w width | -width | goal [maximum]] [file ...]\n"
"Options: -c     center each line instead of formatting\n"
"         -d <chars> double-space after <chars> at line end\n"
"         -l <n> turn each <n> spaces at start of line into a tab\n"
"         -m     try to make sure mail header lines stay separate\n"
"         -n     format lines beginning with a dot\n"
"         -p     allow indented paragraphs\n"
"         -s     coalesce whitespace inside lines\n"
"         -t <n> have tabs every <n> columns\n"
"         -w <n> set maximum width to <n>\n"
"         goal   set target width to goal\n");
      exit(ch=='h' ? 0 : EX_USAGE);
  }
  argc -= optind; argv += optind;

  /* [ goal [ maximum ] ] */

  if (argc>0 && goal_length==0
      && (goal_length=get_positive(*argv,"goal length must be positive", 0))
         != 0) {
    --argc; ++argv;
    if (argc>0
        && (max_length=get_positive(*argv,"max length must be positive", 0))
           != 0) {
      --argc; ++argv;
      if (max_length<goal_length)
        errx(EX_USAGE, "max length must be >= goal length");
    }
  }
  if (goal_length==0) goal_length = 65;
  if (max_length==0) max_length = goal_length+10;
  if (max_length >= SIZE_T_MAX / sizeof (wchar_t)) errx(EX_USAGE, "max length too large");
  /* really needn't be longer */
  output_buffer = XMALLOC((max_length+1) * sizeof(wchar_t));

  /* 2. Process files. */

  if (argc>0) {
    while (argc-->0) process_named_file(*argv++);
  }
  else {
    process_stream(stdin, "standard input");
  }

  /* We're done. */

  return n_errors ? EX_NOINPUT : 0;

}
Пример #24
0
static int
process_stream(struct config *conf, FILE *stream, vector keywords, char *file)
{
	int i;
	int r = 0, t;
	struct keyword *keyword;
	char *str;
	char *buf;
	vector strvec;
	vector uniques;

	uniques = vector_alloc();
	if (!uniques)
		return 1;

	buf = MALLOC(MAXBUF);

	if (!buf) {
		vector_free(uniques);
		return 1;
	}

	while (read_line(stream, buf, MAXBUF)) {
		line_nr++;
		strvec = alloc_strvec(buf);
		if (!strvec)
			continue;

		if (validate_config_strvec(strvec, file) != 0) {
			free_strvec(strvec);
			continue;
		}

		str = VECTOR_SLOT(strvec, 0);

		if (!strcmp(str, EOB)) {
			if (kw_level > 0) {
				free_strvec(strvec);
				break;
			}
			condlog(0, "unmatched '%s' at line %d of %s",
				EOB, line_nr, file);
		}

		for (i = 0; i < VECTOR_SIZE(keywords); i++) {
			keyword = VECTOR_SLOT(keywords, i);

			if (!strcmp(keyword->string, str)) {
				if (keyword->unique &&
				    warn_on_duplicates(uniques, str, file)) {
						r = 1;
						free_strvec(strvec);
						goto out;
				}
				if (keyword->handler) {
				    t = (*keyword->handler) (conf, strvec);
					r += t;
					if (t)
						condlog(1, "multipath.conf +%d, parsing failed: %s",
							line_nr, buf);
				}

				if (keyword->sub) {
					kw_level++;
					r += process_stream(conf, stream,
							    keyword->sub, file);
					kw_level--;
				}
				break;
			}
		}
		if (i >= VECTOR_SIZE(keywords))
			condlog(1, "%s line %d, invalid keyword: %s",
				file, line_nr, str);

		free_strvec(strvec);
	}

out:
	FREE(buf);
	free_uniques(uniques);
	return r;
}
Пример #25
0
int main(int argc, char * argv[])
{
   try{
      po::options_description opts("Options");
      opts.add_options()
         ("help,h", "produce help message") 
         //("after-context,A", po::value<int>(&after_context)->default_value(0), "Print arg  lines  of  trailing  context  after  matching  lines. Places  a  line  containing  --  between  contiguous  groups  of matches.")
         //("before-context,B", po::value<int>(&before_context)->default_value(0), "Print  arg  lines  of  leading  context  before  matching lines. Places  a  line  containing  --  between  contiguous  groups  of matches.")
         //("context,C", po::value<int>(), "Print  arg lines of output context.  Places a line containing -- between contiguous groups of matches.")
         ("byte-offset,b", "Print the byte offset within the input file before each line  of output.")
         ("count,c", "Suppress normal output; instead print a count of matching  lines for  each  input  file.  With the -v, --invert-match option (see below), count non-matching lines.")
         ("extended-regexp,E", "Interpret PATTERN as an POSIX-extended regular expression.")
         ("perl-regexp,P", "Interpret PATTERN as a Perl regular expression.")
         //("regexp,e", po::value<std::string>(&pattern), "Use PATTERN as the pattern; useful to protect patterns beginning with -.")
         ("basic-regexp,G", "Interpret arg as a POSIX-basic regular expression (see below).  This is the default.")
         ("ignore-case,i", "Ignore case distinctions in  both  the  PATTERN  and  the  input files.")
         ("files-without-match,L", "Suppress  normal  output;  instead  print the name of each input file from which no output would normally have been printed.  The scanning will stop on the first match.")
         ("files-with-matches,l", "Suppress  normal  output;  instead  print the name of each input file from which output would normally have  been  printed.   The scanning will stop on the first match.")
         ("line-number,n", "Prefix each line of output with the line number within its input file.")
         ;
      // Hidden options, will be allowed both on command line and
      // in config file, but will not be shown to the user.
      po::options_description hidden("Hidden options");
      hidden.add_options()
         ("input-file", po::value< std::vector<std::string> >(), "input file")
         ("input-pattern", po::value< std::string >(), "input file")
         ;

      po::options_description cmdline_options;
      cmdline_options.add(opts).add(hidden);

      po::positional_options_description p;
      p.add("input-pattern", 1);
      p.add("input-file", -1);

      po::variables_map vm;
      po::store(po::command_line_parser(argc, argv).options(cmdline_options)/*.options(hidden)*/.positional(p).run(), vm);
      po::notify(vm);

      if (vm.count("help")) 
      {
         std::cout << opts << "\n";
         return 0;
      }
      if (vm.count("context")) 
      {
         after_context = vm["context"].as< int >();
         before_context = after_context;
      }
      if(vm.count("extended-regexp"))
      {
         flags = boost::regex_constants::extended;
      }
      if(vm.count("basic-regexp"))
      {
         flags = boost::regex_constants::basic;
      }
      if(vm.count("perl-regexp"))
      {
         flags = boost::regex_constants::perl;
      }
      if(vm.count("ignore-case"))
      {
         flags |= boost::regex_constants::icase;
      }
      if(vm.count("byte-offset"))
      {
         print_byte_offset = true;
      }
      if(vm.count("count"))
      {
         count_only = true;
      }
      if(vm.count("files-without-match"))
      {
         print_non_matching_files = true;
      }
      if(vm.count("files-with-matches"))
      {
         files_only = true;
      }
      if(vm.count("line-number"))
      {
         print_line_numbers = true;
      }
      if(vm.count("input-pattern"))
      {
         pattern = vm["input-pattern"].as< std::string >();
         re.assign(pattern, flags);
      }
      else
      {
         std::cerr << "No pattern specified" << std::endl;
         return 1;
      }
      if (vm.count("input-file"))
      {
         const std::vector<std::string>& files = vm["input-file"].as< std::vector<std::string> >();
         file_count = files.size();
         for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i)
         {
            process_file(*i);
         }
      }
      else
      {
         // no input files, scan stdin instead:
         process_stream(std::cin);
      }

   }
   catch(const std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }

   return 0;
}