Ejemplo n.º 1
0
/**
 * \brief Input plugin "destructor".
 *
 * \param[in,out] config  plugin_info structure
 * \return 0 on success and config is changed to NULL, nonzero else.
 */
int input_close(void **config)
{
	int ret;
	struct plugin_conf *conf = (struct plugin_conf*) *config;
	struct input_info_list *info_list;

	/* close socket */
	int sock = ((struct plugin_conf*) *config)->socket;
	if ((ret = close(sock)) == -1) {
		MSG_ERROR(msg_module, "Cannot close socket: %s", strerror(errno));
	}

	/* free input_info list */
	while (conf->info_list) {
		info_list = conf->info_list->next;
		free(conf->info_list);
		conf->info_list = info_list;
	}

	/* free configuration strings */
	if (conf->info.template_life_time != NULL) {
		free(conf->info.template_life_time);
	}
	if (conf->info.template_life_packet != NULL) {
		free(conf->info.template_life_packet);
	}
	if (conf->info.options_template_life_time != NULL) {
		free(conf->info.options_template_life_time);
	}
	if (conf->info.options_template_life_packet != NULL) {
		free(conf->info.options_template_life_packet);
	}

	/* free allocated structures */
	free(*config);
	convert_close();

	MSG_INFO(msg_module, "All allocated resources have been freed");

	return 0;
}
Ejemplo n.º 2
0
/**
 * @fn int search(const char *pattern, const char *root, const char *cwd, const char *dbpath, int db)
 *
 * search: search specified function 
 *
 *	@param[in]	pattern		search pattern
 *	@param[in]	root		root of source tree
 *	@param[in]	cwd		current directory
 *	@param[in]	dbpath		database directory
 *	@param[in]	db		#GTAGS,#GRTAGS,#GSYMS
 *	@return			count of output lines
 */
int
search(const char *pattern, const char *root, const char *cwd, const char *dbpath, int db)
{
	CONVERT *cv;
	int count = 0;
	GTOP *gtop;
	GTP *gtp;
	int flags = 0;

	start_output();
	/*
	 * open tag file.
	 */
	gtop = gtags_open(dbpath, root, db, GTAGS_READ, debug ? GTAGS_DEBUG : 0);
	cv = convert_open(type, format, root, cwd, dbpath, stdout, db);
	/*
	 * search through tag file.
	 */
	if (nofilter & SORT_FILTER)
		flags |= GTOP_NOSORT;
	if (Gflag)
		flags |= GTOP_BASICREGEX;
	if (format == FORMAT_PATH)
		flags |= GTOP_PATH;
	if (iflag)
		flags |= GTOP_IGNORECASE;
	for (gtp = gtags_first(gtop, pattern, flags); gtp; gtp = gtags_next(gtop)) {
		if (Sflag && !locatestring(gtp->path, localprefix, MATCH_AT_FIRST))
			continue;
		count += output_with_formatting(cv, gtp, gtop->format);
	}
	convert_close(cv);
	if (debug)
		gtags_show_statistics(gtop);
	gtags_close(gtop);
	end_output();
	return count;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        printf("Usage: #simple_demo ip port\n");
        return  -1;
    }

	struct cap_handle *caphandle = NULL;
	struct cvt_handle *cvthandle = NULL;
	struct enc_handle *enchandle = NULL;
	struct pac_handle *pachandle = NULL;
    struct net_handle *nethandle = NULL;
	struct cap_param capp;
	struct cvt_param cvtp;
	struct enc_param encp;
	struct pac_param pacp;
    struct net_param netp;

	// set paraments
	U32 vfmt = V4L2_PIX_FMT_YUYV;
	U32 ofmt = V4L2_PIX_FMT_YUV420;

	capp.dev_name = "/dev/video0";
	capp.width = WIDTH;
	capp.height = HEIGHT;
	capp.pixfmt = vfmt;
	capp.rate = FRAMERATE;

	cvtp.inwidth = WIDTH;
	cvtp.inheight = HEIGHT;
	cvtp.inpixfmt = vfmt;
	cvtp.outwidth = WIDTH;
	cvtp.outheight = HEIGHT;
	cvtp.outpixfmt = ofmt;

	encp.src_picwidth = WIDTH;
	encp.src_picheight = HEIGHT;
	encp.enc_picwidth = WIDTH;
	encp.enc_picheight = HEIGHT;
	encp.chroma_interleave = 0;
	encp.fps = FRAMERATE;
	encp.gop = 30;
	encp.bitrate = 800;

	pacp.max_pkt_len = 1400;
	pacp.ssrc = 10;

    netp.type = UDP;
    netp.serip = argv[1];
    netp.serport = atoi(argv[2]);

	caphandle = capture_open(capp);
	if (!caphandle)
	{
		printf("--- Open capture failed\n");
		return -1;
	}

	cvthandle = convert_open(cvtp);
	if (!cvthandle)
	{
		printf("--- Open convert failed\n");
		return -1;
	}

	enchandle = encode_open(encp);
	if (!enchandle)
	{
		printf("--- Open encode failed\n");
		return -1;
	}

	pachandle = pack_open(pacp);
	if (!pachandle)
	{
		printf("--- Open pack failed\n");
		return -1;
	}

    nethandle = net_open(netp);
    if (!nethandle)
    {
        printf("--- Open network failed\n");
        return -1;
    }

	// start stream loop
	int ret;
	void *cap_buf, *cvt_buf, *hd_buf, *enc_buf, *pac_buf;
	int cap_len, cvt_len, hd_len, enc_len, pac_len;
	enum pic_t ptype;
	unsigned long framecount = 0;

	capture_start(caphandle);		// !!! need to start capture stream!

	while (1)
	{
		ret = capture_get_data(caphandle, &cap_buf, &cap_len);
		if (ret != 0)
		{
			if (ret < 0)		// error
			{
				printf("--- capture_get_data failed\n");
				break;
			}
			else	// again
			{
				usleep(10000);
				continue;
			}
		}
		if (cap_len <= 0)
		{
			printf("!!! No capture data\n");
			continue;
		}
		// else

		ret = convert_do(cvthandle, cap_buf, cap_len, &cvt_buf, &cvt_len);
		if (ret < 0)
		{
			printf("--- convert_do failed\n");
			break;
		}
		if (cvt_len <= 0)
		{
			printf("!!! No convert data\n");
			continue;
		}
		// else

		// fetch h264 headers first!
		while ((ret = encode_get_headers(enchandle, &hd_buf, &hd_len, &ptype))
				== 1)
		{
            //fwrite(hd_buf, 1, hd_len, dumpfile);
			pack_put(pachandle, hd_buf, hd_len);
			while (pack_get(pachandle, &pac_buf, &pac_len) == 1)
			{
                ret = net_send(nethandle, pac_buf, pac_len);
				if (ret != pac_len)
				{
					printf("send pack data failed, size: %d, err: %s\n", pac_len,
							strerror(errno));
				}
			}
		}

		ret = encode_do(enchandle, cvt_buf, cvt_len, &enc_buf, &enc_len,
				&ptype);
		if (ret < 0)
		{
			printf("--- encode_do failed\n");
			break;
		}
		if (enc_len <= 0)
		{
			printf("!!! No encode data\n");
			continue;
		}
		// else

        //fwrite(enc_buf, 1, enc_len, dumpfile);
		// RTP pack and send
		pack_put(pachandle, enc_buf, enc_len);
		while (pack_get(pachandle, &pac_buf, &pac_len) == 1)
		{
            ret = net_send(nethandle, pac_buf, pac_len);
			if (ret != pac_len)
			{
				printf("send pack failed, size: %d, err: %s\n", pac_len,
						strerror(errno));
			}
		}

		framecount++;
	}
	capture_stop(caphandle);

    net_close(nethandle);
	pack_close(pachandle);
	encode_close(enchandle);
	convert_close(cvthandle);
	capture_close(caphandle);

	return 0;
}
Ejemplo n.º 4
0
/*
 * grep: grep pattern
 *
 *	i)	pattern	POSIX regular expression
 */
void
grep(const char *pattern, char *const *argv, const char *dbpath)
{
	FILE *fp;
	CONVERT *cv;
	GFIND *gp = NULL;
	STRBUF *ib = strbuf_open(MAXBUFLEN);
	const char *path;
	char encoded_pattern[IDENTLEN];
	const char *buffer;
	int linenum, count;
	int flags = 0;
	int target = GPATH_SOURCE;
	regex_t	preg;
	int user_specified = 1;

	/*
	 * convert spaces into %FF format.
	 */
	encode(encoded_pattern, sizeof(encoded_pattern), pattern);

	if (oflag)
		target = GPATH_BOTH;
	if (Oflag)
		target = GPATH_OTHER;
	if (!Gflag)
		flags |= REG_EXTENDED;
	if (iflag)
		flags |= REG_ICASE;
	if (regcomp(&preg, pattern, flags) != 0)
		die("invalid regular expression.");
	cv = convert_open(type, format, root, cwd, dbpath, stdout);
	count = 0;

	if (*argv && file_list)
		args_open_both(argv, file_list);
	else if (*argv)
		args_open(argv);
	else if (file_list)
		args_open_filelist(file_list);
	else {
		args_open_gfind(gp = gfind_open(dbpath, localprefix, target));
		user_specified = 0;
	}
	while ((path = args_read()) != NULL) {
		if (user_specified) {
			static char buf[MAXPATHLEN];

			if (normalize(path, get_root_with_slash(), cwd, buf, sizeof(buf)) == NULL)
				if (!qflag)
					fprintf(stderr, "'%s' is out of source tree.\n", path);
			if (!test("f", buf))
				die("'%s' not found. Please remake tag files by invoking gtags(1).", path);
			path = buf;
		}
		if (!(fp = fopen(path, "r")))
			die("cannot open file '%s'.", path);
		linenum = 0;
		while ((buffer = strbuf_fgets(ib, fp, STRBUF_NOCRLF)) != NULL) {
			int result = regexec(&preg, buffer, 0, 0, 0);

			linenum++;
			if ((!Vflag && result == 0) || (Vflag && result != 0)) {
				count++;
				if (format == FORMAT_PATH) {
					convert_put_path(cv, path);
					break;
				} else {
					convert_put_using(cv, encoded_pattern, path, linenum, buffer,
						(user_specified) ? NULL : gp->dbop->lastdat);
				}
			}
		}
		fclose(fp);
	}
	args_close();
	convert_close(cv);
	strbuf_close(ib);
	regfree(&preg);
	if (vflag) {
		print_count(count);
		fprintf(stderr, " (no index used).\n");
	}
}
Ejemplo n.º 5
0
/*
 * idutils:  lid(idutils) pattern
 *
 *	i)	pattern	POSIX regular expression
 *	i)	dbpath	GTAGS directory
 */
void
idutils(const char *pattern, const char *dbpath)
{
	FILE *ip;
	CONVERT *cv;
	STRBUF *ib = strbuf_open(0);
	char encoded_pattern[IDENTLEN];
	char path[MAXPATHLEN];
	const char *lid;
	int linenum, count;
	char *p, *q, *grep;

	lid = usable("lid");
	if (!lid)
		die("lid(idutils) not found.");
	/*
	 * convert spaces into %FF format.
	 */
	encode(encoded_pattern, sizeof(encoded_pattern), pattern);
	/*
	 * make lid command line.
	 * Invoke lid with the --result=grep option to generate grep format.
	 */
	strbuf_puts(ib, lid);
	strbuf_sprintf(ib, " --file='%s/ID'", dbpath);
	strbuf_puts(ib, " --separator=newline");
	if (format == FORMAT_PATH)
		strbuf_puts(ib, " --result=filenames --key=none");
	else
		strbuf_puts(ib, " --result=grep");
	if (iflag)
		strbuf_puts(ib, " --ignore-case");
	strbuf_putc(ib, ' ');
	strbuf_puts(ib, quote_string(pattern));
	if (debug)
		fprintf(stderr, "idutils: %s\n", strbuf_value(ib));
	if (!(ip = popen(strbuf_value(ib), "r")))
		die("cannot execute '%s'.", strbuf_value(ib));
	cv = convert_open(type, format, root, cwd, dbpath, stdout);
	count = 0;
	strcpy(path, "./");
	while ((grep = strbuf_fgets(ib, ip, STRBUF_NOCRLF)) != NULL) {
		q = path + 2;
		/* extract path name */
		if (*grep == '/')
			die("The path in the output of lid is assumed absolute. '%s'", grep);
		p = grep;
		while (*p && *p != ':')
			*q++ = *p++;
		*q = '\0'; 
		if ((xflag || tflag) && !*p)
			die("invalid lid(idutils) output format(1). '%s'", grep);
		p++;
		if (lflag) {
			if (!locatestring(path, localprefix, MATCH_AT_FIRST))
				continue;
		}
		count++;
		switch (format) {
		case FORMAT_PATH:
			convert_put_path(cv, path);
			break;
		default:
			/* extract line number */
			while (*p && isspace(*p))
				p++;
			linenum = 0;
			for (linenum = 0; *p && isdigit(*p); linenum = linenum * 10 + (*p++ - '0'))
				;
			if (*p != ':')
				die("invalid lid(idutils) output format(2). '%s'", grep);
			if (linenum <= 0)
				die("invalid lid(idutils) output format(3). '%s'", grep);
			p++;
			/*
			 * print out.
			 */
			convert_put_using(cv, encoded_pattern, path, linenum, p, NULL);
			break;
		}
	}
	if (pclose(ip) < 0)
		die("terminated abnormally.");
	convert_close(cv);
	strbuf_close(ib);
	if (vflag) {
		print_count(count);
		fprintf(stderr, " (using idutils index in '%s').\n", dbpath);
	}
}
Ejemplo n.º 6
0
int
search(const char *pattern, const char *root, const char *cwd, const char *dbpath, int db)
{
	CONVERT *cv;
	int count = 0;
	GTOP *gtop;
	GTP *gtp;
	int flags = 0;
	STRBUF *sb = NULL, *ib = NULL;
	char curpath[MAXPATHLEN], curtag[IDENTLEN];
	FILE *fp = NULL;
	const char *src = "";
	int lineno, last_lineno;

	lineno = last_lineno = 0;
	curpath[0] = curtag[0] = '\0';
	/*
	 * open tag file.
	 */
	gtop = gtags_open(dbpath, root, db, GTAGS_READ, 0);
	cv = convert_open(type, format, root, cwd, dbpath, stdout);
	/*
	 * search through tag file.
	 */
	if (nofilter & SORT_FILTER)
		flags |= GTOP_NOSORT;
	if (iflag) {
		if (!isregex(pattern)) {
			sb = strbuf_open(0);
			strbuf_putc(sb, '^');
			strbuf_puts(sb, pattern);
			strbuf_putc(sb, '$');
			pattern = strbuf_value(sb);
		}
		flags |= GTOP_IGNORECASE;
	}
	if (Gflag)
		flags |= GTOP_BASICREGEX;
	if (format == FORMAT_PATH)
		flags |= GTOP_PATH;
	if (gtop->format & GTAGS_COMPACT)
		ib = strbuf_open(0);
	for (gtp = gtags_first(gtop, pattern, flags); gtp; gtp = gtags_next(gtop)) {
		if (lflag && !locatestring(gtp->path, localprefix, MATCH_AT_FIRST))
			continue;
		if (format == FORMAT_PATH) {
			convert_put_path(cv, gtp->path);
			count++;
		} else if (gtop->format & GTAGS_COMPACT) {
			/*
			 * Compact format:
			 *                    a          b
			 * tagline = <file id> <tag name> <line no>,...
			 */
			char *p = (char *)gtp->tagline;
			const char *fid, *tagname;
			int n = 0;

			fid = p;
			while (*p != ' ')
				p++;
			*p++ = '\0';			/* a */
			tagname = p;
			while (*p != ' ')
				p++;
			*p++ = '\0';			/* b */
			/*
			 * Reopen or rewind source file.
			 */
			if (!nosource) {
				if (strcmp(gtp->path, curpath) != 0) {
					if (curpath[0] != '\0' && fp != NULL)
						fclose(fp);
					strlimcpy(curtag, tagname, sizeof(curtag));
					strlimcpy(curpath, gtp->path, sizeof(curpath));
					/*
					 * Use absolute path name to support GTAGSROOT
					 * environment variable.
					 */
					fp = fopen(makepath(root, curpath, NULL), "r");
					if (fp == NULL)
						warning("source file '%s' is not available.", curpath);
					last_lineno = lineno = 0;
				} else if (strcmp(gtp->tag, curtag) != 0) {
					strlimcpy(curtag, gtp->tag, sizeof(curtag));
					if (atoi(p) < last_lineno && fp != NULL) {
						rewind(fp);
						lineno = 0;
					}
					last_lineno = 0;
				}
			}
			/*
			 * Unfold compact format.
			 */
			if (!isdigit(*p))
				die("illegal compact format.");
			if (gtop->format & GTAGS_COMPLINE) {
				/*
				 *
				 * If GTAGS_COMPLINE flag is set, each line number is expressed as
				 * the difference from the previous line number except for the head.
				 * Please see flush_pool() in libutil/gtagsop.c for the details.
				 */
				int last = 0, cont = 0;

				while (*p || cont > 0) {
					if (cont > 0) {
						n = last + 1;
						if (n > cont) {
							cont = 0;
							continue;
						}
					} else if (isdigit(*p)) {
						GET_NEXT_NUMBER(p);
					}  else if (*p == '-') {
						GET_NEXT_NUMBER(p);
						cont = n + last;
						n = last + 1;
					} else if (*p == ',') {
						GET_NEXT_NUMBER(p);
						n += last;
					}
					if (last_lineno != n && fp) {
						while (lineno < n) {
							if (!(src = strbuf_fgets(ib, fp, STRBUF_NOCRLF))) {
								src = "";
								fclose(fp);
								fp = NULL;
								break;
							}
							lineno++;
						}
					}
					if (gtop->format & GTAGS_COMPNAME)
						tagname = (char *)uncompress(tagname, gtp->tag);
					convert_put_using(cv, tagname, gtp->path, n, src, fid);
					count++;
					last_lineno = last = n;
				}
			} else {
				/*
				 * In fact, when GTAGS_COMPACT is set, GTAGS_COMPLINE is allways set.
				 * Therefore, the following code are not actually used.
				 * However, it is left for some test.
				 */
				while (*p) {
					for (n = 0; isdigit(*p); p++)
						n = n * 10 + *p - '0';
					if (*p == ',')
						p++;
					if (last_lineno == n)
						continue;
					if (last_lineno != n && fp) {
						while (lineno < n) {
							if (!(src = strbuf_fgets(ib, fp, STRBUF_NOCRLF))) {
								src = "";
								fclose(fp);
								fp = NULL;
								break;
							}
							lineno++;
						}
					}
					if (gtop->format & GTAGS_COMPNAME)
						tagname = (char *)uncompress(tagname, gtp->tag);
					convert_put_using(cv, tagname, gtp->path, n, src, fid);
					count++;
					last_lineno = n;
				}
			}
		} else {
			/*
			 * Standard format:
			 *                    a          b         c
			 * tagline = <file id> <tag name> <line no> <line image>
			 */
			char *p = (char *)gtp->tagline;
			char namebuf[IDENTLEN];
			const char *fid, *tagname, *image;

			fid = p;
			while (*p != ' ')
				p++;
			*p++ = '\0';			/* a */
			tagname = p;
			while (*p != ' ')
				p++;
			*p++ = '\0';			/* b */
			if (gtop->format & GTAGS_COMPNAME) {
				strlimcpy(namebuf, (char *)uncompress(tagname, gtp->tag), sizeof(namebuf));
				tagname = namebuf;
			}
			if (nosource) {
				image = " ";
			} else {
				while (*p != ' ')
					p++;
				image = p + 1;		/* c + 1 */
				if (gtop->format & GTAGS_COMPRESS)
					image = (char *)uncompress(image, gtp->tag);
			}
			convert_put_using(cv, tagname, gtp->path, gtp->lineno, image, fid);
			count++;
		}
	}
	convert_close(cv);
	if (sb)
		strbuf_close(sb);
	if (ib)
		strbuf_close(ib);
	if (fp)
		fclose(fp);
	gtags_close(gtop);
	return count;
}
Ejemplo n.º 7
0
void
parsefile(char *const *argv, const char *cwd, const char *root, const char *dbpath, int db)
{
	int count = 0;
	int file_count = 0;
	STRBUF *sb = strbuf_open(0);
	char *langmap;
	const char *plugin_parser, *av;
	char path[MAXPATHLEN];
	struct parsefile_data data;

	if (db == GRTAGS + GSYMS)
		data.target = TARGET_REF|TARGET_SYM;
	else
		data.target = 1 << db;
	data.extractmethod = getconfb("extractmethod");
	if (getconfs("langmap", sb))
		langmap = check_strdup(strbuf_value(sb));
	else
		langmap = NULL;
	strbuf_reset(sb);
	if (getconfs("gtags_parser", sb))
		plugin_parser = strbuf_value(sb);
	else
		plugin_parser = NULL;
	data.cv = convert_open(type, format, root, cwd, dbpath, stdout);
	if (gpath_open(dbpath, 0) < 0)
		die("GPATH not found.");
	if (data.target == TARGET_REF || data.target == TARGET_SYM) {
		data.dbop = dbop_open(makepath(dbpath, dbname(GTAGS), NULL), 0, 0, 0);
		if (data.dbop == NULL)
			die("%s not found.", dbname(GTAGS));
	} else {
		data.dbop = NULL;
	}
	data.fid = NULL;
	parser_init(langmap, plugin_parser);
	if (langmap != NULL)
		free(langmap);

	if (*argv && file_list)
		args_open_both(argv, file_list);
	else if (*argv)
		args_open(argv);
	else if (file_list)
		args_open_filelist(file_list);
	else
		args_open_nop();
	while ((av = args_read()) != NULL) {
		/*
		 * convert the path into relative to the root directory of source tree.
		 */
		if (normalize(av, get_root_with_slash(), cwd, path, sizeof(path)) == NULL)
			if (!qflag)
				fprintf(stderr, "'%s' is out of source tree.\n", path + 2);
		/*
		 * Memorize the file id of the path. This is used in put_syms().
		 */
		{
			static char s_fid[MAXFIDLEN];
			const char *p = gpath_path2fid(path, NULL);

			if (!p) {
				if (!qflag)
					fprintf(stderr, "'%s' not found in GPATH.\n", path + 2);
				continue;
			}
			strlimcpy(s_fid, p, sizeof(s_fid));
			data.fid = s_fid;
		}
		if (!test("f", makepath(root, path, NULL))) {
			if (test("d", NULL)) {
				if (!qflag)
					fprintf(stderr, "'%s' is a directory.\n", av);
			} else {
				if (!qflag)
					fprintf(stderr, "'%s' not found.\n", av);
			}
			continue;
		}
		if (lflag && !locatestring(path, localprefix, MATCH_AT_FIRST))
			continue;
		data.count = 0;
		parse_file(path, 0, put_syms, &data);
		count += data.count;
		file_count++;
	}
	args_close();
	parser_exit();
	/*
	 * Settlement
	 */
	if (data.dbop != NULL)
		dbop_close(data.dbop);
	gpath_close();
	convert_close(data.cv);
	strbuf_close(sb);
	if (vflag) {
		print_count(count);
		fprintf(stderr, " (no index used).\n");
	}
}
Ejemplo n.º 8
0
/*
 * pathlist: print candidate path list.
 *
 *	i)	dbpath
 */
void
pathlist(const char *pattern, const char *dbpath)
{
	GFIND *gp;
	CONVERT *cv;
	const char *path, *p;
	regex_t preg;
	int count;
	int target = GPATH_SOURCE;

	if (oflag)
		target = GPATH_BOTH;
	if (Oflag)
		target = GPATH_OTHER;
	if (pattern) {
		int flags = 0;
		char edit[IDENTLEN];

		if (!Gflag)
			flags |= REG_EXTENDED;
		if (iflag || getconfb("icase_path"))
			flags |= REG_ICASE;
#ifdef _WIN32
		flags |= REG_ICASE;
#endif /* _WIN32 */
		/*
		 * We assume '^aaa' as '^/aaa'.
		 */
		if (*pattern == '^' && *(pattern + 1) != '/') {
			snprintf(edit, sizeof(edit), "^/%s", pattern + 1);
			pattern = edit;
		}
		if (regcomp(&preg, pattern, flags) != 0)
			die("invalid regular expression.");
	}
	if (!localprefix)
		localprefix = "./";
	cv = convert_open(type, format, root, cwd, dbpath, stdout);
	count = 0;

	gp = gfind_open(dbpath, localprefix, target);
	while ((path = gfind_read(gp)) != NULL) {
		/*
		 * skip localprefix because end-user doesn't see it.
		 */
		p = path + strlen(localprefix) - 1;
		if (pattern) {
			int result = regexec(&preg, p, 0, 0, 0);

			if ((!Vflag && result != 0) || (Vflag && result == 0))
				continue;
		} else if (Vflag)
			continue;
		if (format == FORMAT_PATH)
			convert_put_path(cv, path);
		else
			convert_put_using(cv, "path", path, 1, " ", gp->dbop->lastdat);
		count++;
	}
	gfind_close(gp);
	convert_close(cv);
	if (pattern)
		regfree(&preg);
	if (vflag) {
		switch (count) {
		case 0:
			fprintf(stderr, "file not found");
			break;
		case 1:
			fprintf(stderr, "1 file located");
			break;
		default:
			fprintf(stderr, "%d files located", count);
			break;
		}
		fprintf(stderr, " (using '%s').\n", makepath(dbpath, dbname(GPATH), NULL));
	}
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
    char **url = NULL;
    int n_url = 0, cur_url = 0;
    int check_interval = 15 * 60;
    mrss_t **data_prev = NULL;
    mrss_t **data_cur = NULL;
    int data_size;
    char *proxy = NULL, *proxy_auth = NULL;
    int sw;
    int verbose = 0;
    int notify_friendly = 0;
    char show_timestamp = 0, show_link = 0, show_description = 0, show_pubdate = 0, show_author = 0, show_comments = 0;
    char strip_html = 0, no_error_exit = 0;
    char one_shot = 0;
    char no_heading = 0;
    int bytes_limit = 0;
    time_t last_changed = (time_t)0;
    char continue_on_error = 0/*, dummy*/;
    int show_n = -1;
    /*long int max_age = -1;*/
    char *heading = NULL;
    mrss_options_t mot;

    convert_context_t conv_context;
    convert_context_t* cc = &conv_context;
    char *conv_title = 0;
    char *rss_title = 0;
    char *conv_rss_title = 0;
    char *conv_author = 0;
    char *conv_description = 0;
    char *conv_comments = 0;

    tzset();
    setlocale(LC_ALL, "");

    memset(&mot, 0x00, sizeof(mot));

    while((sw = getopt(argc, argv, "Z:1b:PHztldpacmu:Ni:n:x:y:vVh")) != -1)
    {
        switch(sw)
        {
            case 'Z':
                heading = optarg;
                break;

            case 'N':
                no_heading = 1;
                break;

            case 'm':
                notify_friendly = 1;
                break;

            case '1':
                one_shot = 1;
                break;

            case 'b':
                bytes_limit = atoi(optarg);
                if (bytes_limit <= 0)
                {
                    fprintf(stderr, "-b requires a number > 0\n");
                    return 1;
                }
                break;

            case 'P':
                no_error_exit = 1;
                break;

            case 'H':
                strip_html = 1;
                break;

            case 'n':
                show_n = atoi(optarg);
                if (show_n < 0)
                {
                    fprintf(stderr, "-n requires an positive value\n");
                    return 1;
                }
                else if (show_n > 50)
                    fprintf(stderr, "Initially showing more then 50 items, must be one hell of an rss feed!\n");
                break;

#if 0
            case 'o':
                dummy = optarg[strlen(optarg) - 1];
                max_age = atoi(optarg);
                if (max_age < 0)
                {
                    printf("-o requires an positive value\n");
                    return 1;
                }
                if (dummy == 's')
                    max_age *= 1;
                else if (dummy == 'M')
                    max_age *= 60;
                else if (dummy == 'h')
                    max_age *= 3600;
                else if (dummy == 'd')
                    max_age *= 86400;
                else if (dummy == 'm')
                    max_age *= 86400 * 31;
                else if (dummy == 'y')
                    max_age *= 86400 * 365.25;
                else if (isalpha(dummy))
                {
                    printf("'%c' is a not recognized multiplier\n", dummy);
                    return 1;
                }
                break;
#endif

            case 'z':
                continue_on_error = 1;
                break;

            case 't':
                show_timestamp = 1;
                break;

            case 'l':
                show_link = 1;
                break;

            case 'd':
                show_description = 1;
                break;

            case 'p':
                show_pubdate = 1;
                break;

            case 'a':
                show_author = 1;
                break;

            case 'c':
                show_comments = 1;
                break;

            case 'u':
                url = (char **)realloc(url, sizeof(char *) * (n_url + 1));
                if (!url)
                {
                    fprintf(stderr, "Cannot allocate memory\n");
                    return 2;
                }
                url[n_url++] = optarg;
                break;

            case 'i':
                check_interval = atoi(optarg);
                break;

            case 'x':
                proxy = optarg;
                break;

            case 'y':
                proxy_auth = optarg;
                break;

            case 'v':
                verbose++;
                break;

            case 'V':
                version();
                return 1;

            case 'h':
            default:
                usage();
                return 1;
        }
    }

    mot.timeout = check_interval;
        mot.proxy = proxy;
    mot.proxy_authentication = proxy_auth;
    mot.user_agent = "rsstail " VERSION ", (C) 2006-2007 by [email protected]";

    if (n_url == 0)
    {
        fprintf(stderr, "Please give the URL of the RSS feed to check with the '-u' parameter.\n");
        return 1;
    }

    data_size = sizeof(mrss_t *) * n_url;
    data_prev = (mrss_t **)malloc(data_size);
    data_cur  = (mrss_t **)malloc(data_size);
    if (!data_prev || !data_cur)
    {
        fprintf(stderr, "Cannot allocate memory\n");
        return 2;
    }

    memset(data_prev, 0x00, data_size);
    memset(data_cur , 0x00, data_size);

    if (verbose)
    {
        int loop;
        fprintf(stderr, "Monitoring RSS feeds:\n");
        for(loop=0; loop<n_url; loop++)
            fprintf(stderr, "\t%s\n", url[loop]);
        fprintf(stderr, "Check interval: %d\n", check_interval);
    }

    for(;;)
    {
        mrss_error_t err_read;
        mrss_item_t *item_cur = NULL;
        time_t cur_last_changed;
        int n_shown = 0;

        if (verbose)
            fprintf(stderr, "Retrieving RSS feed '%s'...\n", url[cur_url]);

        if ((err_read = mrss_get_last_modified(url[cur_url], &cur_last_changed)) != MRSS_OK)
        {
            if (err_read == MRSS_ERR_POSIX)
            {
                if (errno == EINPROGRESS)
                {
                    fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
                    goto goto_next_url;
                }
            }

            fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));

            if (no_error_exit)
                goto goto_next_url;
            else
                return 2;
        }

        if (cur_last_changed == last_changed && cur_last_changed != 0)
        {
            if (verbose)
                fprintf(stderr, "Feed did not change since last check.\n");
            goto goto_next_url;
        }
        last_changed = cur_last_changed;

        if ((err_read = mrss_parse_url_with_options(url[cur_url], &data_cur[cur_url], &mot)) != MRSS_OK)
        {
            if (err_read == MRSS_ERR_POSIX)
            {
                if (errno == EINPROGRESS)
                {
                    fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
                    goto goto_next_url;
                }
            }
            else if (err_read == MRSS_ERR_PARSER && continue_on_error)
            {
                fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));
                goto goto_next_url;
            }

            fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));
            if (no_error_exit)
                goto goto_next_url;
            else
                return 2;
        }

        item_cur = data_cur[cur_url] -> item;
        rss_title = data_cur[cur_url] -> title;

        if( !convert_init(cc, data_cur[cur_url]->encoding, convert_system_enc()) )
        {
            fprintf(stderr, "\nERROR: iconv initialization error.\n" );
        }

        while(item_cur)
        {
            if ((data_prev[cur_url] && is_new_record(data_prev[cur_url] -> item, item_cur) != -1) ||
                (!data_prev[cur_url]))
            {
#if 0
                if (/* pubdate */ < max_age && max_age != -1)
                    continue;
#endif

                if ((!data_prev[cur_url]) && n_shown >= show_n && show_n != -1)
                {
                    item_cur = item_cur -> next;
                    continue;
                }
                n_shown++;

                if ((show_link + show_description + show_pubdate + show_author + show_comments ) > 1 && !notify_friendly )
                    printf("\n");

                if (show_timestamp)
                {
                    time_t now = time(NULL);
                    struct tm *now_tm = localtime(&now);

                    printf("%04d/%02d/%02d %02d:%02d:%02d  ",
                            now_tm -> tm_year + 1900,
                            now_tm -> tm_mon + 1,
                            now_tm -> tm_mday,
                            now_tm -> tm_hour,
                            now_tm -> tm_min,
                            now_tm -> tm_sec);
                }

                if (show_pubdate && item_cur -> pubDate != NULL)
                {
                    if ( notify_friendly )
                    {
                        char* new_date_str = convert_pub_date(item_cur->pubDate);
                        printf("%s%s ", no_heading?" ":"Pub.date: ", new_date_str);
                        free(new_date_str);
                    }
                    else
                    {
                        printf("%s%s\n", no_heading?" ":"Pub.date: ", item_cur -> pubDate);
                    }
                }

                if (heading)
                {
                    printf(" %s", heading);
                }

                if ( notify_friendly )
                {
                    if ( rss_title )
                    {
                        conv_rss_title = convert(cc, rss_title);
                        printf("%s*%s* ", no_heading?" ":"RSS Title: ", conv_rss_title);
                        free(conv_rss_title);
                    }
                }

                if (item_cur -> title != NULL)
                {
                    conv_title = convert(cc, item_cur->title);
                    printf("%s%s%s", no_heading?" ":"Title: ", conv_title, (notify_friendly?" ":"\n"));
                    free(conv_title);
                }

                if (show_link && item_cur -> link != NULL)
                {
                    if ( notify_friendly )
                    {
                        printf("%s<a href=\"%s\">Link</a>\n", no_heading?" ":"Link: ", item_cur -> link );
                    }
                    else
                    {
                        printf("%s%s\n", no_heading?" ":"Link: ", item_cur -> link );
                    }
                }
                else
                {
                    if ( notify_friendly )
                    {
                        printf("\n"); //crlf without Link html tag
                    }
                }

                if (show_description && item_cur -> description != NULL)
                {
                    if (strip_html)
                    {
                        char *stripped = remove_html_tags(item_cur -> description);

                        if (bytes_limit != 0 && bytes_limit < strlen(stripped))
                            stripped[bytes_limit] = 0x00;

                        conv_description = convert(cc, stripped);
                        printf("%s%s\n", no_heading?" ":"Description: ", conv_description);
                        free(conv_description);

                        free(stripped);
                    }
                    else
                    {
                        if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> description))
                            (item_cur -> description)[bytes_limit] = 0x00;

                        conv_description = convert(cc, item_cur->description);
                        printf("%s%s\n", no_heading?" ":"Description: ", conv_description);
                        free(conv_description);
                    }
                }

                if (show_author && item_cur -> author != NULL)
                {
                    conv_author = convert(cc, item_cur->author);
                    printf("%s%s\n", no_heading?" ":"Author: ", conv_author);
                    free(conv_author);
                }

                if (show_comments && item_cur -> comments != NULL)
                {
                    if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> comments))
                        (item_cur -> comments)[bytes_limit] = 0x00;

                    conv_comments = convert(cc, item_cur->comments);
                    printf("%s%s\n", no_heading?" ":"Comments: ", conv_comments);
                    free(conv_comments);
                }
            }

            item_cur = item_cur -> next;
        }

        convert_close(cc);

        if (data_prev[cur_url])
        {
            mrss_error_t err_free = mrss_free(data_prev[cur_url]);

            if (err_free != MRSS_OK)
            {
                fprintf(stderr, "Error freeing up memory: %s\n", mrss_strerror(err_read));
                if (no_error_exit)
                    goto goto_next_url;
                else
                    return 2;
            }
        }

        data_prev[cur_url] = data_cur[cur_url];
        data_cur[cur_url] = NULL;

goto_next_url:
        cur_url++;
        if (cur_url == n_url)
            cur_url = 0;

        fflush(stdout);

        if (one_shot)
            break;

        if (verbose > 2)
            fprintf(stderr, "Sleeping...\n");
        sleep(check_interval / n_url);
    }

    return 0;
}
Ejemplo n.º 10
0
/**
 * \brief Input plugin "destructor".
 *
 * \param[in,out] config  plugin_info structure
 * \return 0 on success and config is changed to NULL, nonzero else.
 */
int input_close(void **config)
{
	int ret, error = 0, sock=0;
	struct plugin_conf *conf = (struct plugin_conf*) *config;
	struct input_info_list *info_list;

	/* kill the listening thread */
	if(pthread_cancel(listen_thread) != 0) {
		MSG_WARNING(msg_module, "Cannot cancel listening thread");
	} else {
		pthread_join(listen_thread, NULL);
	}

#ifdef TLS_SUPPORT
	if (conf->tls) {
		/* close TLS connection, if any */
		for (sock = 0; sock < conf->ssl_list_size; sock++) {
			if (conf->ssl_list[sock] == NULL) {
				continue;
			}
			ret = SSL_get_fd(conf->ssl_list[sock]);
			if (ret >= 0) {
				/* send close notify */
				ret = SSL_shutdown(conf->ssl_list[sock]);
				if (ret == -1) {
					MSG_ERROR(msg_module, "Fatal error occured during TLS close notify");
				}
			}

			SSL_free(conf->ssl_list[sock]);
		}
	
		/* we are done here */
		SSL_CTX_free(conf->ctx);
	}
#endif
	
	/* close listening socket */
	if ((ret = close(conf->socket)) == -1) {
		error++;
		MSG_ERROR(msg_module, "Cannot close listening socket: %s", strerror(errno));
	}

	/* close open sockets */
	for (sock = 0; sock <= conf->fd_max; sock++) {
		if (FD_ISSET(sock, &conf->master)) {
			if ((ret = close(sock)) == -1) {
				error++;
				MSG_ERROR(msg_module, "Cannot close socket: %s", strerror(errno));
			}
		}
	}

	destroy_sock_addresses(conf);

	/* free input_info list */
	while (conf->info_list) {
		info_list = conf->info_list->next;
#ifdef TLS_SUPPORT
		X509_free(conf->info_list->exporter_cert);
#endif
		free(conf->info_list);
		conf->info_list = info_list;
	}

	/* free configuration strings */
	if (conf->info.template_life_time != NULL) {
		free(conf->info.template_life_time);
	}
	if (conf->info.template_life_packet != NULL) {
		free(conf->info.template_life_packet);
	}
	if (conf->info.options_template_life_time != NULL) {
		free(conf->info.options_template_life_time);
	}
	if (conf->info.options_template_life_packet != NULL) {
		free(conf->info.options_template_life_packet);
	}
#ifdef TLS_SUPPORT
	/* free strings that are not default (thus static) */
	if (conf->ca_cert_file != NULL) {
		free(conf->ca_cert_file);
	}
	if (conf->server_cert_file != NULL) {
		free(conf->server_cert_file);
	}
	if (conf->server_pkey_file != NULL) {
		free(conf->server_pkey_file);
	}
#endif

	/* free allocated structures */
	FD_ZERO(&conf->master);
	free(*config);
	convert_close();
	*config = NULL;

	MSG_INFO(msg_module, "All allocated resources have been freed");

	return error;
}
Ejemplo n.º 11
0
int
main(int argc, char **argv)
{
	char dbpath[MAXPATHLEN];
	char cwd[MAXPATHLEN];
	STRBUF *sb = strbuf_open(0);
	int optchar;
	int option_index = 0;
	STATISTICS_TIME *tim;

	while ((optchar = getopt_long(argc, argv, "cd:f:iuIn:oOqvwse", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_CONFIG:
			show_config = 1;
			if (optarg)
				config_name = optarg;
			break;
		case OPT_GTAGSCONF:
			gtagsconf = optarg;
			break;
		case OPT_GTAGSLABEL:
			gtagslabel = optarg;
			break;
		case OPT_PATH:
			do_path = 1;
			if (!strcmp("absolute", optarg))
				convert_type = PATH_ABSOLUTE;
			else if (!strcmp("relative", optarg))
				convert_type = PATH_RELATIVE;
			else if (!strcmp("through", optarg))
				convert_type = PATH_THROUGH;
			else
				die("Unknown path type.");
			break;
		case OPT_SINGLE_UPDATE:
			iflag++;
			single_update = optarg;
			break;
		case OPT_ENCODE_PATH:
			if (strlen(optarg) > 255)
				die("too many encode chars.");
			if (strchr(optarg, '/') || strchr(optarg, '.'))
				die("cannot encode '/' and '.' in the path.");
			set_encode_chars((unsigned char *)optarg);
			break;
		case 'c':
			cflag++;
			break;
		case 'd':
			dump_target = optarg;
			break;
		case 'f':
			file_list = optarg;
			break;
		case 'i':
			iflag++;
			break;
		case 'u':
			uflag++;
			iflag++;
			break;
		case 'I':
			Iflag++;
			break;
		case 'o':
			/*
			 * Though the -o(--omit-gsyms) was removed, this code
			 * is left for compatibility.
			 */
			break;
		case 'O':
			Oflag++;
			break;
		case 'q':
			qflag++;
			setquiet();
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
			setverbose();
			break;
		default:
			usage();
			break;
		}
	}
	if (gtagsconf) {
		char path[MAXPATHLEN];

		if (realpath(gtagsconf, path) == NULL)
			die("%s not found.", gtagsconf);
		set_env("GTAGSCONF", path);
	}
	if (gtagslabel) {
		set_env("GTAGSLABEL", gtagslabel);
	}
	if (qflag)
		vflag = 0;
	if (show_version)
		version(NULL, vflag);
	if (show_help)
		help();

	argc -= optind;
        argv += optind;

	/* If dbpath is specified, -O(--objdir) option is ignored. */
	if (argc > 0)
		Oflag = 0;
	if (show_config) {
		if (config_name)
			printconf(config_name);
		else
			fprintf(stdout, "%s\n", getconfline());
		exit(0);
	} else if (do_path) {
		/*
		 * This is the main body of path filter.
		 * This code extract path name from tag line and
		 * replace it with the relative or the absolute path name.
		 *
		 * By default, if we are in src/ directory, the output
		 * should be converted like follws:
		 *
		 * main      10 ./src/main.c  main(argc, argv)\n
		 * main      22 ./libc/func.c   main(argc, argv)\n
		 *		v
		 * main      10 main.c  main(argc, argv)\n
		 * main      22 ../libc/func.c   main(argc, argv)\n
		 *
		 * Similarly, the --path=absolute option specified, then
		 *		v
		 * main      10 /prj/xxx/src/main.c  main(argc, argv)\n
		 * main      22 /prj/xxx/libc/func.c   main(argc, argv)\n
		 */
		STRBUF *ib = strbuf_open(MAXBUFLEN);
		CONVERT *cv;
		char *ctags_x;

		if (argc < 3)
			die("gtags --path: 3 arguments needed.");
		cv = convert_open(convert_type, FORMAT_CTAGS_X, argv[0], argv[1], argv[2], stdout);
		while ((ctags_x = strbuf_fgets(ib, stdin, STRBUF_NOCRLF)) != NULL)
			convert_put(cv, ctags_x);
		convert_close(cv);
		strbuf_close(ib);
		exit(0);
	} else if (dump_target) {
		/*
		 * Dump a tag file.
		 */
		DBOP *dbop = NULL;
		const char *dat = 0;
		int is_gpath = 0;

		char* target_file = NULL;
		if (!test("f", dump_target)) {
			target_file = strchr(dump_target, ':');
			if (target_file == NULL) 
				die("file '%s' not found", dump_target);

			*target_file++ = 0; //move to the next char, which starts the target file.
			if (!test("f", dump_target)) {
				die("file '%s' not found.", dump_target);
			}
		}

		if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
			die("file '%s' is not a tag file.", dump_target);
		/*
		 * The file which has a NEXTKEY record is GPATH.
		 */
		if (dbop_get(dbop, NEXTKEY))
			is_gpath = 1;

		if (target_file && !is_gpath) {
			die("dump target_file can only be used with GPATH");
		}

		if (target_file) {
			dat = dbop_get(dbop, target_file);
			if (dat == NULL) {
				die("target_file %s not found in GPATH", target_file);
			}
			time_t t = gpath_mtime(dbop, target_file);
			printf("%d\n", t);
		} else {
			for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
				const char *flag = is_gpath ? dbop_getflag(dbop) : "";

				if (*flag)
					if (is_gpath) {
						time_t t = gpath_mtime(dbop, dbop->lastkey);
						printf("%s\t%s\t%s\t%s\n", dbop->lastkey, dat, flag, ctime(&t));
					} else
						printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
				else
					printf("%s\t%s\n", dbop->lastkey, dat);
			}
		}
		dbop_close(dbop);
		exit(0);
	} else if (Iflag) {
		if (!usable("mkid"))
			die("mkid not found.");
	}

	/*
	 * If 'gtags.files' exists, use it as a file list.
	 * If the file_list other than "-" is given, it must be readable file.
	 */
	if (file_list == NULL && test("f", GTAGSFILES))
		file_list = GTAGSFILES;
	if (file_list && strcmp(file_list, "-")) {
		if (test("d", file_list))
			die("'%s' is a directory.", file_list);
		else if (!test("f", file_list))
			die("'%s' not found.", file_list);
		else if (!test("r", file_list))
			die("'%s' is not readable.", file_list);
	}
	/*
	 * Regularize the path name for single updating (--single-update).
	 */
	if (single_update) {
		static char regular_path_name[MAXPATHLEN];
		char *p = single_update;
		
		if (!test("f", p))
			die("'%s' not found.", p);
		if (isabspath(p))
			die("--single-update requires relative path name.");
		if (!(p[0] == '.' && p[1] == '/')) {
			snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
			p = regular_path_name;
		}
		single_update = p;
	}
	if (!getcwd(cwd, MAXPATHLEN))
		die("cannot get current directory.");
	canonpath(cwd);
	/*
	 * Decide directory (dbpath) in which gtags make tag files.
	 *
	 * Gtags create tag files at current directory by default.
	 * If dbpath is specified as an argument then use it.
	 * If the -i option specified and both GTAGS and GRTAGS exists
	 * at one of the candidate directories then gtags use existing
	 * tag files.
	 */
	if (iflag) {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	} else {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (Oflag) {
			char *objdir = getobjdir(cwd, vflag);

			if (objdir == NULL)
				die("Objdir not found.");
			strlimcpy(dbpath, objdir, sizeof(dbpath));
		} else
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	}
	if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
		if (wflag)
			warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
		iflag = 0;
	}
	if (!test("d", dbpath))
		die("directory '%s' not found.", dbpath);
	if (vflag)
		fprintf(stderr, "[%s] Gtags started.\n", now());
	/*
	 * load configuration file.
	 */
	openconf();
	if (getconfb("extractmethod"))
		extractmethod = 1;
	strbuf_reset(sb);
	if (getconfs("langmap", sb))
		langmap = check_strdup(strbuf_value(sb));
	strbuf_reset(sb);
	if (getconfs("gtags_parser", sb))
		gtags_parser = check_strdup(strbuf_value(sb));
	/*
	 * initialize parser.
	 */
	if (vflag && gtags_parser)
		fprintf(stderr, " Using plug-in parser.\n");
	parser_init(langmap, gtags_parser);
	if (vflag && file_list)
		fprintf(stderr, " Using '%s' as a file list.\n", file_list);
	/*
	 * Start statistics.
	 */
	init_statistics();
	/*
	 * incremental update.
	 */
	if (iflag) {
		/*
		 * Version check. If existing tag files are old enough
		 * gtagsopen() abort with error message.
		 */
		GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
		gtags_close(gtop);
		/*
		 * GPATH is needed for incremental updating.
		 * Gtags check whether or not GPATH exist, since it may be
		 * removed by mistake.
		 */
		if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
			die("Old version tag file found. Please remake it.");
		(void)incremental(dbpath, cwd);
		print_statistics(statistics);
		exit(0);
	}
	/*
	 * create GTAGS and GRTAGS
	 */
	createtags(dbpath, cwd);
	/*
	 * create idutils index.
	 */
	if (Iflag) {
		tim = statistics_time_start("Time of creating ID");
		if (vflag)
			fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
		strbuf_reset(sb);
		strbuf_puts(sb, "mkid");
		if (vflag)
			strbuf_puts(sb, " -v");
		strbuf_sprintf(sb, " --file='%s/ID'", dbpath);
		if (vflag) {
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 1>&2");
		} else {
			strbuf_puts(sb, " >/dev/null");
		}
		if (debug)
			fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
		if (system(strbuf_value(sb)))
			die("mkid failed: %s", strbuf_value(sb));
		if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
			die("cannot chmod ID file.");
		statistics_time_end(tim);
	}
	if (vflag)
		fprintf(stderr, "[%s] Done.\n", now());
	closeconf();
	strbuf_close(sb);
	print_statistics(statistics);

	return 0;
}
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{
	struct cap_handle *caphandle = NULL;
	struct cvt_handle *cvthandle = NULL;
	struct enc_handle *enchandle = NULL;
	struct pac_handle *pachandle = NULL;
	struct net_handle *nethandle = NULL;
	struct cap_param capp;
	struct cvt_param cvtp;
	struct enc_param encp;
	struct pac_param pacp;
	struct net_param netp;
	int stage = 0b00000011;

	U32 vfmt = V4L2_PIX_FMT_YUYV;
	U32 ofmt = V4L2_PIX_FMT_YUV420;

	// set default values
	capp.dev_name = "/dev/video0";
	capp.width = 640;
	capp.height = 480;
	capp.pixfmt = vfmt;
	capp.rate = 15;

	cvtp.inwidth = 640;
	cvtp.inheight = 480;
	cvtp.inpixfmt = vfmt;
	cvtp.outwidth = 640;
	cvtp.outheight = 480;
	cvtp.outpixfmt = ofmt;

	encp.src_picwidth = 640;
	encp.src_picheight = 480;
	encp.enc_picwidth = 640;
	encp.enc_picheight = 480;
	encp.chroma_interleave = 0;
	encp.fps = 15;
	encp.gop = 12;
	encp.bitrate = 1000;

	pacp.max_pkt_len = 1400;
	pacp.ssrc = 1234;

	netp.serip = NULL;
	netp.serport = -1;
	netp.type = UDP;

	char *outfile = NULL;
	// options
	int opt = 0;
	static const char *optString = "?di:o:a:p:w:h:r:f:t:g:s:c:";

	opt = getopt(argc, argv, optString);
	while (opt != -1)
	{
		int fmt;
		switch (opt)
		{
			case '?':
				display_usage();
				return 0;
			case 'd':
				debug = 1;
				break;
			case 's':
				stage = atoi(optarg);
				break;
			case 'i':
				capp.dev_name = optarg;
				break;
			case 'o':
				outfile = optarg;
				break;
			case 'a':
				netp.serip = optarg;
				break;
			case 'p':
				netp.serport = atoi(optarg);
				break;
			case 'c':
				fmt = atoi(optarg);
				if (fmt == 1)
					capp.pixfmt = V4L2_PIX_FMT_YUV420;
				else
					capp.pixfmt = V4L2_PIX_FMT_YUYV;
				break;
			case 'w':
				capp.width = cvtp.inwidth = cvtp.outwidth = encp.src_picwidth =
						encp.enc_picwidth = atoi(optarg);
				break;
			case 'h':
				capp.height = cvtp.inheight = cvtp.outheight =
						encp.src_picheight = encp.enc_picheight = atoi(optarg);
				break;
			case 'r':
				encp.bitrate = atoi(optarg);
				break;
			case 'f':
				capp.rate = encp.fps = atoi(optarg);
				break;
			case 't':
				encp.chroma_interleave = atoi(optarg);
				break;
			case 'g':
				encp.gop = atoi(optarg);
				break;
			default:
				printf("Unknown option: %s\n", optarg);
				display_usage();
				return -1;
		}

		opt = getopt(argc, argv, optString);
	}

	if (outfile)
		outfd = fopen(outfile, "wb");

	signal(SIGINT, quit_func);

	caphandle = capture_open(capp);
	if (!caphandle)
	{
		printf("--- Open capture failed\n");
		return -1;
	}

	if ((stage & 0b00000001) != 0)
	{
		cvthandle = convert_open(cvtp);
		if (!cvthandle)
		{
			printf("--- Open convert failed\n");
			return -1;
		}
	}

	if ((stage & 0b00000010) != 0)
	{
		enchandle = encode_open(encp);
		if (!enchandle)
		{
			printf("--- Open encode failed\n");
			return -1;
		}
	}

	if ((stage & 0b00000100) != 0)
	{
		pachandle = pack_open(pacp);
		if (!pachandle)
		{
			printf("--- Open pack failed\n");
			return -1;
		}
	}

	if ((stage & 0b00001000) != 0)
	{
		if (netp.serip == NULL || netp.serport == -1)
		{
			printf(
					"--- Server ip and port must be specified when using network\n");
			return -1;
		}

		nethandle = net_open(netp);
		if (!nethandle)
		{
			printf("--- Open network failed\n");
			return -1;
		}
	}

	// start capture encode loop
	int ret;
	void *cap_buf, *cvt_buf, *hd_buf, *enc_buf;
	char *pac_buf = (char *) malloc(MAX_RTP_SIZE);
	int cap_len, cvt_len, hd_len, enc_len, pac_len;
	enum pic_t ptype;
	struct timeval ctime, ltime;
	unsigned long fps_counter = 0;
	int sec, usec;
	double stat_time = 0;

	capture_start(caphandle);		// !!! need to start capture stream!
	quit = 0;
	gettimeofday(&ltime, NULL);
	while (!quit)
	{
		if (debug)		// print fps
		{
			gettimeofday(&ctime, NULL);
			sec = ctime.tv_sec - ltime.tv_sec;
			usec = ctime.tv_usec - ltime.tv_usec;
			if (usec < 0)
			{
				sec--;
				usec = usec + 1000000;
			}
			stat_time = (sec * 1000000) + usec;		// diff in microsecond

			if (stat_time >= 1000000)    // >= 1s
			{
				printf("\n*** FPS: %ld\n", fps_counter);

				fps_counter = 0;
				ltime = ctime;
			}
			fps_counter++;
		}

		ret = capture_get_data(caphandle, &cap_buf, &cap_len);
		if (ret != 0)
		{
			if (ret < 0)		// error
			{
				printf("--- capture_get_data failed\n");
				break;
			}
			else	// again
			{
				usleep(10000);
				continue;
			}
		}
		if (cap_len <= 0)
		{
			printf("!!! No capture data\n");
			continue;
		}
		if (debug)
			fputc('.', stdout);

		if ((stage & 0b00000001) == 0)    // no convert, capture only
		{
			if (outfd)
				fwrite(cap_buf, 1, cap_len, outfd);

			continue;
		}

		// convert
		if (capp.pixfmt == V4L2_PIX_FMT_YUV420)    // no need to convert
		{
			cvt_buf = cap_buf;
			cvt_len = cap_len;
		}
		else	// do convert: YUYV => YUV420
		{
			ret = convert_do(cvthandle, cap_buf, cap_len, &cvt_buf, &cvt_len);
			if (ret < 0)
			{
				printf("--- convert_do failed\n");
				break;
			}
			if (cvt_len <= 0)
			{
				printf("!!! No convert data\n");
				continue;
			}
		}
		if (debug)
			fputc('-', stdout);

		if ((stage & 0b00000010) == 0)		// no encode
		{
			if (outfd)
				fwrite(cvt_buf, 1, cvt_len, outfd);

			continue;
		}

		// encode
		// fetch h264 headers first!
		while ((ret = encode_get_headers(enchandle, &hd_buf, &hd_len, &ptype))
				!= 0)
		{
			if (debug)
				fputc('S', stdout);

			if ((stage & 0b00000100) == 0)		// no pack
			{
				if (outfd)
					fwrite(hd_buf, 1, hd_len, outfd);

				continue;
			}

			// pack headers
			pack_put(pachandle, hd_buf, hd_len);
			while (pack_get(pachandle, pac_buf, MAX_RTP_SIZE, &pac_len) == 1)
			{
				if (debug)
					fputc('#', stdout);

				if ((stage & 0b00001000) == 0)    // no network
				{
					if (outfd)
						fwrite(pac_buf, 1, pac_len, outfd);

					continue;
				}

				// network
				ret = net_send(nethandle, pac_buf, pac_len);
				if (ret != pac_len)
				{
					printf("send pack failed, size: %d, err: %s\n", pac_len,
							strerror(errno));
				}
				if (debug)
					fputc('>', stdout);
			}
		}

		ret = encode_do(enchandle, cvt_buf, cvt_len, &enc_buf, &enc_len,
				&ptype);
		if (ret < 0)
		{
			printf("--- encode_do failed\n");
			break;
		}
		if (enc_len <= 0)
		{
			printf("!!! No encode data\n");
			continue;
		}

		if (debug)
		{
			char c;
			switch (ptype)
			{
				case PPS:
					c = 'S';
					break;
				case SPS:
					c = 'S';
					break;
				case I:
					c = 'I';
					break;
				case P:
					c = 'P';
					break;
				case B:
					c = 'B';
					break;
				default:
					c = 'N';
					break;
			}

			fputc(c, stdout);
		}

		if ((stage & 0b00000100) == 0)		// no pack
		{
			if (outfd)
				fwrite(enc_buf, 1, enc_len, outfd);

			continue;
		}

		// pack
		pack_put(pachandle, enc_buf, enc_len);
		while (pack_get(pachandle, pac_buf, MAX_RTP_SIZE, &pac_len) == 1)
		{
			if (debug)
				fputc('#', stdout);

			if ((stage & 0b00001000) == 0)    // no network
			{
				if (outfd)
					fwrite(pac_buf, 1, pac_len, outfd);

				continue;
			}

			// network
			ret = net_send(nethandle, pac_buf, pac_len);
			if (ret != pac_len)
			{
				printf("send pack failed, size: %d, err: %s\n", pac_len,
						strerror(errno));
			}
			if (debug)
				fputc('>', stdout);
		}
	}
	capture_stop(caphandle);

	free(pac_buf);
	if ((stage & 0b00001000) != 0)
		net_close(nethandle);
	if ((stage & 0b00000100) != 0)
		pack_close(pachandle);
	if ((stage & 0b00000010) != 0)
		encode_close(enchandle);
	if ((stage & 0b00000001) != 0)
		convert_close(cvthandle);
	capture_close(caphandle);

	if (outfd)
		fclose(outfd);
	return 0;
}
Ejemplo n.º 13
0
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int db;
	int optchar;
	int option_index = 0;
	int status = 0;

	/*
	 * get path of following directories.
	 *	o current directory
	 *	o root of source tree
	 *	o dbpath directory
	 *
	 * if GTAGS not found, exit with an error message.
	 */
	status = setupdbpath(0);
	if (status == 0) {
		cwd = get_cwd();
		root = get_root();
		dbpath = get_dbpath();
	}
	/*
	 * Setup GTAGSCONF and GTAGSLABEL environment variable
	 * according to the --gtagsconf and --gtagslabel option.
	 */
	preparse_options(argc, argv);
	/*
	 * Open configuration file.
	 */
	openconf(root);
	setenv_from_config();
	logging_arguments(argc, argv);
	while ((optchar = getopt_long(argc, argv, "acde:EifFgGIlL:MnoOpPqrsS:tTuvVx", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			break;
		case 'a':
			aflag++;
			break;
		case 'c':
			cflag++;
			setcom(optchar);
			break;
		case 'd':
			dflag++;
			break;
		case 'e':
			av = optarg;
			break;
		case 'E':
			Gflag = 0;
			break;
		case 'f':
			fflag++;
			xflag++;
			setcom(optchar);
			break;
		case 'F':
			Tflag = 0;
			break;
		case 'g':
			gflag++;
			setcom(optchar);
			break;
		case 'G':
			Gflag++;
			break;
		case 'i':
			iflag++;
			break;
		case 'I':
			Iflag++;
			setcom(optchar);
			break;
		case 'l':
			Sflag++;
			scope = ".";
			break;
		case 'L':
			file_list = optarg;
			break;
		case 'M':
			Mflag++;
			iflag = 0;
			break;
		case 'n':
			nflag++;
			if (optarg) {
				if (!strcmp(optarg, "sort"))
					nofilter |= SORT_FILTER;
				else if (!strcmp(optarg, "path"))
					nofilter |= PATH_FILTER;
			} else {
				nofilter = BOTH_FILTER;
			}
			break;
		case 'o':
			oflag++;
			break;
		case 'O':
			Oflag++;
			break;
		case 'p':
			pflag++;
			setcom(optchar);
			break;
		case 'P':
			Pflag++;
			setcom(optchar);
			break;
		case 'q':
			qflag++;
			setquiet();
			break;
		case 'r':
			rflag++;
			break;
		case 's':
			sflag++;
			break;
		case 'S':
			Sflag++;
			scope = optarg;
			break;
		case 't':
			tflag++;
			break;
		case 'T':
			Tflag++;
			break;
		case 'u':
			uflag++;
			setcom(optchar);
			break;
		case 'v':
			vflag++;
			setverbose();
			break;
		case 'V':
			Vflag++;
			break;
		case 'x':
			xflag++;
			break;
		case OPT_USE_COLOR:
			if (optarg) {
				if (!strcmp(optarg, "never"))
					use_color = 0;
				else if (!strcmp(optarg, "always"))
					use_color = 1;
				else if (!strcmp(optarg, "auto"))
					use_color = 2;
				else
					die_with_code(2, "unknown color type.");
			} else {
				use_color = 2;
			}
			break;
		case OPT_ENCODE_PATH:
			encode_chars = optarg;
			break;
		case OPT_FROM_HERE:
			{
			char *p = optarg;
			const char *usage = "usage: global --from-here=lineno:path.";

			context_lineno = p;
			while (*p && isdigit(*p))
				p++;
			if (*p != ':')
				die_with_code(2, usage);
			*p++ = '\0';
			if (!*p)
				die_with_code(2, usage);
			context_file = p;
			}
			break;
		case OPT_GTAGSCONF:
		case OPT_GTAGSLABEL:
			/* These options are already parsed in preparse_options() */
			break;
		case OPT_MATCH_PART:
			if (!strcmp(optarg, "first"))
				match_part = MATCH_PART_FIRST;
			else if (!strcmp(optarg, "last"))
				match_part = MATCH_PART_LAST;
			else if (!strcmp(optarg, "all"))
				match_part = MATCH_PART_ALL;
			else
				die_with_code(2, "unknown part type for the --match-part option.");
			break;
		case OPT_PATH_CONVERT:
			do_path = 1;
			if (!strcmp("absolute", optarg))
				convert_type = PATH_ABSOLUTE;
			else if (!strcmp("relative", optarg))
				convert_type = PATH_RELATIVE;
			else if (!strcmp("through", optarg))
				convert_type = PATH_THROUGH;
			else
				die("Unknown path type.");
			break;
		case OPT_PATH_STYLE:
			path_style = optarg;
			break;
		case OPT_RESULT:
			if (!strcmp(optarg, "ctags-x"))
				format = FORMAT_CTAGS_X;
			else if (!strcmp(optarg, "ctags-xid"))
				format = FORMAT_CTAGS_XID;
			else if (!strcmp(optarg, "ctags"))
				format = FORMAT_CTAGS;
			else if (!strcmp(optarg, "ctags-mod"))
				format = FORMAT_CTAGS_MOD;
			else if (!strcmp(optarg, "path"))
				format = FORMAT_PATH;
			else if (!strcmp(optarg, "grep"))
				format = FORMAT_GREP;
			else if (!strcmp(optarg, "cscope"))
				format = FORMAT_CSCOPE;
			else
				die_with_code(2, "unknown format type for the --result option.");
			break;
		case OPT_SINGLE_UPDATE:
			single_update = optarg;
			break;
		default:
			usage();
			break;
		}
	}
	if (qflag)
		vflag = 0;
	if (show_version)
		version(av, vflag);
	if (show_help)
		help();
	if (dbpath == NULL)
		die_with_code(-status, gtags_dbpath_error);
	/*
	 * decide format.
	 * The --result option is given to priority more than the -t and -x option.
	 */
	if (format == 0) {
		if (tflag) { 			/* ctags format */
			format = FORMAT_CTAGS;
		} else if (xflag) {		/* print details */
			format = FORMAT_CTAGS_X;
		} else {			/* print just a file name */
			format = FORMAT_PATH;
		}
	}
	/*
	 * GTAGSBLANKENCODE will be used in less(1).
	 */
	switch (format) {
	case FORMAT_CTAGS_X:
	case FORMAT_CTAGS_XID:
		if (encode_chars == NULL && getenv("GTAGSBLANKENCODE"))
			encode_chars = " \t";
		break;
	}
	if (encode_chars) {
		if (strlen(encode_chars) > 255)
			die("too many encode chars.");
		if (strchr(encode_chars, '/') || strchr(encode_chars, '.'))
			warning("cannot encode '/' and '.' in the path. Ignored.");
		set_encode_chars((unsigned char *)encode_chars);
	}
	if (getenv("GTAGSTHROUGH"))
		Tflag++;
	if (use_color) {
#if defined(_WIN32) && !defined(__CYGWIN__)
		if (!(getenv("ANSICON") || LoadLibrary("ANSI32.dll")) && use_color == 2)
			use_color = 0;
#endif
		if (use_color == 2 && !isatty(1))
			use_color = 0;
		if (Vflag)
			use_color = 0;
	}
	argc -= optind;
	argv += optind;
	/*
	 * Path filter
	 */
	if (do_path) {
		/*
		 * This code is needed for globash.rc.
		 * This code extract path name from tag line and
		 * replace it with the relative or the absolute path name.
		 *
		 * By default, if we are in src/ directory, the output
		 * should be converted like follows:
		 *
		 * main      10 ./src/main.c  main(argc, argv)\n
		 * main      22 ./libc/func.c   main(argc, argv)\n
		 *		v
		 * main      10 main.c  main(argc, argv)\n
		 * main      22 ../libc/func.c   main(argc, argv)\n
		 *
		 * Similarly, the --path-convert=absolute option specified, then
		 *		v
		 * main      10 /prj/xxx/src/main.c  main(argc, argv)\n
		 * main      22 /prj/xxx/libc/func.c   main(argc, argv)\n
		 */
		STRBUF *ib = strbuf_open(MAXBUFLEN);
		CONVERT *cv;
		char *ctags_x;

		if (argc < 3)
			die("global --path-convert: 3 arguments needed.");
		cv = convert_open(convert_type, FORMAT_CTAGS_X, argv[0], argv[1], argv[2], stdout, NOTAGS);
		while ((ctags_x = strbuf_fgets(ib, stdin, STRBUF_NOCRLF)) != NULL)
			convert_put(cv, ctags_x);
		convert_close(cv);
		strbuf_close(ib);
		exit(0);
	}
	/*
	 * At first, we pickup pattern from -e option. If it is not found
	 * then use argument which is not option.
	 */
	if (!av) {
		av = *argv;
		/*
		 * global -g pattern [files ...]
		 *           av      argv
		 */
		if (gflag && av)
			argv++;
	}
	if (single_update) {
		if (command == 0) {
			uflag++;
			command = 'u';
		} else if (command != 'u') {
			;	/* ignored */
		}
	}
	/*
	 * only -c, -u, -P and -p allows no argument.
	 */
	if (!av) {
		switch (command) {
		case 'c':
		case 'u':
		case 'p':
		case 'P':
			break;
		case 'f':
			if (file_list)
				break;
		default:
			usage();
			break;
		}
	}
	/*
	 * -u and -p cannot have any arguments.
	 */
	if (av) {
		switch (command) {
		case 'u':
		case 'p':
			usage();
		default:
			break;
		}
	}
	if (tflag)
		xflag = 0;
	if (nflag > 1)
		nosource = 1;	/* to keep compatibility */
	if (print0)
		set_print0();
	if (cflag && match_part == 0)
		match_part = MATCH_PART_ALL;
	/*
	 * remove leading blanks.
	 */
	if (!Iflag && !gflag && av)
		for (; *av == ' ' || *av == '\t'; av++)
			;
	if (cflag && !Pflag && av && isregex(av))
		die_with_code(2, "only name char is allowed with -c option.");
	/*
	 * print dbpath or rootdir.
	 */
	if (pflag) {
		fprintf(stdout, "%s\n", (rflag) ? root : dbpath);
		exit(0);
	}
	/*
	 * incremental update of tag files.
	 */
	if (uflag) {
		STRBUF	*sb = strbuf_open(0);
		char *gtags_path = usable("gtags");

		if (!gtags_path)
			die("gtags command not found.");
		if (chdir(root) < 0)
			die("cannot change directory to '%s'.", root);
#if defined(_WIN32) && !defined(__CYGWIN__)
		/*
		 * Get around CMD.EXE's weird quoting rules by sticking another
		 * perceived whitespace in front (also works with Take Command).
		 */
		strbuf_putc(sb, ';');
#endif
		strbuf_puts(sb, quote_shell(gtags_path));
		strbuf_puts(sb, " -i");
		if (vflag)
			strbuf_puts(sb, " -v");
		if (single_update) {
			if (!isabspath(single_update)) {
				static char regular_path_name[MAXPATHLEN];

				if (rel2abs(single_update, cwd, regular_path_name, sizeof(regular_path_name)) == NULL)
					die("rel2abs failed.");
				single_update = regular_path_name;
			}
			strbuf_puts(sb, " --single-update ");
			strbuf_puts(sb, quote_shell(single_update));
		}
		strbuf_putc(sb, ' ');
		strbuf_puts(sb, quote_shell(dbpath));
		if (system(strbuf_value(sb)))
			exit(1);
		strbuf_close(sb);
		exit(0);
	}
	/*
	 * decide tag type.
	 */
	if (context_file) {
		if (isregex(av))
			die_with_code(2, "regular expression is not allowed with the --from-here option.");
		db = decide_tag_by_context(av, context_file, atoi(context_lineno));
	} else {
		if (dflag)
			db = GTAGS;
		else if (rflag && sflag)
			db = GRTAGS + GSYMS;
		else
			db = (rflag) ? GRTAGS : ((sflag) ? GSYMS : GTAGS);
	}
	/*
	 * complete function name
	 */
	if (cflag) {
		if (Iflag)
			completion_idutils(dbpath, root, av);
		else if (Pflag)
			completion_path(dbpath, av);
		else
			completion(dbpath, root, av, db);
		exit(0);
	}
	/*
	 * make local prefix.
	 * local prefix must starts with './' and ends with '/'.
	 */
	if (Sflag) {
		STRBUF *sb = strbuf_open(0);
		static char buf[MAXPATHLEN];
		const char *path = scope;
	
		/*
		 * normalize the path of scope directory.
		 */
		if (!test("d", path))
			die("'%s' not found or not a directory.", scope);
		if (!isabspath(path))
			path = makepath(cwd, path, NULL);
		if (realpath(path, buf) == NULL)
			die("cannot get real path of '%s'.", scope);
		if (!in_the_project(buf))
			die("'%s' is out of the source project.", scope);
		scope = buf;
		/*
		 * make local prefix.
		 */
		strbuf_putc(sb, '.');
		if (strcmp(root, scope) != 0) {
			const char *p = scope + strlen(root);
			if (*p != '/')
				strbuf_putc(sb, '/');
			strbuf_puts(sb, p);
		}
		strbuf_putc(sb, '/');
		localprefix = check_strdup(strbuf_value(sb));
		strbuf_close(sb);
#ifdef DEBUG
		fprintf(stderr, "root=%s\n", root);
		fprintf(stderr, "cwd=%s\n", cwd);
		fprintf(stderr, "localprefix=%s\n", localprefix);
#endif
	}
	/*
	 * convert the file-list path into an absolute path.
	 */
	if (file_list && strcmp(file_list, "-") && !isabspath(file_list)) {
		static char buf[MAXPATHLEN];

		if (realpath(file_list, buf) == NULL)
			die("'%s' not found.", file_list);
		file_list = buf;
	}
	/*
	 * decide path conversion type.
	 */
	if (nofilter & PATH_FILTER)
		type = PATH_THROUGH;
	else if (aflag)
		type = PATH_ABSOLUTE;
	else
		type = PATH_RELATIVE;
	if (path_style) {
		if (!strcmp(path_style, "relative"))
			type = PATH_RELATIVE;
		else if (!strcmp(path_style, "absolute"))
			type = PATH_ABSOLUTE;
		else if (!strcmp(path_style, "through"))
			type = PATH_THROUGH;
		else if (!strcmp(path_style, "shorter"))
			type = PATH_SHORTER;
		else if (!strcmp(path_style, "abslib")) {
			type = PATH_RELATIVE;
			abslib++;
		} else
			die("invalid path style.");
	}
	/*
	 * exec lid(idutils).
	 */
	if (Iflag) {
		chdir(root);
		idutils(av, dbpath);
	}
	/*
	 * search pattern (regular expression).
	 */
	else if (gflag) {
		chdir(root);
		grep(av, argv, dbpath);
	}
	/*
	 * locate paths including the pattern.
	 */
	else if (Pflag) {
		chdir(root);
		pathlist(av, dbpath);
	}
	/*
	 * parse source files.
	 */
	else if (fflag) {
		chdir(root);
		parsefile(argv, cwd, root, dbpath, db);
	}
	/*
	 * tag search.
	 */
	else {
		tagsearch(av, cwd, root, dbpath, db);
	}
	return 0;
}
Ejemplo n.º 14
0
/**
 * grep: @NAME{grep} pattern
 *
 *	@param[in]	pattern	@NAME{POSIX} regular expression
 *	@param	argv
 *	@param	dbpath
 */
void
grep(const char *pattern, char *const *argv, const char *dbpath)
{
	FILE *fp;
	CONVERT *cv;
	GFIND *gp = NULL;
	STRBUF *ib = strbuf_open(MAXBUFLEN);
	const char *path;
	char encoded_pattern[IDENTLEN];
	const char *buffer;
	int linenum, count;
	int flags = 0;
	int target = GPATH_SOURCE;
	regex_t	preg;
	int user_specified = 1;

	/*
	 * convert spaces into %FF format.
	 */
	encode(encoded_pattern, sizeof(encoded_pattern), pattern);
	/*
	 * literal search available?
	 */
	if (!literal) {
		const char *p = pattern;
		int normal = 1;

		for (; *p; p++) {
			if (!(isalpha(*p) || isdigit(*p) || isblank(*p) || *p == '_')) {
				normal = 0;
				break;
			}
		}
		if (normal)
			literal = 1;
	}
	if (oflag)
		target = GPATH_BOTH;
	if (Oflag)
		target = GPATH_OTHER;
	if (literal) {
		literal_comple(pattern);
	} else {
		if (!Gflag)
			flags |= REG_EXTENDED;
		if (iflag)
			flags |= REG_ICASE;
		if (regcomp(&preg, pattern, flags) != 0)
			die("invalid regular expression.");
	}
	cv = convert_open(type, format, root, cwd, dbpath, stdout, NOTAGS);
	cv->tag_for_display = encoded_pattern;
	count = 0;

	if (*argv && file_list)
		args_open_both(argv, file_list);
	else if (*argv)
		args_open(argv);
	else if (file_list)
		args_open_filelist(file_list);
	else {
		args_open_gfind(gp = gfind_open(dbpath, localprefix, target));
		user_specified = 0;
	}
	while ((path = args_read()) != NULL) {
		if (user_specified) {
			static char buf[MAXPATHLEN];

			if (normalize(path, get_root_with_slash(), cwd, buf, sizeof(buf)) == NULL) {
				warning("'%s' is out of the source project.", path);
				continue;
			}
			if (test("d", buf)) {
				warning("'%s' is a directory. Ignored.", path);
				continue;
			}
			if (!test("f", buf)) {
				warning("'%s' not found. Ignored.", path);
				continue;
			}
			path = buf;
		}
		if (Sflag && !locatestring(path, localprefix, MATCH_AT_FIRST))
			continue;
		if (literal) {
			int n = literal_search(cv, path);
			if (n > 0)
				count += n;
		} else {
			if (!(fp = fopen(path, "r")))
				die("cannot open file '%s'.", path);
			linenum = 0;
			while ((buffer = strbuf_fgets(ib, fp, STRBUF_NOCRLF)) != NULL) {
				int result = regexec(&preg, buffer, 0, 0, 0);
				linenum++;
				if ((!Vflag && result == 0) || (Vflag && result != 0)) {
					count++;
					if (format == FORMAT_PATH) {
						convert_put_path(cv, NULL, path);
						break;
					} else {
						convert_put_using(cv, pattern, path, linenum, buffer,
							(user_specified) ? NULL : gp->dbop->lastdat);
					}
				}
			}
			fclose(fp);
		}
	}
	args_close();
	convert_close(cv);
	strbuf_close(ib);
	if (literal == 0)
		regfree(&preg);
	if (vflag) {
		print_count(count);
		fprintf(stderr, " (no index used).\n");
	}
}