Esempio n. 1
0
int		main(int ac, char **av)
{
	t_nm		nm;
	int			i;
	int			return_value;
	t_symtable	*list;
	static char	default_name[] = "a.out";

	return_value = EXIT_SUCCESS;
	nm_init(&nm, av);
	nm.list = &list;
	if (ac < 2)
	{
		nm.file = default_name;
		return (handle_file(&nm));
	}
	nm.file = av[1];
	if ((i = nm_flag_handler(av, &(nm.flag))) < 0)
		return (return_value);
	nm.flag = ((ac - i - 2) > 0) ? nm.flag | FLAG_PRINT : nm.flag;
	while (++i < ac)
	{
		nm.file = av[i];
		return_value |= handle_file(&nm);
	}
	return (return_value);
}
Esempio n. 2
0
DEFINE_MAIN_PROTO(cat, argc, argv)
{
    int i;
    const char* progname;
    FILE* handle;
    progname = argv[0];
    if(argc == 1)
    {
        handle_file(progname, stdin, "<stdin>");
        return 0;
    }
    for(i=1; i<argc; i++)
    {
        handle = fopen(argv[i], "rb");
        if(handle == NULL)
        {
            bail(false, "%s: cannot open %s", progname, argv[i]);
        }
        else
        {
            handle_file(progname, handle, argv[i]);
            fclose(handle);
        }
    }
    return 0;
}
Esempio n. 3
0
int handle(int newsockfd, struct sockaddr_in socket, socklen_t socklen)
{
    char buffer[256], path[PATH_MAX], *url;
    struct stat path_stat;
    int n;

    (void) socklen;

    bzero(buffer, 256);
    n = read(newsockfd, buffer, 255);
    if (n < 0)
        error("error reading");

    url = geturl(buffer);

    info("%s GET %s", inet_ntoa(socket.sin_addr), url);

    snprintf(path, PATH_MAX, "%s/%s", basedir, url);

    while (n == 255)
        n = read(newsockfd, buffer, 255);

    if (stat(path, &path_stat)) {
        handle_notfound(newsockfd);
    } else {
        if (S_ISDIR(path_stat.st_mode)) {
            if (path[strlen(path)-1] != '/') {
                size_t len;
                len = strlen(url);
                url = realloc(url, len + 2);
                url[len] = '/';
                url[len+1] = 0;
                handle_redirection(url, url, newsockfd);
            } else {
                struct stat index_stat;
                char index_path[PATH_MAX];
                snprintf(index_path, PATH_MAX, "%s/index.html", path);
                index_stat.st_mode = 0;
                stat(index_path, &index_stat);
                if (S_ISREG(index_stat.st_mode))
                    handle_file(url, index_path, newsockfd);
                else
                    handle_directory(url, path, newsockfd);
            }
        } else {
            handle_file(url, path, newsockfd);
        }
    }

    close(newsockfd);
    free(url);
    return 0;
}
/* this is used with -r to recursively descend directories */
static void
handle_dir(char *dir)
{
	char *path_argv[2];
	FTS *fts;
	FTSENT *entry;

	path_argv[0] = dir;
	path_argv[1] = 0;
	fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
	if (fts == NULL) {
		warn("couldn't fts_open %s", dir);
		return;
	}

	while ((entry = fts_read(fts))) {
		switch(entry->fts_info) {
		case FTS_D:
		case FTS_DP:
			continue;

		case FTS_DNR:
		case FTS_ERR:
		case FTS_NS:
			maybe_warn("%s", entry->fts_path);
			continue;
		case FTS_F:
			handle_file(entry->fts_name, entry->fts_statp);
		}
	}
	(void)fts_close(fts);
}
Esempio n. 5
0
/*
 * The path indicated by rr_item may still have conflict for which we
 * have a recorded resolution, in which case replay it and optionally
 * update it.  Or it may have been resolved by the user and we may
 * only have the preimage for that conflict, in which case the result
 * needs to be recorded as a resolution in a postimage file.
 */
static void do_rerere_one_path(struct string_list_item *rr_item,
			       struct string_list *update)
{
	const char *path = rr_item->string;
	const struct rerere_id *id = rr_item->util;

	/* Is there a recorded resolution we could attempt to apply? */
	if (has_rerere_resolution(id)) {
		if (merge(id, path))
			return; /* failed to replay */

		if (rerere_autoupdate)
			string_list_insert(update, path);
		else
			fprintf(stderr,
				"Resolved '%s' using previous resolution.\n",
				path);
	} else if (!handle_file(path, NULL, NULL)) {
		/* The user has resolved it. */
		copy_file(rerere_path(id, "postimage"), path, 0666);
		fprintf(stderr, "Recorded resolution for '%s'.\n", path);
	} else {
		return;
	}
	free_rerere_id(rr_item);
	rr_item->util = NULL;
}
Esempio n. 6
0
File: rerere.c Progetto: emk/git
static int merge(const char *name, const char *path)
{
	int ret;
	mmfile_t cur, base, other;
	mmbuffer_t result = {NULL, 0};
	xpparam_t xpp = {XDF_NEED_MINIMAL};

	if (handle_file(path, NULL, rr_path(name, "thisimage")) < 0)
		return 1;

	if (read_mmfile(&cur, rr_path(name, "thisimage")) ||
			read_mmfile(&base, rr_path(name, "preimage")) ||
			read_mmfile(&other, rr_path(name, "postimage")))
		return 1;
	ret = xdl_merge(&base, &cur, "", &other, "",
			&xpp, XDL_MERGE_ZEALOUS, &result);
	if (!ret) {
		FILE *f = fopen(path, "w");
		if (!f)
			return error("Could not open %s: %s", path,
				     strerror(errno));
		if (fwrite(result.ptr, result.size, 1, f) != 1)
			error("Could not write %s: %s", path, strerror(errno));
		if (fclose(f))
			return error("Writing %s failed: %s", path,
				     strerror(errno));
	}

	free(cur.ptr);
	free(base.ptr);
	free(other.ptr);
	free(result.ptr);

	return ret;
}
Esempio n. 7
0
void dequeue (CIRCLE_handle * handle)
{
	char buf[CIRCLE_MAX_STRING_LEN];
	char * p;
	int depth;

	handle->dequeue(buf);
	switch(buf[0])
	{
		case 'D':
			depth = atoi(&buf[2]);
			p = strchr(&buf[2], ':');
			handle_dir(p+1, depth);
		break;

		case 'F':
			handle_file(&buf[2]);
		break;

		default:
			fprintf(stderr, "bad buffer %s\n", buf);
			return;
		break;
	}

	return;
}
Esempio n. 8
0
int main(int argc, char *argv[]) {

	printf("LG electronics digital tv firmware EPK2 extractor\n");
	printf("Version 0.7 by sirius (openlgtv.org.ru) 22.02.2011\n\n");

	char *current_dir = getcwd(NULL, 0);

	printf("current directory: %s\n\n", current_dir);

	if (argc < 2) {
		printf("\n");
		printf("usage: %s FILENAME\n", argv[0]);
		exit(1);
	}

	char *input_file = argv[1];

	printf("input file: %s\n\n", input_file);

	int exit_code =  handle_file(input_file, NULL);

	printf("finished\n");

	return exit_code;
}
Esempio n. 9
0
/* this is used with -r to recursively descend directories */
static void
handle_dir(char *dir)
{
	char *path_argv[2];
	FTS *fts;
	FTSENT *entry;

	path_argv[0] = dir;
	path_argv[1] = 0;
	fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
	if (fts == NULL) {
		// warn("couldn't fts_open %s", dir);
        fprintf(stderr, "gzip: couldn't fts_open %s: %s\n", dir, strerror(errno));
		return;
	}

	while ((entry = fts_read(fts))) {
		switch(entry->fts_info) {
		case FTS_D:
		case FTS_DP:
			continue;

		case FTS_DNR:
		case FTS_ERR:
		case FTS_NS:
			maybe_warn("%s", entry->fts_path);
			continue;
		case FTS_F:
			handle_file(entry->fts_path, entry->fts_statp);
		}
	}
	(void)fts_close(fts);
}
Esempio n. 10
0
/*
 * Find the conflict identified by "id"; the change between its
 * "preimage" (i.e. a previous contents with conflict markers) and its
 * "postimage" (i.e. the corresponding contents with conflicts
 * resolved) may apply cleanly to the contents stored in "path", i.e.
 * the conflict this time around.
 *
 * Returns 0 for successful replay of recorded resolution, or non-zero
 * for failure.
 */
static int merge(const struct rerere_id *id, const char *path)
{
	FILE *f;
	int ret;
	mmfile_t cur = {NULL, 0}, base = {NULL, 0}, other = {NULL, 0};
	mmbuffer_t result = {NULL, 0};

	/*
	 * Normalize the conflicts in path and write it out to
	 * "thisimage" temporary file.
	 */
	if (handle_file(path, NULL, rerere_path(id, "thisimage")) < 0) {
		ret = 1;
		goto out;
	}

	if (read_mmfile(&cur, rerere_path(id, "thisimage")) ||
	    read_mmfile(&base, rerere_path(id, "preimage")) ||
	    read_mmfile(&other, rerere_path(id, "postimage"))) {
		ret = 1;
		goto out;
	}

	/*
	 * A three-way merge. Note that this honors user-customizable
	 * low-level merge driver settings.
	 */
	ret = ll_merge(&result, path, &base, NULL, &cur, "", &other, "", NULL);
	if (ret)
		goto out;

	/*
	 * A successful replay of recorded resolution.
	 * Mark that "postimage" was used to help gc.
	 */
	if (utime(rerere_path(id, "postimage"), NULL) < 0)
		warning("failed utime() on %s: %s",
			rerere_path(id, "postimage"),
			strerror(errno));

	/* Update "path" with the resolution */
	f = fopen(path, "w");
	if (!f)
		return error("Could not open %s: %s", path,
			     strerror(errno));
	if (fwrite(result.ptr, result.size, 1, f) != 1)
		error("Could not write %s: %s", path, strerror(errno));
	if (fclose(f))
		return error("Writing %s failed: %s", path,
			     strerror(errno));

out:
	free(cur.ptr);
	free(base.ptr);
	free(other.ptr);
	free(result.ptr);

	return ret;
}
Esempio n. 11
0
/* do what is asked for, for the path name */
static void
handle_pathname(char *path)
{
	char *opath = path, *s = NULL;
	ssize_t len;
	int slen;
	struct stat sb;

	/* check for stdout/stdin */
	if (path[0] == '-' && path[1] == '\0') {
		if (dflag)
			handle_stdin();
		else
			handle_stdout();
		return;
	}

retry:
	if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
	    lstat(path, &sb) != 0)) {
		/* lets try <path>.gz if we're decompressing */
		if (dflag && s == NULL && errno == ENOENT) {
			len = strlen(path);
			slen = suffixes[0].ziplen;
			s = malloc(len + slen + 1);
			if (s == NULL)
				maybe_err("malloc");
			memcpy(s, path, len);
			memcpy(s + len, suffixes[0].zipped, slen + 1);
			path = s;
			goto retry;
		}
		maybe_warn("can't stat: %s", opath);
		goto out;
	}

	if (S_ISDIR(sb.st_mode)) {
#ifndef SMALL
		if (rflag)
			handle_dir(path);
		else
#endif
			maybe_warnx("%s is a directory", path);
		goto out;
	}

	if (S_ISREG(sb.st_mode))
		handle_file(path, &sb);
	else
		maybe_warnx("%s is not a regular file", path);

out:
	if (s)
		free(s);
}
Esempio n. 12
0
static void handle_current_files(void) {
    DIR * nsca_dir_s;

    /* Open the output directory */
    nsca_dir_s = opendir(NSCA_OUTPUT_DIR);
    if (nsca_dir_s == NULL) {
        return;
    }

    /* And browse any single file in it */
    for (;;) {
        pid_t worker;
        struct dirent * dir_entry;

        /* Get a file */
        dir_entry = readdir(nsca_dir_s);
        if (dir_entry == NULL) {
            break;
        }

        /* Fork, we don't care about the rest at that point */
        worker = fork();
        /* Let's assume, for now, that we were just lacking resources
         * at a point, and try to keep on the work...
         */
        soft_assert(worker != -1);

        if (worker == 0)
        {
            char complete_name[MAX_FILE_LENGTH];

            /* Build complete path */
            strncpy(complete_name, NSCA_OUTPUT_DIR, MAX_FILE_LENGTH);
            strncat(complete_name, dir_entry->d_name, MAX_FILE_LENGTH - sizeof(NSCA_OUTPUT_DIR));
            complete_name[MAX_FILE_LENGTH - 1] = '\0';

            /* And handle file */
            handle_file(complete_name);

            exit(EXIT_SUCCESS);
        }

        /* Get to the next file */
    }

    /* That's all! */
    (void)closedir(nsca_dir_s);

    return;
}
Esempio n. 13
0
File: rerere.c Progetto: Noffica/git
static int do_plain_rerere(struct repository *r,
			   struct string_list *rr, int fd)
{
	struct string_list conflict = STRING_LIST_INIT_DUP;
	struct string_list update = STRING_LIST_INIT_DUP;
	int i;

	find_conflict(r, &conflict);

	/*
	 * MERGE_RR records paths with conflicts immediately after
	 * merge failed.  Some of the conflicted paths might have been
	 * hand resolved in the working tree since then, but the
	 * initial run would catch all and register their preimages.
	 */
	for (i = 0; i < conflict.nr; i++) {
		struct rerere_id *id;
		unsigned char hash[GIT_MAX_RAWSZ];
		const char *path = conflict.items[i].string;
		int ret;

		/*
		 * Ask handle_file() to scan and assign a
		 * conflict ID.  No need to write anything out
		 * yet.
		 */
		ret = handle_file(r->index, path, hash, NULL);
		if (ret != 0 && string_list_has_string(rr, path)) {
			remove_variant(string_list_lookup(rr, path)->util);
			string_list_remove(rr, path, 1);
		}
		if (ret < 1)
			continue;

		id = new_rerere_id(hash);
		string_list_insert(rr, path)->util = id;

		/* Ensure that the directory exists. */
		mkdir_in_gitdir(rerere_path(id, NULL));
	}

	for (i = 0; i < rr->nr; i++)
		do_rerere_one_path(r->index, &rr->items[i], &update);

	if (update.nr)
		update_paths(r, &update);

	return write_rr(rr, fd);
}
Esempio n. 14
0
static void
check_path_for_file(FileView *view, const char *path, int handle)
{
	if(path[0] != '\0' && !is_dir(path))
	{
		const char *slash = strrchr(path, '/');
		if(slash == NULL)
			slash = path - 1;
		load_dir_list(view, !(cfg.vifm_info&VIFMINFO_SAVEDIRS));
		if(ensure_file_is_selected(view, slash + 1))
		{
			if(handle)
				handle_file(view, 0, 0);
		}
	}
}
Esempio n. 15
0
//**********************************************************************
//* Argument Handling / Checks the file isn't imaginary
int main(int argc, char*argv[])
{
	char *fname = NULL;
	FILE *fp;
	char bruteforce = 0;
	
	int ret = EXIT_SUCCESS;
	
	if (argc > 1 && !strncmp(argv[1], "--help", 6))
		printf ("\tfilename\tA binary file containing text encrypted with sac16\n\t"
				  "-bf\t\tBrute Force (Don't cheat)\n\t"
				  "-bfnrc\t\tBrute Force Without checking best key every round (use if -bf fails)");
	else if (argc < 2 || argc > 3)
		printf("usage: %s filename [-bf | -bfnrc]\n\t--help for more\n", argv[0]);
	else
	{
		fname = argv[1];
		if (argc == 3)
		{
			if (strcmp(argv[2], "-bfnrc") == 0)
				bruteforce = 1;
			else if (strcmp(argv[2], "-bf") == 0)
				bruteforce = 2;
			else
			{
				bruteforce = -1;
				printf("usage: %s filename plaintext [-bf]\n\t--help for more\n", argv[0]);
			}
		}
		if (bruteforce >= 0)
		{
			fp = fopen(fname, "r");
			if (fp != NULL)
			{
				ret = handle_file(fp, bruteforce, fname);
				fclose(fp);
			}
			else
			{
				ret = EXIT_FAILURE;
				perror("fopen");
			}
		}
	}
	return ret;
}
Esempio n. 16
0
void
follow_file(FileView *view)
{
	if(flist_custom_active(view))
	{
		/* Entry might be freed on navigation, so make sure name and origin will
		 * remain available for the call. */
		const dir_entry_t *const entry = &view->dir_entry[view->list_pos];
		char *const name = strdup(entry->name);
		char *const origin = strdup(entry->origin);
		navigate_to_file(view, origin, name, 0);
		free(origin);
		free(name);
		return;
	}

	handle_file(view, FHE_RUN, FHL_FOLLOW);
}
Esempio n. 17
0
/*
 * Find the conflict identified by "id"; the change between its
 * "preimage" (i.e. a previous contents with conflict markers) and its
 * "postimage" (i.e. the corresponding contents with conflicts
 * resolved) may apply cleanly to the contents stored in "path", i.e.
 * the conflict this time around.
 *
 * Returns 0 for successful replay of recorded resolution, or non-zero
 * for failure.
 */
static int merge(const struct rerere_id *id, const char *path)
{
	FILE *f;
	int ret;
	mmfile_t cur = {NULL, 0};
	mmbuffer_t result = {NULL, 0};

	/*
	 * Normalize the conflicts in path and write it out to
	 * "thisimage" temporary file.
	 */
	if ((handle_file(path, NULL, rerere_path(id, "thisimage")) < 0) ||
	    read_mmfile(&cur, rerere_path(id, "thisimage"))) {
		ret = 1;
		goto out;
	}

	ret = try_merge(id, path, &cur, &result);
	if (ret)
		goto out;

	/*
	 * A successful replay of recorded resolution.
	 * Mark that "postimage" was used to help gc.
	 */
	if (utime(rerere_path(id, "postimage"), NULL) < 0)
		warning_errno(_("failed utime() on '%s'"),
			      rerere_path(id, "postimage"));

	/* Update "path" with the resolution */
	f = fopen(path, "w");
	if (!f)
		return error_errno(_("could not open '%s'"), path);
	if (fwrite(result.ptr, result.size, 1, f) != 1)
		error_errno(_("could not write '%s'"), path);
	if (fclose(f))
		return error_errno(_("writing '%s' failed"), path);

out:
	free(cur.ptr);
	free(result.ptr);

	return ret;
}
bool xml_sax_handler_read_devices::open_file(QString file_input, QTreeWidgetItem *item_input, QList<QTreeWidgetItem *>    *all_row_input)
{
        file.setFileName(file_input);

	if (!handle_file())
		return FALSE;

        item = item_input;
        all_row = all_row_input;

        reader.setContentHandler(this);
        reader.setErrorHandler(this);
	xmlInputSource.setData(QString(""));	//All'inizio faccio il parse su una stringa vuota per poi fare parseContinue
	reader.parse(&xmlInputSource,TRUE);
	int datablock_lunghezza = datablock.size();
	int pos_start = 0;
	int pos_return = datablock.indexOf(QString("\n"));
        xml_wrong_attribute = FALSE;
	while (pos_return < datablock_lunghezza)
		{
                line = QString::fromUtf8(datablock.mid(pos_start, pos_return - pos_start));
                xmlInputSource.setData(line);
		reader.parseContinue();
		pos_start = pos_return + 1;
		pos_return = datablock.indexOf(QString("\n"), pos_start);
                if ((pos_return == -1))
			{
			//Leggo fino al fondo ed esco da ciclo while
			line = QString(datablock.mid(pos_start, datablock_lunghezza - pos_start));	
                        if (line.length() > 0)
                            {
                            xmlInputSource.setData(line);
                            reader.parseContinue();
                            }
			pos_return = datablock_lunghezza; //Mi serve per uscire dal ciclo while
                        }
		}	
		
	file.close();
	if (errorString() == "")
		return TRUE;
	else
                return FALSE;
}
Esempio n. 19
0
int
main (int argc, char *argv[])
{
  /* Make memory leak detection possible.  */
  mtrace ();

  /* We use no threads here which can interfere with handling a stream.  */
  (void) __fsetlocking (stdin, FSETLOCKING_BYCALLER);
  (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
  (void) __fsetlocking (stderr, FSETLOCKING_BYCALLER);

  /* Set locale.  */
  (void) setlocale (LC_ALL, "");

  /* Make sure the message catalog can be found.  */
  (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);

  /* Initialize the message catalog.  */
  (void) textdomain (PACKAGE_TARNAME);

  /* Parse and process arguments.  */
  int remaining;
  (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);

  /* Tell the library which version we are expecting.  */
  (void) elf_version (EV_CURRENT);

  /* There must at least be one more parameter specifying the archive.   */
  if (remaining == argc)
    {
      error (0, 0, gettext ("Archive name required"));
      argp_help (&argp, stderr, ARGP_HELP_SEE, "ranlib");
      exit (EXIT_FAILURE);
    }

  /* We accept the names of multiple archives.  */
  int status = 0;
  do
    status |= handle_file (argv[remaining]);
  while (++remaining < argc);

  return status;
}
Esempio n. 20
0
int
main(int argc, char **argv)
{
    if (argc == 1) {
        usage();
    } else {
        hasharray_init();
        while (--argc > 0) {
            if (handle_file(*(++argv)) != R_OK) {
                usage();
                die("error: invalid agruments\n");
            }
        }
        fputc('\r', stderr);    /* make sure the cursor is at the begining */
        hasharray_finddups(print_callback);
        hasharray_free();
    }
    return EXIT_SUCCESS;
}
Esempio n. 21
0
static int merge(const char *name, const char *path)
{
	int ret;
	mmfile_t cur = {NULL, 0}, base = {NULL, 0}, other = {NULL, 0};
	mmbuffer_t result = {NULL, 0};

	if (handle_file(path, NULL, rerere_path(name, "thisimage")) < 0)
		return 1;

	if (read_mmfile(&cur, rerere_path(name, "thisimage")) ||
			read_mmfile(&base, rerere_path(name, "preimage")) ||
			read_mmfile(&other, rerere_path(name, "postimage"))) {
		ret = 1;
		goto out;
	}
	ret = ll_merge(&result, path, &base, NULL, &cur, "", &other, "", NULL);
	if (!ret) {
		FILE *f;

		if (utime(rerere_path(name, "postimage"), NULL) < 0)
			warning("failed utime() on %s: %s",
					rerere_path(name, "postimage"),
					strerror(errno));
		f = fopen(path, "w");
		if (!f)
			return error("Could not open %s: %s", path,
				     strerror(errno));
		if (fwrite(result.ptr, result.size, 1, f) != 1)
			error("Could not write %s: %s", path, strerror(errno));
		if (fclose(f))
			return error("Writing %s failed: %s", path,
				     strerror(errno));
	}

out:
	free(cur.ptr);
	free(base.ptr);
	free(other.ptr);
	free(result.ptr);

	return ret;
}
Esempio n. 22
0
static void handle_new( LWControl *ectl, void *edata )
{
   static char
      node[ 256 ] = { 0 },
      path[ 256 ] = { 0 };
   LWDirInfoFunc *dif;
   const char *dir;

   if ( !filename[ 0 ] ) {
      if ( dif = panf->globalFun( LWDIRINFOFUNC_GLOBAL, GFUSE_TRANSIENT )) {
         dir = dif( "Content" );
         if ( dir )
            strcpy( path, dir );
      }
   }

   if ( 0 > filereq( "View", node, path, filename, sizeof( filename )))
      return;

   SET_STR( ctl[ 1 ], filename, sizeof( filename ));
   handle_file( ctl[ 1 ], NULL );
}
Esempio n. 23
0
int handle_file(const char *file, char *destination) {
	if (check_lzo_header(file)) {
		if (destination == NULL) {
			destination = "./lzounpack.out";
		}
		printf("extracting lzo compressed file to: %s\n", destination);
		if (lzo_unpack(file, destination) == 0) {
			handle_file(destination, NULL);
			return EXIT_SUCCESS;
		}
	} else if (is_squashfs(file)) {
		if (destination == NULL) {
			destination = "./unsquashfs.out";
		}
		printf("unsquashfs compressed file system to: %s\n", destination);
		rmrf(destination);
		unsquashfs(file, destination);
		return EXIT_SUCCESS;
	} else if (is_cramfs_image(file)) {
		if (destination == NULL) {
			destination = "./uncramfs.out";
		}
		printf("uncramfs compressed file system to: %s\n", destination);
		rmrf(destination);
		uncramfs(destination, file);
		return EXIT_SUCCESS;
	} else if (is_epk2_file(file)) {
		printf("extracting firmware file...\n\n");
		extract_epk2_file(file);
		return EXIT_SUCCESS;
	}

	printf("\n");
	printf("unsupported file format:\n", file);
	exit(EXIT_FAILURE);
}
Esempio n. 24
0
static int do_plain_rerere(struct string_list *rr, int fd)
{
	struct string_list conflict = STRING_LIST_INIT_DUP;
	struct string_list update = STRING_LIST_INIT_DUP;
	int i;

	find_conflict(&conflict);

	/*
	 * MERGE_RR records paths with conflicts immediately after
	 * merge failed.  Some of the conflicted paths might have been
	 * hand resolved in the working tree since then, but the
	 * initial run would catch all and register their preimages.
	 */
	for (i = 0; i < conflict.nr; i++) {
		struct rerere_id *id;
		unsigned char sha1[20];
		const char *path = conflict.items[i].string;
		int ret;

		if (string_list_has_string(rr, path))
			continue;

		/*
		 * Ask handle_file() to scan and assign a
		 * conflict ID.  No need to write anything out
		 * yet.
		 */
		ret = handle_file(path, sha1, NULL);
		if (ret < 1)
			continue;

		id = new_rerere_id(sha1);
		string_list_insert(rr, path)->util = id;

		/*
		 * If the directory does not exist, create
		 * it.  mkdir_in_gitdir() will fail with
		 * EEXIST if there already is one.
		 *
		 * NEEDSWORK: make sure "gc" does not remove
		 * preimage without removing the directory.
		 */
		if (mkdir_in_gitdir(rerere_path(id, NULL)))
			continue;

		/*
		 * We are the first to encounter this
		 * conflict.  Ask handle_file() to write the
		 * normalized contents to the "preimage" file.
		 */
		handle_file(path, NULL, rerere_path(id, "preimage"));
		fprintf(stderr, "Recorded preimage for '%s'\n", path);
	}

	for (i = 0; i < rr->nr; i++)
		do_rerere_one_path(&rr->items[i], &update);

	if (update.nr)
		update_paths(&update);

	return write_rr(rr, fd);
}
Esempio n. 25
0
void handle_stlv_packet(unsigned char* packet)
{
    stlv_packet pack = packet;
    char type_buf[MAX_ELEMENT_TYPE_BUFSIZE];

    element_handle handle = get_first_element(pack);
    while (IS_VALID_STLV_HANDLE(handle))
    {
        int type_len = get_element_type(pack, handle, type_buf, sizeof(type_buf));
        log_info("Read Element: %x\n", type_buf[0]);
        switch (type_buf[0])
        {
        case ELEMENT_TYPE_ECHO:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                unsigned char* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                log_info("echo: ");
                print_stlv_string(data, data_len);
                log_info("\n");
                handle_echo(data, data_len);
            }
            break;

        case ELEMENT_TYPE_CLOCK:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                unsigned char* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                log_info("clock: %d/%d/%d %d:%d:%d\n",
                    (int)data[0], (int)data[1], (int)data[2], (int)data[3], (int)data[4], (int)data[5]);
                handle_clock(data[0], data[1], data[2], data[3], data[4], data[5]);
                if (data_len >= 8)
                    handle_phone_info(data[6], data[7]);
            }
            break;

        case ELEMENT_TYPE_MESSAGE:
            if (type_len == 2)
            {
                switch (type_buf[1])
                {
                case ELEMENT_TYPE_MESSAGE_SMS:
                    log_info("notification(SMS):\n");
                    break;
                case ELEMENT_TYPE_MESSAGE_FB:
                    log_info("notification(Facebook):\n");
                    break;
                case ELEMENT_TYPE_MESSAGE_TW:
                    log_info("notification(Twitter):\n");
                    break;
                default:
                    break;
                }
                handle_msg_element(type_buf[1], pack, handle);
            }
            break;

        case ELEMENT_TYPE_FILE:
            handle_file(pack, handle);
            break;

        case ELEMENT_TYPE_GET_FILE:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                STLV_BUF_BEGIN_TEMP_STRING(data, data_len);
                handle_get_file((char*)data);
                STLV_BUF_END_TEMP_STRING(data, data_len);
            }
            break;

        case ELEMENT_TYPE_ACTIVITY_DATA:
            handle_get_activity();
            break;

        case ELEMENT_TYPE_LIST_FILES:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                STLV_BUF_BEGIN_TEMP_STRING(data, data_len);
                handle_list_file((char*)data);
                STLV_BUF_END_TEMP_STRING(data, data_len);
            }
            break;

        case ELEMENT_TYPE_REMOVE_FILE:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                STLV_BUF_BEGIN_TEMP_STRING(data, data_len);
                uint8_t file_name_pos = 0;
                for (uint8_t i = 0; i < data_len; ++i)
                {
                    if (data[i] == ';')
                        data[i] = '\0';

                    if (data[i] == '\0')
                    {
                        handle_remove_file((char*)(&data[file_name_pos]));
                        file_name_pos = i + 1;
                    }
                }
                STLV_BUF_END_TEMP_STRING(data, data_len);
            }
           break;

#if 0
        case ELEMENT_TYPE_SPORT_HEARTBEAT:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                STLV_BUF_BEGIN_TEMP_STRING(data, data_len);
                handle_sports_heartbeat((char*)data);
                STLV_BUF_END_TEMP_STRING(data, data_len);
            }
            break;
        case ELEMENT_TYPE_SPORTS_DATA:
            handle_get_sports_data();
            break;
#endif
        case ELEMENT_TYPE_SPORTS_GRID:
            log_info("Get Sports Grid Request\n");
            handle_get_sports_grid();
            break;

        case ELEMENT_TYPE_ALARM:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                if (data_len != sizeof(alarm_conf_t))
                {
                    log_info("Alarm element decode failed: length mismatch (%d/%d)", data_len, sizeof(alarm_conf_t));
                }
                else
                {
                    handle_alarm((alarm_conf_t*)data);
                }
            }
            break;

        case ELEMENT_TYPE_SN:
            handle_get_device_id();
            break;

        case ELEMENT_TYPE_ACTIVITY:
            handle_gps_data(pack, handle);
            break;

        case ELEMENT_TYPE_GESTURE_CONTROL:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                if (data_len != 5)
                {
                    log_info("gesture control decode failed: length mismatch (%d/1)", data_len);
                }
                else
                {
                    handle_gesture_control(*data, data + 1);
                }
            }
            break;

        case ELEMENT_TYPE_WATCHCONFIG:
            {
                int data_len = get_element_data_size(pack, handle, type_buf, type_len);
                uint8_t* data = get_element_data_buffer(pack, handle, type_buf, type_len);
                log_info("Set Watch UI Config %d/%d", data_len, (int)sizeof(ui_config));
                //if (data_len >= (int)sizeof(ui_config))
                    handle_set_watch_config((ui_config*)(data + 1));
            }
            break;

        case ELEMENT_TYPE_UNLOCK_WATCH:
            handle_unlock_watch();
            break;

        case ELEMENT_TYPE_DAILY_ACTIVITY:
            handle_daily_activity();
            break;

        }

        handle = get_next_element(pack, handle);

    }
}
Esempio n. 26
0
void
open_file(FileView *view, FileHandleExec exec)
{
	handle_file(view, exec, FHL_NO_FOLLOW);
}
Esempio n. 27
0
/*
 * The path indicated by rr_item may still have conflict for which we
 * have a recorded resolution, in which case replay it and optionally
 * update it.  Or it may have been resolved by the user and we may
 * only have the preimage for that conflict, in which case the result
 * needs to be recorded as a resolution in a postimage file.
 */
static void do_rerere_one_path(struct string_list_item *rr_item,
			       struct string_list *update)
{
	const char *path = rr_item->string;
	struct rerere_id *id = rr_item->util;
	struct rerere_dir *rr_dir = id->collection;
	int variant;

	variant = id->variant;

	/* Has the user resolved it already? */
	if (variant >= 0) {
		if (!handle_file(path, NULL, NULL)) {
			copy_file(rerere_path(id, "postimage"), path, 0666);
			id->collection->status[variant] |= RR_HAS_POSTIMAGE;
			fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
			free_rerere_id(rr_item);
			rr_item->util = NULL;
			return;
		}
		/*
		 * There may be other variants that can cleanly
		 * replay.  Try them and update the variant number for
		 * this one.
		 */
	}

	/* Does any existing resolution apply cleanly? */
	for (variant = 0; variant < rr_dir->status_nr; variant++) {
		const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
		struct rerere_id vid = *id;

		if ((rr_dir->status[variant] & both) != both)
			continue;

		vid.variant = variant;
		if (merge(&vid, path))
			continue; /* failed to replay */

		/*
		 * If there already is a different variant that applies
		 * cleanly, there is no point maintaining our own variant.
		 */
		if (0 <= id->variant && id->variant != variant)
			remove_variant(id);

		if (rerere_autoupdate)
			string_list_insert(update, path);
		else
			fprintf_ln(stderr,
				   _("Resolved '%s' using previous resolution."),
				   path);
		free_rerere_id(rr_item);
		rr_item->util = NULL;
		return;
	}

	/* None of the existing one applies; we need a new variant */
	assign_variant(id);

	variant = id->variant;
	handle_file(path, NULL, rerere_path(id, "preimage"));
	if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
		const char *path = rerere_path(id, "postimage");
		if (unlink(path))
			die_errno(_("cannot unlink stray '%s'"), path);
		id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
	}
	id->collection->status[variant] |= RR_HAS_PREIMAGE;
	fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
}
Esempio n. 28
0
static int do_plain_rerere(struct string_list *rr, int fd)
{
	struct string_list conflict = STRING_LIST_INIT_DUP;
	struct string_list update = STRING_LIST_INIT_DUP;
	int i;

	find_conflict(&conflict);

	/*
	 * MERGE_RR records paths with conflicts immediately after merge
	 * failed.  Some of the conflicted paths might have been hand resolved
	 * in the working tree since then, but the initial run would catch all
	 * and register their preimages.
	 */

	for (i = 0; i < conflict.nr; i++) {
		const char *path = conflict.items[i].string;
		if (!string_list_has_string(rr, path)) {
			unsigned char sha1[20];
			char *hex;
			int ret;
			ret = handle_file(path, sha1, NULL);
			if (ret < 1)
				continue;
			hex = xstrdup(sha1_to_hex(sha1));
			string_list_insert(rr, path)->util = hex;
			if (mkdir_in_gitdir(git_path("rr-cache/%s", hex)))
				continue;
			handle_file(path, NULL, rerere_path(hex, "preimage"));
			fprintf(stderr, "Recorded preimage for '%s'\n", path);
		}
	}

	/*
	 * Now some of the paths that had conflicts earlier might have been
	 * hand resolved.  Others may be similar to a conflict already that
	 * was resolved before.
	 */

	for (i = 0; i < rr->nr; i++) {
		int ret;
		const char *path = rr->items[i].string;
		const char *name = (const char *)rr->items[i].util;

		if (has_rerere_resolution(name)) {
			if (!merge(name, path)) {
				const char *msg;
				if (rerere_autoupdate) {
					string_list_insert(&update, path);
					msg = "Staged '%s' using previous resolution.\n";
				} else
					msg = "Resolved '%s' using previous resolution.\n";
				fprintf(stderr, msg, path);
				goto mark_resolved;
			}
		}

		/* Let's see if we have resolved it. */
		ret = handle_file(path, NULL, NULL);
		if (ret)
			continue;

		fprintf(stderr, "Recorded resolution for '%s'.\n", path);
		copy_file(rerere_path(name, "postimage"), path, 0666);
	mark_resolved:
		rr->items[i].util = NULL;
	}

	if (update.nr)
		update_paths(&update);

	return write_rr(rr, fd);
}
Esempio n. 29
0
/* Handle file management */
void LogCollectorStart()
{
    int i = 0, r = 0;
    int max_file = 0;
    int f_check = 0;
    time_t curr_time = 0;
    char keepalive[1024];

    /* To check for inode changes */
    struct stat tmp_stat;

#ifndef WIN32
    int int_error = 0;
    struct timeval fp_timeout;
#else

    /* Check if we are on Windows Vista */
    checkVista();

    /* Read vista descriptions */
    if (isVista) {
        win_read_vista_sec();
    }
#endif

    debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0);

    /* Initialize each file and structure */
    for (i = 0;; i++) {
        if (logff[i].file == NULL) {
            break;
        }

        /* Remove duplicate entries */
        for (r = 0; r < i; r++) {
            if (logff[r].file && strcmp(logff[i].file, logff[r].file) == 0) {
                merror("%s: WARN: Duplicated log file given: '%s'.",
                       ARGV0, logff[i].file);
                logff[i].file = NULL;
                logff[i].command = NULL;
                logff[i].fp = NULL;

                break;
            }
        }

        if (logff[i].file == NULL) {
            /* Do nothing, duplicated entry */
        }

        else if (strcmp(logff[i].logformat, "eventlog") == 0) {
#ifdef WIN32

            verbose(READING_EVTLOG, ARGV0, logff[i].file);
            win_startel(logff[i].file);

#endif
            logff[i].file = NULL;
            logff[i].command = NULL;
            logff[i].fp = NULL;
        }

        else if (strcmp(logff[i].logformat, "eventchannel") == 0) {
#ifdef WIN32

#ifdef EVENTCHANNEL_SUPPORT
            verbose(READING_EVTLOG, ARGV0, logff[i].file);
            win_start_event_channel(logff[i].file, logff[i].future, logff[i].query);
#else
            merror("%s: WARN: eventchannel not available on this version of OSSEC", ARGV0);
#endif

#endif

            logff[i].file = NULL;
            logff[i].command = NULL;
            logff[i].fp = NULL;
        }

        else if (strcmp(logff[i].logformat, "command") == 0) {
            logff[i].file = NULL;
            logff[i].fp = NULL;
            logff[i].size = 0;

            if (logff[i].command) {
                logff[i].read = read_command;

                verbose("%s: INFO: Monitoring output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command);

                if (!logff[i].alias) {
                    os_strdup(logff[i].command, logff[i].alias);
                }
            } else {
                merror("%s: ERROR: Missing command argument. Ignoring it.",
                       ARGV0);
            }
        } else if (strcmp(logff[i].logformat, "full_command") == 0) {
            logff[i].file = NULL;
            logff[i].fp = NULL;
            logff[i].size = 0;
            if (logff[i].command) {
                logff[i].read = read_fullcommand;

                verbose("%s: INFO: Monitoring full output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command);

                if (!logff[i].alias) {
                    os_strdup(logff[i].command, logff[i].alias);
                }
            } else {
                merror("%s: ERROR: Missing command argument. Ignoring it.",
                       ARGV0);
            }
        }

        else {
            logff[i].command = NULL;

            /* Initialize the files */
            if (logff[i].ffile) {
                /* Day must be zero for all files to be initialized */
                _cday = 0;
                if (update_fname(i)) {
                    handle_file(i, 1, 1);
                } else {
                    ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile);
                }

            } else {
                handle_file(i, 1, 1);
            }

            verbose(READING_FILE, ARGV0, logff[i].file);

            /* Get the log type */
            if (strcmp("snort-full", logff[i].logformat) == 0) {
                logff[i].read = read_snortfull;
            }
#ifndef WIN32
            if (strcmp("ossecalert", logff[i].logformat) == 0) {
                logff[i].read = read_ossecalert;
            }
#endif
            else if (strcmp("nmapg", logff[i].logformat) == 0) {
                logff[i].read = read_nmapg;
            } else if (strcmp("mysql_log", logff[i].logformat) == 0) {
                logff[i].read = read_mysql_log;
            } else if (strcmp("mssql_log", logff[i].logformat) == 0) {
                logff[i].read = read_mssql_log;
            } else if (strcmp("postgresql_log", logff[i].logformat) == 0) {
                logff[i].read = read_postgresql_log;
            } else if (strcmp("djb-multilog", logff[i].logformat) == 0) {
                if (!init_djbmultilog(i)) {
                    merror(INV_MULTILOG, ARGV0, logff[i].file);
                    if (logff[i].fp) {
                        fclose(logff[i].fp);
                        logff[i].fp = NULL;
                    }
                    logff[i].file = NULL;
                }
                logff[i].read = read_djbmultilog;
            } else if (logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9') {
                logff[i].read = read_multiline;
            } else {
                logff[i].read = read_syslog;
            }

            /* More tweaks for Windows. For some reason IIS places
             * some weird characters at the end of the files and getc
             * always returns 0 (even after clearerr).
             */
#ifdef WIN32
            if (logff[i].fp) {
                logff[i].read(i, &r, 1);
            }
#endif
        }

        if (logff[i].alias) {
            int ii = 0;
            while (logff[i].alias[ii] != '\0') {
                if (logff[i].alias[ii] == ':') {
                    logff[i].alias[ii] = '\\';
                }
                ii++;
            }
        }
    }

    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, (int)getpid());

    max_file = i - 1;

    /* Cannot be zero */
    if (max_file < 0) {
        max_file = 0;
    }

    /* Daemon loop */
    while (1) {
#ifndef WIN32
        fp_timeout.tv_sec = loop_timeout;
        fp_timeout.tv_usec = 0;

        /* Wait for the select timeout */
        if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) {
            merror(SELECT_ERROR, ARGV0, errno, strerror(errno));
            int_error++;

            if (int_error >= 5) {
                ErrorExit(SYSTEM_ERROR, ARGV0);
            }
            continue;
        }
#else

        /* Windows doesn't like select that way */
        sleep(loop_timeout + 2);

        /* Check for messages in the event viewer */
        win_readel();
#endif

        f_check++;

        /* Check which file is available */
        for (i = 0; i <= max_file; i++) {
            if (!logff[i].fp) {
                /* Run the command */
                if (logff[i].command && (f_check % 2)) {
                    curr_time = time(0);
                    if ((curr_time - logff[i].size) >= logff[i].ign) {
                        logff[i].size = curr_time;
                        logff[i].read(i, &r, 0);
                    }
                }
                continue;
            }

            /* Windows with IIS logs is very strange.
             * For some reason it always returns 0 (not EOF)
             * the fgetc. To solve this problem, we always
             * pass it to the function pointer directly.
             */
#ifndef WIN32
            /* We check for the end of file. If is returns EOF,
             * we don't attempt to read it.
             */
            if ((r = fgetc(logff[i].fp)) == EOF) {
                clearerr(logff[i].fp);
                continue;
            }

            /* If it is not EOF, we need to return the read character */
            ungetc(r, logff[i].fp);
#endif

            /* Finally, send to the function pointer to read it */
            logff[i].read(i, &r, 0);

            /* Check for error */
            if (!ferror(logff[i].fp)) {
                /* Clear EOF */
                clearerr(logff[i].fp);

                /* Parsing error */
                if (r != 0) {
                    logff[i].ign++;
                }
            }
            /* If ferror is set */
            else {
                merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
#ifndef WIN32
                if (fseek(logff[i].fp, 0, SEEK_END) < 0)
#else
                if (1)
#endif
                {

#ifndef WIN32
                    merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
#endif

                    /* Close the file */
                    if (logff[i].fp) {
                        fclose(logff[i].fp);
#ifdef WIN32
                        CloseHandle(logff[i].h);
#endif
                    }
                    logff[i].fp = NULL;


                    /* Try to open it again */
                    if (handle_file(i, 1, 1) != 0) {
                        logff[i].ign++;
                        continue;
                    }
#ifdef WIN32
                    logff[i].read(i, &r, 1);
#endif
                }
                /* Increase the error count  */
                logff[i].ign++;
                clearerr(logff[i].fp);
            }
        }

        /* Only check below if check > VCHECK_FILES */
        if (f_check <= VCHECK_FILES) {
            continue;
        }

        /* Send keep alive message */
        rand_keepalive_str(keepalive, 700);
        SendMSG(logr_queue, keepalive, "ossec-keepalive", LOCALFILE_MQ);

        /* Zero f_check */
        f_check = 0;

        /* Check if any file has been renamed/removed */
        for (i = 0; i <= max_file; i++) {
            /* These are the windows logs or ignored files */
            if (!logff[i].file) {
                continue;
            }

            /* Files with date -- check for day change */
            if (logff[i].ffile) {
                if (update_fname(i)) {
                    if (logff[i].fp) {
                        fclose(logff[i].fp);
#ifdef WIN32
                        CloseHandle(logff[i].h);
#endif
                    }
                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }

                /* Variable file name */
                else if (!logff[i].fp) {
                    handle_file(i, 0, 0);
                    continue;
                }
            }

            /* Check for file change -- if the file is open already */
            if (logff[i].fp) {
#ifndef WIN32

		/* To help detect a file rollover, temporarily open the file a second time.
 		 * Previously the fstat would work on "cached" file data, but this should 
 		 * ensure it's fresh when hardlinks are used (like alerts.log).
 		 */
		FILE *tf;
		tf = fopen(logff[i].file, "r");
		if(tf == NULL) {
			merror(FOPEN_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
		}

                if ((fstat(fileno(tf), &tmp_stat)) == -1) {
                    fclose(logff[i].fp);
                    logff[i].fp = NULL;

                    merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno));
                }
		if(fclose(tf) == EOF) {
			merror("Closing the temporary file %s did not work (%d): %s", logff[i].file, errno, strerror(errno));
		}
#else
                BY_HANDLE_FILE_INFORMATION lpFileInformation;
                HANDLE h1;

                h1 = CreateFile(logff[i].file, GENERIC_READ,
                                FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
                if (h1 == INVALID_HANDLE_VALUE) {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);
                } else if (GetFileInformationByHandle(h1, &lpFileInformation) == 0) {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);;
                }
#endif

#ifdef WIN32
                else if (logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh))
#else
                else if (logff[i].fd != tmp_stat.st_ino)
#endif
                {
                    char msg_alert[512 + 1];

                    snprintf(msg_alert, 512, "ossec: File rotated (inode "
                             "changed): '%s'.",
                             logff[i].file);

                    /* Send message about log rotated */
                    SendMSG(logr_queue, msg_alert,
                            "ossec-logcollector", LOCALFILE_MQ);

                    debug1("%s: DEBUG: File inode changed. %s",
                           ARGV0, logff[i].file);

                    fclose(logff[i].fp);

#ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
#endif

                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }
#ifdef WIN32
                else if (logff[i].size > (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow))
#else
                else if (logff[i].size > tmp_stat.st_size)
#endif
                {
                    char msg_alert[512 + 1];

                    snprintf(msg_alert, 512, "ossec: File size reduced "
                             "(inode remained): '%s'.",
                             logff[i].file);

                    /* Send message about log rotated */
                    SendMSG(logr_queue, msg_alert,
                            "ossec-logcollector", LOCALFILE_MQ);

                    debug1("%s: DEBUG: File size reduced. %s",
                           ARGV0, logff[i].file);


                    /* Fix size so we don't alert more than once */
                    logff[i].size = tmp_stat.st_size;

                    /* Get new file */
                    fclose(logff[i].fp);

#ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
#endif

                    logff[i].fp = NULL;
                    handle_file(i, 1, 1);
                }
#ifdef WIN32
                else {
                    CloseHandle(h1);
                }
#endif
            }


            /* Too many errors for the file */
            if (logff[i].ign > open_file_attempts) {
                /* 999 Maximum ignore */
                if (logff[i].ign == 999) {
                    continue;
                }

                merror(LOGC_FILE_ERROR, ARGV0, logff[i].file);
                if (logff[i].fp) {
                    fclose(logff[i].fp);
#ifdef WIN32
                    CloseHandle(logff[i].h);
#endif
                }

                logff[i].fp = NULL;

                /* If the file has a variable date, ignore it for today only */
                if (!logff[i].ffile) {
                    /* Variable log files should always be attempted
                     * to be open...
                     */
                    //logff[i].file = NULL;
                }
                logff[i].ign = 999;
                continue;
            }

            /* File not open */
            if (!logff[i].fp) {
                if (logff[i].ign >= 999) {
                    continue;
                } else {
                    /* Try for a few times to open the file */
                    if (handle_file(i, 1, 1) < 0) {
                        logff[i].ign++;
                    }
                    continue;
                }
            }
        }
    }
Esempio n. 30
0
int main(int argc, char *argv[]) {
	duk_context *ctx = NULL;
	int retval = 0;
	int have_files = 0;
	int have_eval = 0;
	int interactive = 0;
	int memlimit_high = 1;
	int alloc_provider = ALLOC_DEFAULT;
	int i;

#ifdef DUK_CMDLINE_AJSHEAP
	alloc_provider = ALLOC_AJSHEAP;
#endif

	/*
	 *  Signal handling setup
	 */

#ifndef NO_SIGNAL
	set_sigint_handler();

	/* This is useful at the global level; libraries should avoid SIGPIPE though */
	/*signal(SIGPIPE, SIG_IGN);*/
#endif

	/*
	 *  Parse options
	 */

	for (i = 1; i < argc; i++) {
		char *arg = argv[i];
		if (!arg) {
			goto usage;
		}
		if (strcmp(arg, "--restrict-memory") == 0) {
			memlimit_high = 0;
		} else if (strcmp(arg, "-i") == 0) {
			interactive = 1;
		} else if (strcmp(arg, "-e") == 0) {
			have_eval = 1;
			if (i == argc - 1) {
				goto usage;
			}
			i++;  /* skip code */
		} else if (strcmp(arg, "--alloc-default") == 0) {
			alloc_provider = ALLOC_DEFAULT;
		} else if (strcmp(arg, "--alloc-logging") == 0) {
			alloc_provider = ALLOC_LOGGING;
		} else if (strcmp(arg, "--alloc-torture") == 0) {
			alloc_provider = ALLOC_TORTURE;
		} else if (strcmp(arg, "--alloc-hybrid") == 0) {
			alloc_provider = ALLOC_HYBRID;
		} else if (strcmp(arg, "--alloc-ajsheap") == 0) {
			alloc_provider = ALLOC_AJSHEAP;
		} else if (strlen(arg) >= 1 && arg[0] == '-') {
			goto usage;
		} else {
			have_files = 1;
		}
	}
	if (!have_files && !have_eval) {
		interactive = 1;
	}

	/*
	 *  Memory limit
	 */

#ifndef NO_RLIMIT
	set_resource_limits(memlimit_high ? MEM_LIMIT_HIGH : MEM_LIMIT_NORMAL);
#else
	if (memlimit_high == 0) {
		fprintf(stderr, "Warning: option --restrict-memory ignored, no rlimit support\n");
		fflush(stderr);
	}
#endif

	/*
	 *  Create context
	 */

	ctx = NULL;
	if (!ctx && alloc_provider == ALLOC_LOGGING) {
#ifdef DUK_CMDLINE_ALLOC_LOGGING
		ctx = duk_create_heap(duk_alloc_logging,
		                      duk_realloc_logging,
		                      duk_free_logging,
		                      NULL,
		                      NULL);
#else
		fprintf(stderr, "Warning: option --alloc-logging ignored, no logging allocator support\n");
		fflush(stderr);
#endif
	}
	if (!ctx && alloc_provider == ALLOC_TORTURE) {
#ifdef DUK_CMDLINE_ALLOC_TORTURE
		ctx = duk_create_heap(duk_alloc_torture,
		                      duk_realloc_torture,
		                      duk_free_torture,
		                      NULL,
		                      NULL);
#else
		fprintf(stderr, "Warning: option --alloc-torture ignored, no torture allocator support\n");
		fflush(stderr);
#endif
	}
	if (!ctx && alloc_provider == ALLOC_HYBRID) {
#ifdef DUK_CMDLINE_ALLOC_HYBRID
		void *udata = duk_alloc_hybrid_init();
		if (!udata) {
			fprintf(stderr, "Failed to init hybrid allocator\n");
			fflush(stderr);
		} else {
			ctx = duk_create_heap(duk_alloc_hybrid,
			                      duk_realloc_hybrid,
			                      duk_free_hybrid,
			                      udata,
			                      NULL);
		}
#else
		fprintf(stderr, "Warning: option --alloc-hybrid ignored, no hybrid allocator support\n");
		fflush(stderr);
#endif
	}
	if (!ctx && alloc_provider == ALLOC_AJSHEAP) {
#ifdef DUK_CMDLINE_AJSHEAP
		ajsheap_init();

		ctx = duk_create_heap(AJS_Alloc,
		                      AJS_Realloc,
		                      AJS_Free,
		                      (void *) &ctx,  /* alloc_udata */
		                      NULL);          /* fatal_handler */
#else
		fprintf(stderr, "Warning: option --alloc-ajsheap ignored, no ajsheap allocator support\n");
		fflush(stderr);
#endif
	}
	if (!ctx && alloc_provider == ALLOC_DEFAULT) {
		ctx = duk_create_heap_default();
	}

	if (!ctx) {
		fprintf(stderr, "Failed to create Duktape heap\n");
		fflush(stderr);
		exit(-1);
	}

#ifdef DUK_CMDLINE_AJSHEAP
	if (alloc_provider == ALLOC_AJSHEAP) {
		fprintf(stdout, "Pool dump after heap creation\n");
		fflush(stdout);
		AJS_HeapDump();
		fflush(stdout);
	}
#endif

#ifdef DUK_CMDLINE_AJSHEAP
	if (alloc_provider == ALLOC_AJSHEAP) {
		ajsheap_register(ctx);
	}
#endif

	/*
	 *  Execute any argument file(s)
	 */

	for (i = 1; i < argc; i++) {
		char *arg = argv[i];
		if (!arg) {
			continue;
		} else if (strlen(arg) == 2 && strcmp(arg, "-e") == 0) {
			/* Here we know the eval arg exists but check anyway */
			if (i == argc - 1) {
				retval = 1;
				goto cleanup;
			}
			if (handle_eval(ctx, argv[i + 1]) != 0) {
				retval = 1;
				goto cleanup;
			}
			i++;  /* skip code */
			continue;
		} else if (strlen(arg) >= 1 && arg[0] == '-') {
			continue;
		}

		if (handle_file(ctx, arg) != 0) {
			retval = 1;
			goto cleanup;
		}
	}

	/*
	 *  Enter interactive mode if options indicate it
	 */

	if (interactive) {
		if (handle_interactive(ctx) != 0) {
			retval = 1;
			goto cleanup;
		}
	}

	/*
	 *  Cleanup and exit
	 */

 cleanup:
	if (interactive) {
		fprintf(stderr, "Cleaning up...\n");
		fflush(stderr);
	}

#ifdef DUK_CMDLINE_AJSHEAP
	if (alloc_provider == ALLOC_AJSHEAP) {
		fprintf(stdout, "Pool dump before duk_destroy_heap(), before forced gc\n");
		fflush(stdout);
		AJS_HeapDump();
		fflush(stdout);

		duk_gc(ctx, 0);

		fprintf(stdout, "Pool dump before duk_destroy_heap(), after forced gc\n");
		fflush(stdout);
		AJS_HeapDump();
		fflush(stdout);
	}
#endif

	if (ctx) {
		duk_destroy_heap(ctx);
	}

#ifdef DUK_CMDLINE_AJSHEAP
	if (alloc_provider == ALLOC_AJSHEAP) {
		fprintf(stdout, "Pool dump after duk_destroy_heap() (should have zero allocs)\n");
		fflush(stdout);
		AJS_HeapDump();
		fflush(stdout);
	}
#endif

	return retval;

	/*
	 *  Usage
	 */

 usage:
	fprintf(stderr, "Usage: duk [options] [<filenames>]\n"
	                "\n"
	                "   -i                 enter interactive mode after executing argument file(s) / eval code\n"
	                "   -e CODE            evaluate code\n"
	                "   --restrict-memory  use lower memory limit (used by test runner)\n"
	                "   --alloc-default    use Duktape default allocator\n"
#ifdef DUK_CMDLINE_ALLOC_LOGGING
	                "   --alloc-logging    use logging allocator (writes to /tmp)\n"
#endif
#ifdef DUK_CMDLINE_ALLOC_TORTURE
	                "   --alloc-torture    use torture allocator\n"
#endif
#ifdef DUK_CMDLINE_ALLOC_HYBRID
	                "   --alloc-hybrid     use hybrid allocator\n"
#endif
#ifdef DUK_CMDLINE_AJSHEAP
	                "   --alloc-ajsheap    use ajsheap allocator (enabled by default with 'ajduk')\n"
#endif
	                "\n"
	                "If <filename> is omitted, interactive mode is started automatically.\n");
	fflush(stderr);
	exit(1);
}