示例#1
0
文件: tree.c 项目: Oblomov/tig
void
open_blob_editor(const char *id, const char *name, unsigned int lineno)
{
	const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
	char file[SIZEOF_STR];
	int fd;

	if (!name)
		name = "unknown";

	if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
		report("Temporary file name is too long");
		return;
	}

	fd = mkstemps(file, strlen(name) + 1);

	if (fd == -1)
		report("Failed to create temporary file");
	else if (!io_run_append(blob_argv, fd))
		report("Failed to save blob data to file");
	else
		open_editor(file, lineno);
	if (fd != -1)
		unlink(file);
}
示例#2
0
static rc_t show_details( tool_ctx_t * tool_ctx )
{
    rc_t rc = KOutMsg( "cursor-cache : %,ld bytes\n", tool_ctx -> cursor_cache );
    if ( rc == 0 )
        rc = KOutMsg( "buf-size     : %,ld bytes\n", tool_ctx -> buf_size );
    if ( rc == 0 )
        rc = KOutMsg( "mem-limit    : %,ld bytes\n", tool_ctx -> mem_limit );
    if ( rc == 0 )
        rc = KOutMsg( "threads      : %d\n", tool_ctx -> num_threads );
    if ( rc == 0 )
        rc = KOutMsg( "scratch-path : '%s'\n", get_temp_dir( tool_ctx -> temp_dir ) );
    if ( rc == 0 )
        rc = KOutMsg( "output-format: " );
    if ( rc == 0 )
    {
        switch ( tool_ctx -> fmt )
        {
            case ft_special             : rc = KOutMsg( "SPECIAL\n" ); break;
            case ft_whole_spot          : rc = KOutMsg( "FASTQ whole spot\n" ); break;
            case ft_fastq_split_spot    : rc = KOutMsg( "FASTQ split spot\n" ); break;
            case ft_fastq_split_file    : rc = KOutMsg( "FASTQ split file\n" ); break;
            case ft_fastq_split_3       : rc = KOutMsg( "FASTQ split 3\n" ); break;
            default                     : rc = KOutMsg( "unknow format\n" ); break;
        }
    }
    if ( rc == 0 )
    {
        rc = KOutMsg( "output-file  : '%s'\n", tool_ctx -> output_filename );
        rc = KOutMsg( "output-dir   : '%s'\n", tool_ctx -> output_dirname );
    }
    return rc;
}
示例#3
0
FILE *make_temp_file(char **filename) {
	char tmp[PATH_MAX];
	FILE *temp;
	int fd;

	if (get_temp_dir(tmp, PATH_MAX) < 0)
		return NULL;

	strncat(tmp, "xmp_XXXXXX", PATH_MAX - 10);

	if ((*filename = strdup(tmp)) == NULL)
		goto err;

#ifdef HAVE_UMASK
	umask(0177);
#endif
	if ((fd = mkstemp(*filename)) < 0)
		goto err2;

	if ((temp = fdopen(fd, "w+b")) == NULL)
		goto err3;

	return temp;

    err3:
	close(fd);
    err2:
	free(*filename);
    err:
	return NULL;
}
示例#4
0
std::string Filesystem::get_temp_filename(std::string filename_tag, std::string filename_end) {
    std::string temp_path = get_temp_dir() + "/" + filename_tag + "-";

    static std::unique_ptr<std::mt19937> rng;
    if (!rng) {
        // Construct and seed the RNG
        std::random_device r{};
        rng.reset(new std::mt19937(r()));
    }

    std::uniform_int_distribution<char> uniform_dist(0, 61);
    for (unsigned i = 0; i < 10; ++i) {
        char rand_char = uniform_dist(*rng);
        if (rand_char >= 52) {
            rand_char = '0' + (rand_char - 52);
        } else if (rand_char >= 26) {
            rand_char = 'A' + (rand_char - 26);
        } else {
            rand_char = 'a' + rand_char;
        }
        temp_path += rand_char;
    }

    if (! filename_end.empty()) {
        temp_path += "-" + filename_end.substr(filename_end.rfind('/')+1);
    }

    return temp_path;
}
示例#5
0
static rc_t populate_tool_ctx( tool_ctx_t * tool_ctx, const Args * args )
{
    rc_t rc = ArgsParamValue( args, 0, ( const void ** )&( tool_ctx -> accession_path ) );
    if ( rc != 0 )
        ErrMsg( "ArgsParamValue() -> %R", rc );
    else
    {
        tool_ctx -> lookup_filename[ 0 ] = 0;
        tool_ctx -> index_filename[ 0 ] = 0;
        tool_ctx -> dflt_output[ 0 ] = 0;
    
        get_user_input( tool_ctx, args );
        encforce_constrains( tool_ctx );
        get_environment( tool_ctx );
        
        rc = make_temp_dir( &tool_ctx -> temp_dir,
                          tool_ctx -> requested_temp_path,
                          tool_ctx -> dir );
    }
    
    if ( rc == 0 )
        rc = handle_accession( tool_ctx );
    
    if ( rc == 0 )
        rc = handle_lookup_path( tool_ctx );
    
    if ( rc == 0 && tool_ctx -> output_dirname != NULL )
    {
        if ( !dir_exists( tool_ctx -> dir, "%s", tool_ctx -> output_dirname ) )
            rc = create_this_dir_2( tool_ctx -> dir, tool_ctx -> output_dirname, true );
    }
    
    if ( rc == 0 )
    {
        if ( tool_ctx -> output_filename == NULL )
        {
            if ( tool_ctx -> output_dirname == NULL )
                rc = make_output_filename_from_accession( tool_ctx );
            else
                rc = make_output_filename_from_dir_and_accession( tool_ctx );
        }
        else
        {
            if ( tool_ctx -> output_dirname == NULL )
                rc = adjust_output_filename( tool_ctx );
            else
                rc = adjust_output_filename_by_dir( tool_ctx );
        }
    }
    
    if ( rc == 0 )
        rc = Make_FastDump_Cleanup_Task ( &( tool_ctx -> cleanup_task ) ); /* cleanup_task.c */
    if ( rc == 0 )
        rc = Add_Directory_to_Cleanup_Task ( tool_ctx -> cleanup_task, 
                get_temp_dir( tool_ctx -> temp_dir ) );
    return rc;
}
示例#6
0
void
mux_dialog::run() {
    auto &arg_list = static_cast<mmg_dialog *>(GetParent())->get_command_line_args();

    opt_file_name.Printf(wxT("%smmg-mkvmerge-options-%d-%d"), get_temp_dir().c_str(), (int)wxGetProcessId(), (int)wxGetUTCTime());
    try {
        const unsigned char utf8_bom[3] = {0xef, 0xbb, 0xbf};
        wxFile opt_file{opt_file_name, wxFile::write};
        opt_file.Write(utf8_bom, 3);

        for (size_t i = 1; i < arg_list.Count(); i++) {
            if (arg_list[i].IsEmpty())
                opt_file.Write(wxT("#EMPTY#"));
            else {
                auto arg_utf8 = escape(to_utf8(arg_list[i]));
                opt_file.Write(arg_utf8.c_str(), arg_utf8.length());
            }
            opt_file.Write(wxT("\n"));
        }
    } catch (mtx::mm_io::exception &ex) {
        wxString error;
        error.Printf(Z("Could not create a temporary file for mkvmerge's command line option called '%s' (error code %d, %s)."), opt_file_name.c_str(), errno, wxUCS(ex.error()));
        wxMessageBox(error, Z("File creation failed"), wxOK | wxCENTER | wxICON_ERROR);
        throw 0;
    }

#if defined(SYS_WINDOWS)
    if (get_windows_version() >= WINDOWS_VERSION_7) {
        m_taskbar_progress = new taskbar_progress_c(mdlg);
        m_taskbar_progress->set_state(TBPF_NORMAL);
        m_taskbar_progress->set_value(0, 100);
    }
#endif  // SYS_WINDOWS

    update_label(Z("Muxing in progress."));

    m_start_time                 = get_current_time_millis();
    m_next_remaining_time_update = m_start_time + 8000;

    m_process                    = new mux_process{this};
    m_pid                        = wxExecute(wxString::Format(wxT("\"%s\" \"@%s\""), arg_list[0].c_str(), opt_file_name.c_str()), wxEXEC_ASYNC, m_process);

    if (0 == m_pid) {
        wxCommandEvent evt(mux_process::event, mux_process::process_terminated);
        evt.SetInt(2);
        wxPostEvent(this, evt);

    } else {
        m_read_input_timer.SetOwner(this, ID_T_READ_INPUT);
        m_read_input_timer.Start(100);
    }

    ShowModal();
}
示例#7
0
char* get_asset_temp_dir()
{
	static char gAssetTempFolder[MAX_PATH_LEN] = "";
	static bool created = false;
	if(!created) {
		if(assetName[0] == '\0') {
			error("ERROR: the asset name has not been specified before get_asset_temp_dir() was called.");
		}

		created = true;

		sprintf(gAssetTempFolder, "%s"DSSTR"%s",  get_temp_dir(), assetName);

		if(!Compat::Path(gAssetTempFolder).mkdir()) {
			error("ERROR: Failed to create directory %s.", gAssetTempFolder);
		}
	}
	return gAssetTempFolder;
}
示例#8
0
static const char * getLogPath() {
	static char gLogPath[MAX_PATH_LEN] = "";

	if(gLogPath[0] == '\0') {
#ifdef IS_UNIX
		const char * env_path = getenv("MODTOOLS_LOG");
		if(env_path) {
			if(strlen(env_path) >= sizeof(gLogPath)) {
				error("ERROR: buffer overflow on setting log path from environment.");
			}
			strcpy(gLogPath, env_path);
		}
		if(gLogPath[0] == '\0') {
#endif
			strcpy(gLogPath, get_temp_dir());
			strcat(gLogPath, DSSTR LOG_NAME);
#ifdef IS_UNIX
		}
#endif

	}

	return gLogPath;
}
示例#9
0
static void get_stderr_file_path(char *path) {
	get_temp_dir(path);
	strcat(path, "/stderr-SqueezePlay.txt");
}
示例#10
0
mux_dialog::mux_dialog(wxWindow *parent):
    wxDialog(parent, -1, Z("mkvmerge is running"), wxDefaultPosition,
#ifdef SYS_WINDOWS
             wxSize(700, 560),
#else
             wxSize(700, 520),
#endif
             wxDEFAULT_FRAME_STYLE)
#if defined(SYS_WINDOWS)
    , pid(0)
    , m_taskbar_progress(NULL)
    , m_abort_button_changed(false)
#endif  // SYS_WINDOWS
    , m_exit_code(0)
    , m_progress(0)
{
    char c;
    std::string arg_utf8, line;
    long value;
    wxString wx_line, tmp;
    wxInputStream *out;
    wxFile *opt_file;
    uint32_t i;
    wxArrayString *arg_list;
    wxBoxSizer *siz_all, *siz_buttons, *siz_line;
    wxStaticBoxSizer *siz_status, *siz_output;

    m_window_disabler = new wxWindowDisabler(this);

    c = 0;
    siz_status = new wxStaticBoxSizer(new wxStaticBox(this, -1, Z("Status and progress")), wxVERTICAL);
    st_label = new wxStaticText(this, -1, wxEmptyString);
    st_remaining_time_label = new wxStaticText(this, -1, Z("Remaining time:"));
    st_remaining_time       = new wxStaticText(this, -1, Z("is being estimated"));
    siz_line = new wxBoxSizer(wxHORIZONTAL);
    siz_line->Add(st_label);
    siz_line->AddSpacer(5);
    siz_line->Add(st_remaining_time_label);
    siz_line->AddSpacer(5);
    siz_line->Add(st_remaining_time);
    siz_status->Add(siz_line, 0, wxGROW | wxALIGN_LEFT | wxALL, 5);
    g_progress = new wxGauge(this, -1, 100, wxDefaultPosition, wxSize(250, 15));
    siz_status->Add(g_progress, 1, wxALL | wxGROW, 5);

    siz_output = new wxStaticBoxSizer(new wxStaticBox(this, -1, Z("Output")), wxVERTICAL);
    siz_output->Add(new wxStaticText(this, -1, Z("mkvmerge output:")), 0, wxALIGN_LEFT | wxALL, 5);
    tc_output = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_BESTWRAP | wxTE_MULTILINE);
    siz_output->Add(tc_output, 2, wxGROW | wxALL, 5);
    siz_output->Add(new wxStaticText(this, -1, Z("Warnings:")), 0, wxALIGN_LEFT | wxALL, 5);
    tc_warnings = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_BESTWRAP | wxTE_MULTILINE);
    siz_output->Add(tc_warnings, 1, wxGROW | wxALL, 5);
    siz_output->Add(new wxStaticText(this, -1, Z("Errors:")), 0, wxALIGN_LEFT | wxALL, 5);
    tc_errors = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_BESTWRAP | wxTE_MULTILINE);
    siz_output->Add(tc_errors, 1, wxGROW | wxALL, 5);

    siz_buttons = new wxBoxSizer(wxHORIZONTAL);
    siz_buttons->AddStretchSpacer();
    b_ok = new wxButton(this, ID_B_MUX_OK, Z("Ok"));
    b_ok->Enable(false);
    siz_buttons->Add(b_ok, 0, wxGROW);
    siz_buttons->AddStretchSpacer();
    b_abort = new wxButton(this, ID_B_MUX_ABORT, Z("Abort"));
    siz_buttons->Add(b_abort, 0, wxGROW);
    siz_buttons->AddStretchSpacer();
    b_save_log = new wxButton(this, ID_B_MUX_SAVELOG, Z("Save log"));
    siz_buttons->Add(b_save_log, 0, wxGROW);
    siz_buttons->AddStretchSpacer();

    siz_all = new wxBoxSizer(wxVERTICAL);
    siz_all->Add(siz_status, 0, wxGROW | wxALL, 5);
    siz_all->Add(siz_output, 1, wxGROW | wxALL, 5);
    siz_all->Add(siz_buttons, 0, wxGROW | wxALL, 10);
    SetSizer(siz_all);

    update_window(Z("Muxing in progress."));
    Show(true);

    process = new mux_process(this);

    opt_file_name.Printf(wxT("%smmg-mkvmerge-options-%d-%d"), get_temp_dir().c_str(), (int)wxGetProcessId(), (int)wxGetUTCTime());
    try {
        const unsigned char utf8_bom[3] = {0xef, 0xbb, 0xbf};
        opt_file = new wxFile(opt_file_name, wxFile::write);
        opt_file->Write(utf8_bom, 3);
    } catch (...) {
        wxString error;
        error.Printf(Z("Could not create a temporary file for mkvmerge's command line option called '%s' (error code %d, %s)."), opt_file_name.c_str(), errno, wxUCS(strerror(errno)));
        wxMessageBox(error, Z("File creation failed"), wxOK | wxCENTER | wxICON_ERROR);
        throw 0;
    }
    arg_list = &static_cast<mmg_dialog *>(parent)->get_command_line_args();
    for (i = 1; i < arg_list->Count(); i++) {
        if ((*arg_list)[i].Length() == 0)
            opt_file->Write(wxT("#EMPTY#"));
        else {
            arg_utf8 = escape(wxMB((*arg_list)[i]));
            opt_file->Write(arg_utf8.c_str(), arg_utf8.length());
        }
        opt_file->Write(wxT("\n"));
    }
    delete opt_file;

#if defined(SYS_WINDOWS)
    if (get_windows_version() >= WINDOWS_VERSION_7) {
        m_taskbar_progress = new taskbar_progress_c(mdlg);
        m_taskbar_progress->set_state(TBPF_NORMAL);
        m_taskbar_progress->set_value(0, 100);
    }
#endif  // SYS_WINDOWS

    m_start_time                 = get_current_time_millis();
    m_next_remaining_time_update = m_start_time + 8000;

    wxString command_line = wxString::Format(wxT("\"%s\" \"@%s\""), (*arg_list)[0].c_str(), opt_file_name.c_str());
    pid = wxExecute(command_line, wxEXEC_ASYNC, process);
    if (0 == pid) {
        wxLogError(wxT("Execution of '%s' failed."), command_line.c_str());
        done(2);
        return;
    }
    out = process->GetInputStream();

    line = "";
    log = wxEmptyString;
    while (1) {
        while (app->Pending())
            app->Dispatch();

        if (!out->CanRead() && !out->Eof()) {
            wxMilliSleep(5);
            continue;
        }

        if (!out->Eof())
            c = out->GetC();
        else
            c = '\n';

        if ((c == '\n') || (c == '\r') || out->Eof()) {
            wx_line = wxU(line);
            log += wx_line;
            if (c != '\r')
                log += wxT("\n");
            if (wx_line.Find(Z("Warning:")) == 0)
                tc_warnings->AppendText(wx_line + wxT("\n"));
            else if (wx_line.Find(Z("Error:")) == 0)
                tc_errors->AppendText(wx_line + wxT("\n"));
            else if (wx_line.Find(Z("Progress")) == 0) {
                if (wx_line.Find(wxT("%")) != 0) {
                    wx_line.Remove(wx_line.Find(wxT("%")));
                    tmp = wx_line.AfterLast(wxT(' '));
                    tmp.ToLong(&value);
                    if ((value >= 0) && (value <= 100))
                        update_gauge(value);
                }
            } else if (wx_line.Length() > 0)
                tc_output->AppendText(wx_line + wxT("\n"));
            line = "";

            update_remaining_time();

        } else if ((unsigned char)c != 0xff)
            line += c;

        if (out->Eof())
            break;
    }
}
示例#11
0
/*
 * Archiving related functions.
 * This one creates a list of files to be included into the archive and
 * sets up the libarchive context.
 */
int
setup_archiver(pc_ctx_t *pctx, struct stat *sbuf)
{
	char *tmpfile, *tmp;
	int err, fd;
	uchar_t *pbuf;
	struct archive *arc;
	struct fn_list *fn;

	/*
	 * If sorting is enabled create the initial sort buffer.
	 */
	if (pctx->enable_archive_sort) {
		struct sort_buf *srt;
		srt = (struct sort_buf *)malloc(sizeof (struct sort_buf));
		if (srt == NULL) {
			log_msg(LOG_ERR, 0, "Out of memory.");
			return (-1);
		}
		srt->next = NULL;
		srt->pos = 0;
		pctx->archive_sort_buf = srt;
	}

	/*
	 * Create a temporary file to hold the generated list of pathnames to be archived.
	 * Storing in a file saves memory usage and allows scalability.
	 */
	tmpfile = pctx->archive_members_file;
	tmp = get_temp_dir();
	strcpy(tmpfile, tmp);
	free(tmp);

	strcat(tmpfile, "/.pcompXXXXXX");
	if ((fd = mkstemp(tmpfile)) == -1) {
		log_msg(LOG_ERR, 1, "mkstemp errored.");
		return (-1);
	}

	add_fname(tmpfile);
	pbuf = malloc(pctx->chunksize);
	if (pbuf == NULL) {
		log_msg(LOG_ERR, 0, "Out of memory.");
		close(fd);  unlink(tmpfile);
		return (-1);
	}

	/*
	 * Use nftw() to scan all the directory hierarchies provided on the command
	 * line and generate a consolidated list of pathnames to be archived. By
	 * doing this we can sort the pathnames and estimate the total archive size.
	 * Total archive size is needed by the subsequent compression stages.
	 */
	log_msg(LOG_INFO, 0, "Scanning files.");
	sbuf->st_size = 0;
	pctx->archive_size = 0;
	pctx->archive_members_count = 0;

	/*
	 * nftw requires using global state variable. So we lock to be mt-safe.
	 * This means only one directory tree scan can happen at a time.
	 */
	pthread_mutex_lock(&nftw_mutex);
	fn = pctx->fn;
	a_state.pbuf = pbuf;
	a_state.bufsiz = pctx->chunksize;
	a_state.bufpos = 0;
	a_state.fd = fd;
	a_state.srt = pctx->archive_sort_buf;
	a_state.srt_pos = 0;
	a_state.head = a_state.srt;
	a_state.pathlist_size = 0;

	while (fn) {
		struct stat sb;

		if (lstat(fn->filename, &sb) == -1) {
			log_msg(LOG_ERR, 1, "Ignoring %s.", fn->filename);
			fn = fn->next;
			continue;
		}

		a_state.arc_size = 0;
		a_state.fcount = 0;
		if (S_ISDIR(sb.st_mode)) {
			/*
			 * Depth-First scan, FTW_DEPTH, is needed to handle restoring
			 * all directory permissions correctly.
			 */
			err = nftw(fn->filename, add_pathname, 1024, FTW_PHYS | FTW_DEPTH);
		} else {
			int tflag;
			struct FTW ftwbuf;
			char *pos;

			if (S_ISLNK(sb.st_mode))
				tflag = FTW_SL;
			else
				tflag = FTW_F;

			/*
			 * Find out basename to mimic FTW.
			 */
			pos = strrchr(fn->filename, PATHSEP_CHAR);
			if (pos)
				ftwbuf.base = pos - fn->filename + 1;
			else
				ftwbuf.base = 0;
			add_pathname(fn->filename, &sb, tflag, &ftwbuf);
			a_state.arc_size = sb.st_size;
		}
		if (a_state.bufpos > 0) {
			ssize_t wrtn = Write(a_state.fd, a_state.pbuf, a_state.bufpos);
			if (wrtn < a_state.bufpos) {
				log_msg(LOG_ERR, 1, "Write failed.");
				close(fd);  unlink(tmpfile);
				return (-1);
			}
			a_state.bufpos = 0;
			a_state.pathlist_size += wrtn;
		}
		pctx->archive_size += a_state.arc_size;
		pctx->archive_members_count += a_state.fcount;
		fn = fn->next;
	}

	if (a_state.srt == NULL) {
		pctx->enable_archive_sort = 0;
	} else {
		log_msg(LOG_INFO, 0, "Sorting ...");
		a_state.srt->max = a_state.srt_pos - 1;
		qsort(a_state.srt->members, a_state.srt_pos, sizeof (member_entry_t), compare_members);
		pctx->archive_temp_size = a_state.pathlist_size;
	}
	pthread_mutex_unlock(&nftw_mutex);

	sbuf->st_size = pctx->archive_size;
	lseek(fd, 0, SEEK_SET);
	free(pbuf);
	sbuf->st_uid = geteuid();
	sbuf->st_gid = getegid();
	sbuf->st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

	arc = archive_write_new();
	if (!arc) {
		log_msg(LOG_ERR, 1, "Unable to create libarchive context.\n");
		close(fd);
		unlink(tmpfile);
		return (-1);
	}
	archive_write_set_format_pax_restricted(arc);
	archive_write_set_bytes_per_block(arc, 0);
	archive_write_open(arc, pctx, arc_open_callback,
			   creat_write_callback, creat_close_callback);
	pctx->archive_ctx = arc;
	pctx->archive_members_fd = fd;
	if (pctx->enable_archive_sort) {
		pctx->temp_mmap_len = TEMP_MMAP_SIZE;
		pctx->temp_mmap_buf = mmap(NULL, pctx->temp_mmap_len, PROT_READ,
					MAP_SHARED, pctx->archive_members_fd, 0);
		if (pctx->temp_mmap_buf == NULL) {
			log_msg(LOG_WARN, 1, "Unable to mmap pathlist file, switching to read().");
			pctx->temp_mmap_len = 0;
		}
	} else {
		pctx->temp_mmap_buf = NULL;
		pctx->temp_mmap_len = 0;
	}
	pctx->temp_mmap_pos = 0;
	pctx->arc_writing = 0;

	return (0);
}
示例#12
0
文件: load.c 项目: kacmem/zxtune
static int decrunch(struct list_head *head, FILE **f, char **s, int ttl)
{
    unsigned char b[1024];
    char *cmd;
    FILE *t;
    int fd, builtin, res;
    char *temp2, tmp[PATH_MAX];
    struct tmpfilename *temp;
    int headersize;

    cmd = NULL;
    builtin = res = 0;

    if (get_temp_dir(tmp, PATH_MAX) < 0)
	return 0;

    strncat(tmp, "xmp_XXXXXX", PATH_MAX);

    fseek(*f, 0, SEEK_SET);
    if ((headersize = fread(b, 1, 1024, *f)) < 100)	/* minimum valid file size */
	return 0;

#if defined __AMIGA__ && !defined __AROS__
    if (test_xfd(b, 1024)) {
	builtin = BUILTIN_XFD;
    } else
#endif

    if (b[0] == 'P' && b[1] == 'K' &&
	((b[2] == 3 && b[3] == 4) || (b[2] == '0' && b[3] == '0' &&
	b[4] == 'P' && b[5] == 'K' && b[6] == 3 && b[7] == 4))) {

	/* Zip */
	builtin = BUILTIN_ZIP;
    } else if (b[2] == '-' && b[3] == 'l' && b[4] == 'h') {
	/* LHa */
	builtin = BUILTIN_LHA;
    } else if (b[0] == 31 && b[1] == 139) {
	/* gzip */
	builtin = BUILTIN_GZIP;
    } else if (b[0] == 'B' && b[1] == 'Z' && b[2] == 'h') {
	/* bzip2 */
	builtin = BUILTIN_BZIP2;
    } else if (b[0] == 0xfd && b[3] == 'X' && b[4] == 'Z' && b[5] == 0x00) {
	/* xz */
	builtin = BUILTIN_XZ;
#if 0
    } else if (b[0] == 'Z' && b[1] == 'O' && b[2] == 'O' && b[3] == ' ') {
	/* zoo */
	builtin = BUILTIN_ZOO;
#endif
    } else if (b[0] == 'M' && b[1] == 'O' && b[2] == '3') {
	/* MO3 */
	cmd = "unmo3 -s \"%s\" STDOUT";
    } else if (b[0] == 31 && b[1] == 157) {
	/* compress */
	builtin = BUILTIN_COMPRESS;
    } else if (memcmp(b, "PP20", 4) == 0) {
	/* PowerPack */
	builtin = BUILTIN_PP;
    } else if (memcmp(b, "XPKF", 4) == 0 && memcmp(b + 8, "SQSH", 4) == 0) {
	/* SQSH */
	builtin = BUILTIN_SQSH;
    } else if (!memcmp(b, "Archive\0", 8)) {
	/* ArcFS */
	builtin = BUILTIN_ARCFS;
    } else if (memcmp(b, "ziRCONia", 8) == 0) {
	/* MMCMP */
	builtin = BUILTIN_MMCMP;
    } else if (memcmp(b, "MUSE", 4) == 0 && readmem32b(b + 4) == 0xdeadbeaf) {
	/* J2B MUSE */
	builtin = BUILTIN_MUSE;
    } else if (memcmp(b, "MUSE", 4) == 0 && readmem32b(b + 4) == 0xdeadbabe) {
	/* MOD2J2B MUSE */
	builtin = BUILTIN_MUSE;
    } else if (memcmp(b, "LZX", 3) == 0) {
	/* LZX */
	builtin = BUILTIN_LZX;
    } else if (memcmp(b, "Rar", 3) == 0) {
	/* rar */
	cmd = "unrar p -inul -xreadme -x*.diz -x*.nfo -x*.txt "
	    "-x*.exe -x*.com \"%s\"";
    } else if (memcmp(b, "S404", 4) == 0) {
	/* Stonecracker */
	builtin = BUILTIN_S404;
    } else if (test_oxm(*f) == 0) {
	/* oggmod */
	builtin = BUILTIN_OXM;
    }

    if (builtin == 0 && cmd == NULL && b[0] == 0x1a) {
	int x = b[1] & 0x7f;
	int i, flag = 0;
	long size;
	
	/* check file name */
	for (i = 0; i < 13; i++) {
	    if (b[2 + i] == 0) {
		if (i == 0)		/* name can't be empty */
		    flag = 1;
		break;
	    }
	    if (!isprint(b[2 + i])) {	/* name must be printable */
		flag = 1;
		break;
	    }
	}

	size = readmem32l(b + 15);	/* max file size is 512KB */
	if (size < 0 || size > 512 * 1024)
		flag = 1;

        if (flag == 0) {
	    if (x >= 1 && x <= 9 && x != 7) {
		/* Arc */
		builtin = BUILTIN_ARC;
	    } else if (x == 0x7f) {
		/* !Spark */
		builtin = BUILTIN_ARC;
	    }
	}
    }

    fseek(*f, 0, SEEK_SET);

    if (builtin == 0 && cmd == NULL)
	return 0;

#if defined ANDROID || defined __native_client__
    /* Don't use external helpers in android */
    if (cmd)
	return 0;
#endif

    D_(D_WARN "Depacking file... ");

    temp = calloc(sizeof (struct tmpfilename), 1);
    if (!temp) {
	D_(D_CRIT "calloc failed");
	return -1;
    }

    temp->name = strdup(tmp);
    if (temp->name == NULL || (fd = mkstemp(temp->name)) < 0) {
	D_(D_CRIT "failed");
	return -1;
    }

    list_add_tail(&temp->list, head);

    if ((t = fdopen(fd, "w+b")) == NULL) {
	D_(D_CRIT "failed");
	return -1;
    }

    if (cmd) {
#define BSIZE 0x4000
	int n;
	char line[1024], buf[BSIZE];
	FILE *p;

	snprintf(line, 1024, cmd, *s);

#ifdef WIN32
	/* Note: The _popen function returns an invalid file opaque, if
	 * used in a Windows program, that will cause the program to hang
	 * indefinitely. _popen works properly in a Console application.
	 * To create a Windows application that redirects input and output,
	 * read the section "Creating a Child Process with Redirected Input
	 * and Output" in the Win32 SDK. -- Mirko 
	 */
	if ((p = popen(line, "rb")) == NULL) {
#else
	/* Linux popen fails with "rb" */
	if ((p = popen(line, "r")) == NULL) {
#endif
	    D_(D_CRIT "failed");
	    fclose(t);
	    return -1;
	}
	while ((n = fread(buf, 1, BSIZE, p)) > 0)
	    fwrite(buf, 1, n, t);
	pclose (p);
    } else {
	switch (builtin) {
	case BUILTIN_PP:    
	    res = decrunch_pp(*f, t);
	    break;
	case BUILTIN_ARC:
	    res = decrunch_arc(*f, t);
	    break;
	case BUILTIN_ARCFS:
	    res = decrunch_arcfs(*f, t);
	    break;
	case BUILTIN_SQSH:    
	    res = decrunch_sqsh(*f, t);
	    break;
	case BUILTIN_MMCMP:    
	    res = decrunch_mmcmp(*f, t);
	    break;
	case BUILTIN_MUSE:    
	    res = decrunch_muse(*f, t);
	    break;
	case BUILTIN_LZX:    
	    res = decrunch_lzx(*f, t);
	    break;
	case BUILTIN_S404:
	    res = decrunch_s404(*f, t);
	    break;
	case BUILTIN_ZIP:
	    res = decrunch_zip(*f, t);
	    break;
	case BUILTIN_GZIP:
	    res = decrunch_gzip(*f, t);
	    break;
	case BUILTIN_COMPRESS:
	    res = decrunch_compress(*f, t);
	    break;
	case BUILTIN_BZIP2:
	    res = decrunch_bzip2(*f, t);
	    break;
	case BUILTIN_XZ:
	    res = decrunch_xz(*f, t);
	    break;
	case BUILTIN_LHA:
	    res = decrunch_lha(*f, t);
	    break;
#if 0
	case BUILTIN_ZOO:
	    res = decrunch_zoo(*f, t);
	    break;
#endif
	case BUILTIN_OXM:
	    res = decrunch_oxm(*f, t);
	    break;
#ifdef AMIGA
	case BUILTIN_XFD:
	    res = decrunch_xfd(*f, t);
	    break;
#endif
	}
    }

    if (res < 0) {
	D_(D_CRIT "failed");
	fclose(t);
	return -1;
    }

    D_(D_INFO "done");

    fclose(*f);
    *f = t;
 
    if (!--ttl) {
	    return -1;
    }
    
    temp2 = strdup(temp->name);
    res = decrunch(head, f, &temp->name, ttl);
    free(temp2);
    /* Mirko: temp is now deallocated in unlink_tempfiles()
     * not a problem, since unlink_tempfiles() is called after decrunch
     * in loader routines
     *
     * free(temp);
     */

    return res;
}


/*
 * Windows doesn't allow you to unlink an open file, so we changed the
 * temp file cleanup system to remove temporary files after we close it
 */
static void unlink_tempfiles(struct list_head *head)
{
	struct tmpfilename *li;
	struct list_head *tmp;

	/* can't use list_for_each when freeing the node! */
	for (tmp = head->next; tmp != head; ) {
		li = list_entry(tmp, struct tmpfilename, list);
		D_(D_INFO "unlink tmpfile %s", li->name);
		unlink(li->name);
		free(li->name);
		list_del(&li->list);
		tmp = tmp->next;
		free(li);
	}
}


int xmp_test_module(char *path, struct xmp_test_info *info)
{
	HIO_HANDLE *h;
	struct stat st;
	char buf[XMP_NAME_SIZE];
	int i;
	struct list_head tmpfiles_list;
	int ret = -XMP_ERROR_FORMAT;;

	if (stat(path, &st) < 0)
		return -XMP_ERROR_SYSTEM;

#ifndef _MSC_VER
	if (S_ISDIR(st.st_mode)) {
		errno = EISDIR;
		return -XMP_ERROR_SYSTEM;
	}
#endif

	if ((h = hio_open_file(path, "rb")) == NULL)
		return -XMP_ERROR_SYSTEM;

	INIT_LIST_HEAD(&tmpfiles_list);

	if (decrunch(&tmpfiles_list, &h->f, &path, DECRUNCH_MAX) < 0) {
		ret = -XMP_ERROR_DEPACK;
		goto err;
	}

	if (hio_stat(h, &st) < 0) {/* get size after decrunch */
		ret = -XMP_ERROR_DEPACK;
		goto err;
	}

	if (st.st_size < 256) {		/* set minimum valid module size */
		ret = -XMP_ERROR_FORMAT;
		goto err;
	}

	if (info != NULL) {
		*info->name = 0;	/* reset name prior to testing */
		*info->type = 0;	/* reset type prior to testing */
	}

	for (i = 0; format_loader[i] != NULL; i++) {
		fseek(h->f, 0, SEEK_SET);
		if (format_loader[i]->test(h, buf, 0) == 0) {
			int is_prowizard = 0;

			if (strcmp(format_loader[i]->name, "prowizard") == 0) {
				fseek(h->f, 0, SEEK_SET);
				pw_test_format(h->f, buf, 0, info);
				is_prowizard = 1;
			}

			fclose(h->f);

			unlink_tempfiles(&tmpfiles_list);
			if (info != NULL && !is_prowizard) {
				strncpy(info->name, buf, XMP_NAME_SIZE);
				strncpy(info->type, format_loader[i]->name,
							XMP_NAME_SIZE);
			}
			return 0;
		}
	}

    err:
	hio_close(h);
	unlink_tempfiles(&tmpfiles_list);
	return ret;
}
示例#13
0
    fprintf(stderr, "Failed to locate temporary directory\n");
    return NULL;
}

/* Generates a temporary filename, and creates a file of that name.
 * Caller is responsible for free()ing the string and unlink()ing the file
 * after use.
 */
static char* generate_temp_file(void) {
#ifdef WIN32
    const char sep = '\\';
#else
    const char sep = '/';
#endif
    char template[1024];
    const char *tempdir = get_temp_dir();
    if (tempdir == NULL) {
        return NULL;
    }
    if (snprintf(template, sizeof(template), "%s%cconfig_parse_test_XXXXXX",
                 tempdir, sep) >= sizeof(template)) {
        return NULL;
    }

    if (cb_mktemp(template) == NULL) {
        fprintf(stderr, "FATAL: failed to create temporary file: %s\n",
                strerror(errno));
        return NULL;
    }

    return strdup(template);
示例#14
0
static void get_stderr_file_path(char *path) {
    get_temp_dir(path);
    strcat(path, "/stderr-JiveLite.txt");
}
示例#15
0
void create_temp_dir() {
	(void)get_temp_dir();
}
示例#16
0
文件: send.c 项目: dscho/nmh
int
main (int argc, char **argv)
{
    int msgp = 0, distsw = 0, vecp;
    int isdf = 0, mime = 0;
    int msgnum, status;
    char *cp, *dfolder = NULL, *maildir = NULL;
    char buf[BUFSIZ], **ap, **argp, **arguments, *program;
    char *msgs[MAXARGS], **vec;
    struct msgs *mp;
    struct stat st;

    if (nmh_init(argv[0], 1)) { return 1; }

    arguments = getarguments (invo_name, argc, argv, 1);
    argp = arguments;

    vec = argsplit(postproc, &program, &vecp);

    vec[vecp++] = "-library";
    vec[vecp++] = getcpy (m_maildir (""));

    if ((cp = context_find ("fileproc"))) {
	vec[vecp++] = "-fileproc";
	vec[vecp++] = cp;
    }

    if ((cp = context_find ("mhlproc"))) {
	vec[vecp++] = "-mhlproc";
	vec[vecp++] = cp;
    }

    if ((cp = context_find ("credentials"))) {
	/* post doesn't read context so need to pass credentials. */
	vec[vecp++] = "-credentials";
	vec[vecp++] = cp;
    }

    while ((cp = *argp++)) {
	if (*cp == '-') {
	    switch (smatch (++cp, switches)) {
		case AMBIGSW: 
		    ambigsw (cp, switches);
		    done (1);
		case UNKWNSW: 
		    adios (NULL, "-%s unknown\n", cp);

		case HELPSW: 
		    snprintf (buf, sizeof(buf), "%s [file] [switches]", invo_name);
		    print_help (buf, switches, 1);
		    done (0);
		case VERSIONSW:
		    print_version(invo_name);
		    done (0);

		case DRAFTSW: 
		    msgs[msgp++] = draft;
		    continue;

		case DFOLDSW: 
		    if (dfolder)
			adios (NULL, "only one draft folder at a time!");
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    dfolder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp,
			    *cp != '@' ? TFOLDER : TSUBCWF);
		    continue;
		case DMSGSW: 
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    msgs[msgp++] = cp;
		    continue;
		case NDFLDSW: 
		    dfolder = NULL;
		    isdf = NOTOK;
		    continue;

		case PUSHSW: 
		    pushsw++;
		    continue;
		case NPUSHSW: 
		    pushsw = 0;
		    continue;

		case SPLITSW: 
		    if (!(cp = *argp++) || sscanf (cp, "%d", &splitsw) != 1)
			adios (NULL, "missing argument to %s", argp[-2]);
		    continue;

		case UNIQSW: 
		    unique++;
		    continue;
		case NUNIQSW: 
		    unique = 0;
		    continue;

		case FORWSW:
		    forwsw++;
		    continue;
		case NFORWSW:
		    forwsw = 0;
		    continue;

		case VERBSW: 
		    verbsw++;
		    vec[vecp++] = --cp;
		    continue;
		case NVERBSW:
		    verbsw = 0;
		    vec[vecp++] = --cp;
		    continue;

		case MIMESW:
		    mime++;
		    vec[vecp++] = --cp;
		    continue;
		case NMIMESW:
		    mime = 0;
		    vec[vecp++] = --cp;
		    continue;

		case DEBUGSW: 
		    debugsw++;	/* fall */
		case NFILTSW: 
		case FRMTSW: 
		case NFRMTSW: 
		case BITSTUFFSW:
		case NBITSTUFFSW:
		case MSGDSW: 
		case NMSGDSW: 
		case WATCSW: 
		case NWATCSW: 
		case SNOOPSW: 
		case SASLSW:
		case NOSASLSW:
		case TLSSW:
		case INITTLSSW:
		case NTLSSW:
		    vec[vecp++] = --cp;
		    continue;

		case ALIASW: 
		case FILTSW: 
		case WIDTHSW: 
		case CLIESW: 
		case SERVSW: 
		case SASLMECHSW:
		case SASLMXSSFSW:
		case USERSW:
		case PORTSW:
		case MTSSW:
		case MESSAGEIDSW:
		    vec[vecp++] = --cp;
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    vec[vecp++] = cp;
		    continue;
		
		case ATTACHSW:
		    advise(NULL, "The -attach switch is deprecated");
		    continue;
		case NOATTACHSW:
		    advise(NULL, "The -noattach switch is deprecated");
		    continue;

		case ATTACHFORMATSW:
		    advise(NULL, "The -attachformat switch is deprecated");
		    continue;
	    }
	} else {
	    msgs[msgp++] = cp;
	}
    }

    /*
     * check for "Aliasfile:" profile entry
     */
    if ((cp = context_find ("Aliasfile"))) {
	char *dp = NULL;

	for (ap = brkstring(dp = getcpy(cp), " ", "\n"); ap && *ap; ap++) {
	    vec[vecp++] = "-alias";
	    vec[vecp++] = *ap;
	}
    }

    if (dfolder == NULL) {
	if (msgp == 0) {
	    msgs[msgp++] = getcpy (m_draft (NULL, NULL, 1, &isdf));
	    if (stat (msgs[0], &st) == NOTOK)
		adios (msgs[0], "unable to stat draft file");
	    cp = concat ("Use \"", msgs[0], "\"? ", NULL);
	    for (status = LISTDSW; status != YESW;) {
		if (!(argp = getans (cp, anyl)))
		    done (1);
		switch (status = smatch (*argp, anyl)) {
		    case NOSW: 
			done (0);
		    case YESW: 
			break;
		    case LISTDSW: 
			showfile (++argp, msgs[0]);
			break;
		    default:
			advise (NULL, "say what?");
			break;
		}
	    }
	} else {
	    for (msgnum = 0; msgnum < msgp; msgnum++)
		msgs[msgnum] = getcpy (m_maildir (msgs[msgnum]));
	}
    } else {
	if (!context_find ("path"))
	    free (path ("./", TFOLDER));

	if (!msgp)
	    msgs[msgp++] = "cur";
	maildir = m_maildir (dfolder);

	if (chdir (maildir) == NOTOK)
	    adios (maildir, "unable to change directory to");

	/* read folder and create message structure */
	if (!(mp = folder_read (dfolder, 1)))
	    adios (NULL, "unable to read folder %s", dfolder);

	/* check for empty folder */
	if (mp->nummsg == 0)
	    adios (NULL, "no messages in %s", dfolder);

	/* parse all the message ranges/sequences and set SELECTED */
	for (msgnum = 0; msgnum < msgp; msgnum++)
	    if (!m_convert (mp, msgs[msgnum]))
		done (1);
	seq_setprev (mp);	/* set the previous-sequence */

	for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	    if (is_selected (mp, msgnum)) {
		msgs[msgp++] = getcpy (m_name (msgnum));
		unset_exists (mp, msgnum);
	    }
	}

	mp->msgflags |= SEQMOD;
	seq_save (mp);
    }

#ifdef WHATNOW
go_to_it:
#endif /* WHATNOW */

    if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
	if ((cp = context_find ("signature")) && *cp)
	    m_putenv ("SIGNATURE", cp);

    for (msgnum = 0; msgnum < msgp; msgnum++)
	if (stat (msgs[msgnum], &st) == NOTOK)
	    adios (msgs[msgnum], "unable to stat draft file");

    if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
	annotext = NULL;
    if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
	inplace = atoi (cp);
    if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
	altmsg = NULL;	/* used by dist interface - see below */

    if ((cp = getenv ("mhdist"))
	    && *cp
	    && (distsw = atoi (cp))
	    && altmsg) {
	vec[vecp++] = "-dist";
	if ((cp = m_mktemp2(altmsg, invo_name, NULL, NULL)) == NULL) {
	    adios(NULL, "unable to create temporary file in %s",
		  get_temp_dir());
	}
	distfile = getcpy (cp);
	(void) m_unlink(distfile);
	if (link (altmsg, distfile) == NOTOK) {
	    /* Cygwin with FAT32 filesystem produces EPERM. */
	    if (errno != EXDEV  &&  errno != EPERM
#ifdef EISREMOTE
		    && errno != EISREMOTE
#endif /* EISREMOTE */
		)
		adios (distfile, "unable to link %s to", altmsg);
	    free (distfile);
	    if ((cp = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
		adios(NULL, "unable to create temporary file in %s",
		      get_temp_dir());
	    }
	    distfile = getcpy (cp);
	    {
		int in, out;
		struct stat st;

		if ((in = open (altmsg, O_RDONLY)) == NOTOK)
		    adios (altmsg, "unable to open");
		fstat(in, &st);
		if ((out = creat (distfile, (int) st.st_mode & 0777)) == NOTOK)
		    adios (distfile, "unable to write");
		cpydata (in, out, altmsg, distfile);
		close (in);
		close (out);
	    }	
	}
    } else {
	distfile = NULL;
    }

    if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
	st.st_mtime = 0;
	st.st_dev = 0;
	st.st_ino = 0;
    }
    if (pushsw)
	push ();

    status = 0;
    closefds (3);

    for (msgnum = 0; msgnum < msgp; msgnum++) {
	switch (sendsbr (vec, vecp, program, msgs[msgnum], &st, 1)) {
	    case DONE: 
		done (++status);
	    case NOTOK: 
		status++;	/* fall */
	    case OK:
		break;
	}
    }

    context_save ();	/* save the context file */
    done (status);
    return 1;
}