Exemplo n.º 1
0
bool array_deserialize(const char *src_file, void *dst_data, const size_t elem_size, const size_t elem_count) 
{
	if (! src_file || ! dst_data || elem_size == 0 || elem_count == 0)
    {
        return false;
    }
    
    FILE* file = fopen(src_file, "r");
    
    if (! file || ! is_valid_filename(src_file))
    {
        //file didn't open properly
        return false;
    }
    
    //get number of elements read
    int bRead = fread(dst_data, elem_size, elem_count, file);
    
    //check to see they were all read
    if (bRead != elem_count)
    {
        return false; //not all the elements were read!
    }
    
    //else, all the bytes were read....
    return true;
    
    
	return true;
}
Exemplo n.º 2
0
bool array_serialize(const void *src_data, const char *dst_file, const size_t elem_size, const size_t elem_count) 
{
    if (! src_data || ! dst_file || elem_size == 0 || elem_count == 0)
    {
        return false;
    }
    
    FILE* file = fopen(dst_file, "w");
    
    if (! file || ! is_valid_filename(dst_file))
    {
        //file couldn't open properly
        return false;
    }
    
    //get the number of elements written
    int bWritten = fwrite(src_data, elem_size, elem_count, file);
    
    //cleanup
    fclose(file);
    
    //check to see they were all written
    if (bWritten != elem_count)
    {
        return false; //not all the bytes were written!
    } 
    
    //else, all the bytes were written...
    return true;
}
Exemplo n.º 3
0
/***********************************************************************//**
 * @brief Get application parameters
 *
 * Get all task parameters from parameter file or (if required) by querying
 * the user. The parameters are read in the correct order.
 ***************************************************************************/
void ctexpcube::get_parameters(void)
{
    // Setup observations from "inobs" parameter. Do not accept counts cubes.
    setup_observations(m_obs, true, true, false);

    // Get the incube filename
    std::string incube = (*this)["incube"].filename();

    // If the "incube" file name is valid then setup the exposure cube from
    // the counts cube. Otherwise create a counts cube from the user
    // parameters
    GCTAEventCube cube = is_valid_filename(incube) ? GCTAEventCube(incube)
                                                   : create_cube(m_obs);
    
    // Define exposure cube
    m_expcube = GCTACubeExposure(cube);

    // Get remaining parameters
    m_addbounds = (*this)["addbounds"].boolean();
    m_publish   = (*this)["publish"].boolean();
    m_chatter   = static_cast<GChatter>((*this)["chatter"].integer());

    // Read output filename (if needed)
    if (read_ahead()) {
        m_outcube = (*this)["outcube"].filename();
    }

    // Write parameters into logger
    log_parameters(TERSE);

    // Return
    return;
}
Exemplo n.º 4
0
/********************************************//**
 *
 * This is the main method which will start the compiler.
 * 1) Check if the file name contains .ps, if not it will exit.
 * 2) Do the first Transition.
 * 3) Do the second transition.
 * 4) Check for errors, if errors exist it will print them and exit the program
 *    before writing the files.
 * 5) Generate the required files.
 *
 ***********************************************/
int main(int argc, char *argv[]) {
	Compiler *compiler = NULL;
	int curFileIdx = 1;

	if (argc == 1) {
		printf("No input files to compile!\n");
		exit(0);
	} else {
		while (--argc) {

			if (is_valid_filename(argv[curFileIdx]) == FALSE)
				exit(0);

			init_compiler(&compiler, BASE_OFFSET, argv[curFileIdx]);
			first_transition(compiler);
			second_transition(compiler);

			if (check_errors(compiler)) {
				//printf("errors\n");
				print_errors(compiler);
				exit(0);
			} else
				generate_files(compiler);

			free(compiler);
			curFileIdx++;
		}
	}

	printf("Compilation finished successfully.\n");
	return 0;
}
Exemplo n.º 5
0
static void handle_event(struct inotify_event *ievent)
{
	char *event_filename;
	char *dirname = NULL;
	char *fullname;

	assert(ievent);

	if (ievent->len) {
		event_filename = ievent->name;
	} else {
		return;
	}

	for (size_t i = 0; i < wds_count; i++) {
		if (wds[i] == ievent->wd) {
			dirname = dirnames[i];
			break;
		}
	}
	assert(dirname);
	fullname = strjoin(dirname, "/", event_filename, NULL);

	switch (ievent->mask & (IN_CLOSE_WRITE | IN_CREATE)) {
		case IN_CLOSE_WRITE:
			// We don't treat directories modifications
			if (ievent->mask & IN_ISDIR) {
				break;
			}
			if (!is_valid_filename(event_filename)) {
				break;
			}

			reload_callback(callback_arg, fullname);
			break;
		case IN_CREATE:
			// recursively watch new dirs
			if (!(ievent->mask & IN_ISDIR)) {
				break;
			}

			livecoding_watch_directory(fullname);
			break;
		default:
			break;
	}

	free(fullname);
}
Exemplo n.º 6
0
int ShortcutDialog::check_values()
{
	Glib::ustring path = path_entry.get_text() ;
	Glib::ustring display = display_entry.get_text() ;

	//TODO check display for correct
	if (path=="")
		return -2 ;
	else if (display=="")
		return -1 ;
	else if ( !Glib::file_test(path, Glib::FILE_TEST_EXISTS) )
		return -4 ;
	else if ( manager->exist_tree(path, number_tree) )
		return -3 ;
	//don't check name for default system name (ftp cache file, work directory)
	else if (is_valid_filename(display)<0 && !lock_name)
		return -5 ;
	else if (!FileHelper::is_readable(path)||!FileHelper::is_executable(path))
		return -6 ;
	else
		return 1 ;
}
Exemplo n.º 7
0
int main(int argc, const char **argv) {
  srand (time(NULL));
  try {
    string chrom_file;
    string outfile;
    /****************** COMMAND LINE OPTIONS ********************/
    OptionParser opt_parse(strip_path(argv[0]),
                           "build index for reference genome", "");
    opt_parse.add_opt(
        "chrom",
        'c',
        "chromosomes in FASTA file or dir \
        (the suffix of the chromosome file should be '.fa')",
        true, chrom_file);
    opt_parse.add_opt(
        "output", 'o',
        "output file name (the suffix of the file should be '.dbindex')", true,
        outfile);

    vector<string> leftover_args;
    opt_parse.parse(argc, argv, leftover_args);
    if (argc == 1 || opt_parse.help_requested()) {
      fprintf(stderr, "%s\n", opt_parse.help_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.about_requested()) {
      fprintf(stderr, "%s\n", opt_parse.about_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.option_missing()) {
      fprintf(stderr, "%s\n", opt_parse.option_missing_message().c_str());
      return EXIT_SUCCESS;
    }
    if (!is_valid_filename(outfile, "dbindex")) {
      fprintf(stderr, "The suffix of the output file should be '.dbindex'\n");
      return EXIT_FAILURE;
    }
    if (outfile.size() > 1000) {
      fprintf(stderr, "The output file name is too long, "
          "please select a shorter name\n");
      return EXIT_FAILURE;;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    //////////////////////////////////////////////////////////////
    // READ GENOME
    //
    vector<string> chrom_files;
    IdentifyChromosomes(chrom_file, chrom_files);

    //////////////////////////////////////////////////////////////
    // BUILD  INDEX
    //
    uint32_t size_of_index = 0;
    ////////// BUILD INDEX FOR FORWARD STRAND (C->T)
    BuildIndex(chrom_files, 0, outfile + "_CT00", size_of_index);

    ////////// BUILD INDEX FOR REVERSE STRAND (C->T)
    BuildIndex(chrom_files, 1, outfile + "_CT01", size_of_index);

    ////////// BUILD INDEX FOR FORWARD STRAND (G->A)
    BuildIndex(chrom_files, 2, outfile + "_GA10", size_of_index);

    ////////// BUILD INDEX FOR REVERSE STRAND (G->A)
    BuildIndex(chrom_files, 3, outfile + "_GA11", size_of_index);

    Genome genome;
    ReadGenome(chrom_files, genome);
    WriteIndexHeadInfo(outfile, genome, size_of_index);
  } catch (const SMITHLABException &e) {
    fprintf(stderr, "%s\n", e.what().c_str());
    return EXIT_FAILURE;
  } catch (std::bad_alloc &ba) {
    fprintf(stderr, "ERROR: could not allocate memory\n");
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
Exemplo n.º 8
0
int main(int argc, const char **argv) {
  srand (time(NULL));
  try {
    string command = argv[0];
    bool help_info = false;
    for (int i = 1; i < argc; i++) {
      command += " ";
      command += argv[i];
      if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-about") == 0
          || strcmp(argv[i], "-?") == 0) {
        help_info = true;
      }
    }

    if (argc > 1 && help_info == false) {
      /* show the command line one the screen */
      fprintf(stderr, "[WELCOME TO WALT v%s]\n", walt_version);
      fprintf(stderr, "[%s", argv[0]);
      for (int i = 1; i < argc; i++) {
        fprintf(stderr, " %s", argv[i]);
      }
      fprintf(stderr, "]\n");
    }

    /* singled-end reads file, comma-separated list of files */
    string reads_file_s;
    vector<string> v_reads_file_s;

    /* paired-end reads files, comma-separated list of files*/
    string reads_file_p1;
    string reads_file_p2;
    vector<string> v_reads_file_p1;
    vector<string> v_reads_file_p2;

    /* index file*/
    string index_file;

    /* output file */
    string output_file;
    vector<string> v_output_file;

    /* WALT supports Tab-delimited SAM and MR output formats.
     * By default, WALT produces SAM format output files. To
     * get MR format, the suffix of the output file should be
     * ".mr". */
    bool SAM = true;

    /* trimming adaptor sequence */
    string adaptor;

    /* paired-end or single-end mapping */
    bool is_paired_end_reads = false;

    /* output ambiguous or unmapped reads or not, both are false by default */
    bool ambiguous = false;
    bool unmapped = false;

    /* AG_WILDCARD is false by default, which means that all Cs
     * in the reads and genome are converted to Ts.
     * If AG_WILDCARD is true, all Gs in the reads and genome
     * are converted to As. If option is only for single-end mapping */
    bool AG_WILDCARD = false;

    /* maximum allowed mismatches */
    uint32_t max_mismatches = 6;

    /* number of reads to map at one loop */
    uint32_t n_reads_to_process = 1000000;

    /* paired-end reads: keep top k genome positions for each in the pair */
    uint32_t top_k = 50;

    /* max fragment length for paired end reads */
    int frag_range = 1000;

    /* number of threads for mapping */
    int num_of_threads = 1;

    /****************** COMMAND LINE OPTIONS ********************/
    OptionParser opt_parse(strip_path(argv[0]), "map Illumina BS-seq reads",
                           "");
    opt_parse.add_opt(
        "index",
        'i',
        "index file created by makedb command \
        (the suffix of the index file should be '.dbindex')",
        true, index_file);
    opt_parse.add_opt(
        "reads",
        'r',
        "comma-separated list of read files for singled-end mapping \
         (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_s);
    opt_parse.add_opt(
        "reads1",
        '1',
        "comma-separated list of read files for mate 1 \
         (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_p1);
    opt_parse.add_opt(
        "reads2",
        '2',
        "comma-separated list of read files for mate 2 \
        (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_p2);
    opt_parse.add_opt("output", 'o', "output file name", true, output_file);
    opt_parse.add_opt("mismatch", 'm', "maximum allowed mismatches", false,
                      max_mismatches);
    opt_parse.add_opt("number", 'N', "number of reads to map at one loop",
                      false, n_reads_to_process);
    opt_parse.add_opt(
        "ambiguous",
        'a',
        "randomly output one mapped position for ambiguous \
        reads in a separated file",
        false, ambiguous);
    opt_parse.add_opt("unmapped", 'u',
                      "output unmapped reads in a separated file", false,
                      unmapped);
    opt_parse.add_opt("clip", 'C', "clip the specified adaptor", false,
                      adaptor);
    opt_parse.add_opt("ag-wild", 'A',
                      "map using A/G bisulfite wildcards (single-end)", false,
                      AG_WILDCARD);
    opt_parse.add_opt("topk", 'k',
                      "maximum allowed mappings for a read (paired-end)", false,
                      top_k);
    opt_parse.add_opt("fraglen", 'L', "max fragment length (paired-end)", false,
                      frag_range);
    opt_parse.add_opt("thread", 't', "number of threads for mapping", false,
                      num_of_threads);

    vector<string> leftover_args;
    opt_parse.parse(argc, argv, leftover_args);
    if (argc == 1 || opt_parse.help_requested()) {
      fprintf(stderr, "%s\n", opt_parse.help_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.about_requested()) {
      fprintf(stderr, "%s\n", opt_parse.about_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.option_missing()) {
      fprintf(stderr, "%s\n", opt_parse.option_missing_message().c_str());
      return EXIT_SUCCESS;
    }

    if (!is_valid_filename(index_file, "dbindex")) {
      fprintf(stderr, "The suffix of the index file should be '.dbindex'\n");
      return EXIT_FAILURE;
    }

    if (!reads_file_s.empty() && reads_file_p1.empty()
        && reads_file_p2.empty()) {
      is_paired_end_reads = false;
    } else if (reads_file_s.empty() && !reads_file_p1.empty()
        && !reads_file_p2.empty()) {
      is_paired_end_reads = true;
    } else {
      fprintf(stderr, "Please use -r option to set singled-end reads, \n"
              "-1 and -2 options to set paired-end reads\n");
      return EXIT_FAILURE;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    bool get_empty_fields = false;
    if (!is_paired_end_reads) {
      v_reads_file_s = smithlab::split(reads_file_s, ",", get_empty_fields);
      for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
        if (!is_valid_filename(v_reads_file_s[i], "fastq")
            && !is_valid_filename(v_reads_file_s[i], "fq")) {
          fprintf(stderr,
                  "The suffix of the reads file should be '.fastq', '.fq'\n");
          return EXIT_FAILURE;
        }
      }
    } else {
      v_reads_file_p1 = smithlab::split(reads_file_p1, ",", get_empty_fields);
      v_reads_file_p2 = smithlab::split(reads_file_p2, ",", get_empty_fields);
      if (v_reads_file_p1.size() != v_reads_file_p2.size()) {
        fprintf(
            stderr,
            "For paired-end mapping, mate 1 and mate 2 should \n\
                have the same number of files, and the paired files \n\
                should be in the same order.");
        return EXIT_FAILURE;
      }
      for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
        if (!is_valid_filename(v_reads_file_p1[i], "fastq")
            && !is_valid_filename(v_reads_file_p1[i], "fq")) {
          fprintf(stderr,
                  "The suffix of the reads file should be '.fastq', '.fq'\n");
          return EXIT_FAILURE;
        }
      }
    }

    if (!is_paired_end_reads) {
      if (v_reads_file_s.size() == 1) {
        v_output_file.push_back(output_file);
      } else {
        char output_filename[1000];
        for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
          sprintf(output_filename, "%s_s%u", output_file.c_str(), i);
          v_output_file.push_back(output_filename);
        }
      }
    } else {
      if (v_reads_file_p1.size() == 1) {
        v_output_file.push_back(output_file);
      } else {
        char output_filename[1000];
        for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
          sprintf(output_filename, "%s_p%u", output_file.c_str(), i);
          v_output_file.push_back(output_filename);
        }
      }
    }

    for (uint32_t i = 0; i < v_reads_file_p2.size(); ++i) {
      if (!is_valid_filename(v_reads_file_p2[i], "fastq")
          && !is_valid_filename(v_reads_file_p2[i], "fq")) {
        fprintf(stderr,
                "The suffix of the reads file should be '.fastq', '.fq'\n");
        return EXIT_FAILURE;
      }
    }

    size_t suffix_pos = output_file.find_last_of(".");
    if (suffix_pos == string::npos) {
      SAM = true;
    } else if (".mr" == output_file.substr(suffix_pos)) {
      SAM = false;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    //////////////////////////////////////////////////////////////
    // CHECK OPTIONS
    fprintf(stderr, "[MAXIMUM NUMBER OF MISMATCHES IS %u]\n", max_mismatches);
    fprintf(stderr, "[NUMBER OF THREADS FOR MAPPING IS %d]\n", num_of_threads);

    if (n_reads_to_process > 5000000) {
      n_reads_to_process = 5000000;
    }

    if (is_paired_end_reads && top_k < 2) {
      fprintf(stderr, "-k option should be at least 2 for paired-end reads\n");
      return EXIT_FAILURE;
    }

    if (is_paired_end_reads && top_k > 300) {
      fprintf(stderr,
              "-k option should be less than 300 for paired-end reads\n");
      return EXIT_FAILURE;
    }
    ShowGenomeInfo(index_file);

    //////////////////////////////////////////////////////////////
    // Mapping
    if (!is_paired_end_reads) {
      for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
        ProcessSingledEndReads(command, index_file, v_reads_file_s[i],
                               v_output_file[i], n_reads_to_process,
                               max_mismatches, adaptor, AG_WILDCARD, ambiguous,
                               unmapped, SAM, num_of_threads);
      }
    } else {
      for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
        ProcessPairedEndReads(command, index_file, v_reads_file_p1[i],
                              v_reads_file_p2[i], v_output_file[i],
                              n_reads_to_process, max_mismatches, adaptor,
                              top_k, frag_range, ambiguous, unmapped, SAM,
                              num_of_threads);
      }
    }
  } catch (const SMITHLABException &e) {
Exemplo n.º 9
0
void do_bset( CHAR_DATA * ch, char *argument )
{
  BOARD_DATA *board = NULL;
  bool found = FALSE;
  char arg1[MAX_INPUT_LENGTH];
  char arg2[MAX_INPUT_LENGTH];
  char buf[MAX_STRING_LENGTH];
  int value = 0;

  argument = one_argument( argument, arg1 );
  argument = one_argument( argument, arg2 );

  if( arg1[0] == '\0' || arg2[0] == '\0' )
  {
    send_to_char( "Usage: bset <board filename> <field> value\r\n", ch );
    send_to_char( "\r\nField being one of:\r\n", ch );
    send_to_char( "  vnum read post remove maxpost filename type\r\n", ch );
    send_to_char
      ( "  read_group post_group extra_readers extra_removers\r\n", ch );
    return;
  }

  value = atoi( argument );

  for( board = first_board; board; board = board->next )
    if( !str_cmp( arg1, board->note_file ) )
    {
      found = TRUE;
      break;
    }
  if( !found )
  {
    send_to_char( "Board not found.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "vnum" ) )
  {
    if( !get_obj_index( value ) )
    {
      send_to_char( "No such object.\r\n", ch );
      return;
    }
    board->board_obj = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "read" ) )
  {
    if( value < 0 || value > MAX_LEVEL )
    {
      send_to_char( "Value out of range.\r\n", ch );
      return;
    }
    board->min_read_level = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "read_group" ) )
  {
    if( !argument || argument[0] == '\0' )
    {
      send_to_char( "No group specified.\r\n", ch );
      return;
    }
    DISPOSE( board->read_group );
    if( !str_cmp( argument, "none" ) )
      board->read_group = str_dup( "" );
    else
      board->read_group = str_dup( argument );
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "post_group" ) )
  {
    if( !argument || argument[0] == '\0' )
    {
      send_to_char( "No group specified.\r\n", ch );
      return;
    }
    DISPOSE( board->post_group );
    if( !str_cmp( argument, "none" ) )
      board->post_group = str_dup( "" );
    else
      board->post_group = str_dup( argument );
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "extra_removers" ) )
  {
    if( !argument || argument[0] == '\0' )
    {
      send_to_char( "No names specified.\r\n", ch );
      return;
    }
    if( !str_cmp( argument, "none" ) )
      buf[0] = '\0';
    else
      sprintf( buf, "%s %s", board->extra_removers, argument );
    DISPOSE( board->extra_removers );
    board->extra_removers = str_dup( buf );
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "extra_readers" ) )
  {
    if( !argument || argument[0] == '\0' )
    {
      send_to_char( "No names specified.\r\n", ch );
      return;
    }
    if( !str_cmp( argument, "none" ) )
      buf[0] = '\0';
    else
      sprintf( buf, "%s %s", board->extra_readers, argument );
    DISPOSE( board->extra_readers );
    board->extra_readers = str_dup( buf );
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "filename" ) )
  {
    char filename[256];

    if( !is_valid_filename( ch, BOARD_DIR, argument ) )
      return;

    sprintf( filename, "%s%s", BOARD_DIR, board->note_file );
    if( !remove( filename ) )
      send_to_char( "Old board file deleted.\r\n", ch );

    DISPOSE( board->note_file );
    board->note_file = str_dup( argument );
    write_boards_txt();
    send_to_char( "Done.  (board's filename set)\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "post" ) )
  {
    if( value < 0 || value > MAX_LEVEL )
    {
      send_to_char( "Value out of range.\r\n", ch );
      return;
    }
    board->min_post_level = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "remove" ) )
  {
    if( value < 0 || value > MAX_LEVEL )
    {
      send_to_char( "Value out of range.\r\n", ch );
      return;
    }
    board->min_remove_level = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  if( !str_cmp( arg2, "maxpost" ) )
  {
    if( value < 1 || value > 1000 )
    {
      send_to_char( "Value out of range.\r\n", ch );
      return;
    }
    board->max_posts = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }
  if( !str_cmp( arg2, "type" ) )
  {
    if( value < 0 || value > 1 )
    {
      send_to_char( "Value out of range.\r\n", ch );
      return;
    }
    board->type = value;
    write_boards_txt();
    send_to_char( "Done.\r\n", ch );
    return;
  }

  do_bset( ch, STRLIT_EMPTY );
}
Exemplo n.º 10
0
static int zwr(struct zws *zws, size_t offset)
{
	int err, fd;
	size_t len;
	DIR *dir;
	struct dirent *ent;
	zip_int64_t z64;
	struct zip_source *zsrc;
	FILE *fp;

	fd = openat(workdirfd, offset ? zws->name : ".", O_DIRECTORY|O_RDONLY);
	if (fd < 0) {
		ERROR("opendir %.*s failed in zwr", (int)offset, zws->name);
		return -1;
	}
	dir = fdopendir(fd);
	if (!dir) {
		close(fd);
		ERROR("opendir %.*s failed in zwr", (int)offset, zws->name);
		return -1;
	}

	if (offset != 0)
		zws->name[offset++] = '/';

	ent = readdir(dir);
	while (ent != NULL) {
		len = strlen(ent->d_name);
		if (ent->d_name[0] == '.' && (len == 1 || 
			(ent->d_name[1] == '.' && len == 2)))
			;
		else if (offset + len >= sizeof(zws->name)) {
			ERROR("name too long in zwr");
			errno = ENAMETOOLONG;
			goto error;
		} else {
			memcpy(zws->name + offset, ent->d_name, 1+len);
			if (!is_valid_filename(ent->d_name)) {
				ERROR("invalid name %s", zws->name);
				goto error;
			}
			switch (ent->d_type) {
			case DT_DIR:
				z64 = zip_dir_add(zws->zip, zws->name, ZIP_FL_ENC_UTF_8);
				if (z64 < 0) {
					ERROR("zip_dir_add of %s failed", zws->name);
					goto error;
				}
				err = zwr(zws, offset + len);
				if (err)
					goto error;
				break;
			case DT_REG:
				fd = openat(workdirfd, zws->name, O_RDONLY);
				if (fd < 0) {
					ERROR("openat of %s failed", zws->name);
					goto error;
				}
				fp = fdopen(fd, "r");
				if (fp == NULL) {
					ERROR("fdopen of %s failed", zws->name);
					close(fd);
					goto error;
				}
				zsrc = zip_source_filep(zws->zip, fp, 0, 0);
				if (zsrc == NULL) {
					ERROR("zip_source_file of %s failed", zws->name);
					fclose(fp);
					goto error;
				}
				z64 = zip_file_add(zws->zip, zws->name, zsrc, ZIP_FL_ENC_UTF_8);
				if (z64 < 0) {
					ERROR("zip_file_add of %s failed", zws->name);
					zip_source_free(zsrc);
					goto error;
				}
				break;
			default:
				break;
			}
		}
		ent = readdir(dir);
	}

	closedir(dir);
	return 0;
error:
	closedir(dir);
	return -1;
}
Exemplo n.º 11
0
/* read (extract) 'zipfile' in current directory */
int zread(const char *zipfile, unsigned long long maxsize)
{
	struct filedesc *fdesc;
	int err, fd;
	size_t len;
	struct zip *zip;
	zip_int64_t z64;
	zip_uint64_t uz64;
	unsigned int count, index;
	struct zip_file *zfile;
	struct zip_stat zstat;
	char buffer[32768];
	ssize_t sizr, sizw;
	size_t esize;

	/* open the zip file */
	zip = zip_open(zipfile, ZIP_CHECKCONS, &err);
	if (!zip) {
		ERROR("Can't connect to file %s", zipfile);
		return -1;
	}

	z64 = zip_get_num_entries(zip, 0);
	if (z64 < 0 || z64 > UINT_MAX) {
		ERROR("too many entries in %s", zipfile);
		goto error;
	}
	count = (unsigned int)z64;

	/* records the files */
	file_reset();
	esize = 0;
	for (index = 0 ; index < count ; index++) {
		err = zip_stat_index(zip, index, ZIP_FL_ENC_GUESS, &zstat);
		/* check the file name */
		if (!is_valid_filename(zstat.name)) {
			ERROR("invalid entry %s found in %s", zstat.name, zipfile);
			goto error;
		}
		if (zstat.name[0] == '/') {
			ERROR("absolute entry %s found in %s", zstat.name, zipfile);
			goto error;
		}
		len = strlen(zstat.name);
		if (len == 0) {
			ERROR("empty entry found in %s", zipfile);
			goto error;
		}
		if (zstat.name[len - 1] == '/')
			/* record */
			fdesc = file_add_directory(zstat.name);
		else {
			/* get the size */
			esize += zstat.size;
			/* record */
			fdesc = file_add_file(zstat.name);
		}
		if (!fdesc)
			goto error;
		fdesc->zindex = index;
	}

	/* check the size */
	if (maxsize && esize > maxsize) {
		ERROR("extracted size %zu greater than allowed size %llu", esize, maxsize);
		goto error;
	}

	/* unpack the recorded files */
	assert(count == file_count());
	for (index = 0 ; index < count ; index++) {
		fdesc = file_of_index(index);
		assert(fdesc != NULL);
		err = zip_stat_index(zip, fdesc->zindex, ZIP_FL_ENC_GUESS, &zstat);
		assert(zstat.name[0] != '/');
		len = strlen(zstat.name);
		assert(len > 0);
		if (zstat.name[len - 1] == '/') {
			/* directory name */
			err = create_directory((char*)zstat.name, MODE_OF_DIRECTORY_CREATION);
			if (err && errno != EEXIST)
				goto error;
		} else {
			/* file name */
			zfile = zip_fopen_index(zip, fdesc->zindex, 0);
			if (!zfile) {
				ERROR("Can't open %s in %s", zstat.name, zipfile);
				goto error;
			}
			fd = create_file((char*)zstat.name, MODE_OF_FILE_CREATION, MODE_OF_DIRECTORY_CREATION);
			if (fd < 0)
				goto errorz;
			/* extract */
			uz64 = zstat.size;
			while (uz64) {
				sizr = zip_fread(zfile, buffer, sizeof buffer);
				if (sizr < 0) {
					ERROR("error while reading %s in %s", zstat.name, zipfile);
					goto errorzf;
				}
				sizw = write(fd, buffer, (size_t)sizr);
				if (sizw < 0) {
					ERROR("error while writing %s", zstat.name);
					goto errorzf;
				}
				uz64 -= (size_t)sizw;
			}
			close(fd);
			zip_fclose(zfile);
		}
	}

	zip_close(zip);
	return 0;

errorzf:
	close(fd);
errorz:
	zip_fclose(zfile);
error:
	zip_close(zip);
	return -1;
}