Пример #1
0
static void
exp_pdu_file_open(exp_pdu_t *exp_pdu_tap_data)
{
    int   import_file_fd;
    char *tmpname, *capfile_name, *comment;
    int   err;

    /* Choose a random name for the temporary import buffer */
    import_file_fd = create_tempfile(&tmpname, "Wireshark_PDU_", NULL);
    capfile_name = g_strdup(tmpname);

    comment = g_strdup_printf("Dump of PDUs from %s", cfile.filename);
    err = exp_pdu_open(exp_pdu_tap_data, import_file_fd, comment);
    if (err != 0) {
        g_free(comment);
        cfile_dump_open_failure_alert_box(capfile_name ? capfile_name : "temporary file",
                                          err, WTAP_FILE_TYPE_SUBTYPE_PCAPNG);
        goto end;
    }

    /* Run the tap */
    cf_retap_packets(&cfile);

    err = exp_pdu_close(exp_pdu_tap_data);
    if (err!= 0) {
        cfile_close_failure_alert_box(capfile_name, err);
    }

    /* XXX: should this use the open_routine type in the cfile instead of WTAP_TYPE_AUTO? */
    if (cf_open(&cfile, capfile_name, WTAP_TYPE_AUTO, TRUE /* temporary file */, &err) != CF_OK) {
        /* cf_open() has put up a dialog box for the error */
        goto end;
    }

    switch (cf_read(&cfile, FALSE)) {
    case CF_READ_OK:
    case CF_READ_ERROR:
        /* Just because we got an error, that doesn't mean we were unable
        to read any of the file; we handle what we could get from the
        file. */
        break;

    case CF_READ_ABORTED:
        /* The user bailed out of re-reading the capture file; the
        capture file has been closed - just free the capture file name
        string and return (without changing the last containing
        directory). */
        break;
    }

end:
    g_free(capfile_name);
}
Пример #2
0
int run_test_forked_in_gdb(execute_context_t * ecp, test_results_t *testp){
	int status;
	char buffer[100] = "unittest_XXXXXX";
	char * tempfile = create_tempfile(buffer,testp->suite_name, testp->test_name);
	pid_t child_pid = run_test_forked_h1(ecp, testp,1);
	char bufferp[2000];

	sprintf(bufferp, "%s -x %s -q -p %u",getenvd("GDB", "gdb"),tempfile,  child_pid);
	system (bufferp);
	waitpid(child_pid, &status,0);
	unlink(buffer);
	return status;
}
Пример #3
0
/*Func: opt_q()
 * If the -q has been specified, this function is called
 * Read from file in argv[n]; n is filecount[lq|cq]
 * Format the input and put the info. in temp file
 * Read from temp into arch
 */
void opt_q(int argc, char **argv,int arch, int *filecount, int *fcalled, file *info){
	int tempfile = 0;
	for((*fcalled) = 0; (*fcalled)<filecount[1];++(*fcalled)){
		tempfile = 0;
		read_header(argc,argv,filecount, 0, fcalled,info );
		tempfile = create_tempfile();
		write_file_header(tempfile, info);
		write_file_content(tempfile, info);
		all_in_arch(tempfile,arch,fcalled ,info);
		close(tempfile);
	}
	(*fcalled)=0;
	return ;
}
Пример #4
0
/* Make sure errno contains a meaningful value on error */
static int lock_file(struct lock_file *lk, const char *path, int flags)
{
	int fd;
	struct strbuf filename = STRBUF_INIT;

	strbuf_addstr(&filename, path);
	if (!(flags & LOCK_NO_DEREF))
		resolve_symlink(&filename);

	strbuf_addstr(&filename, LOCK_SUFFIX);
	fd = create_tempfile(&lk->tempfile, filename.buf);
	strbuf_release(&filename);
	return fd;
}
Пример #5
0
static void
followFileOpen(
  follow_t *fp
  )
{
  int   fd;
  char *tempfilep;

  if (fp->type == type_TCP && data_out_file != NULL)
  {
    followExit("Only one TCP stream can be followed at a time.");
  }

  followFileClose(fp);

  fd = create_tempfile(&tempfilep, "follow");
  if (fd == -1)
  {
    followExit("Error creating temp file.");
  }

  fp->filenamep = g_strdup(tempfilep);
  if (fp->filenamep == NULL)
  {
    ws_close(fd);
    ws_unlink(tempfilep);
    followExit("Error duping temp file name.");
  }

  fp->filep = fdopen(fd, "w+b");
  if (fp->filep == NULL)
  {
    ws_close(fd);
    ws_unlink(fp->filenamep);
    g_free(fp->filenamep);
    fp->filenamep = NULL;
    followExit("Error opening temp file stream.");
  }

  if (fp->type == type_TCP)
  {
    data_out_file = fp->filep;
  }
}
Пример #6
0
void ImportTextDialog::convertTextFile() {
    int import_file_fd;
    char *tmpname;
    int err;

    capfile_name_.clear();
    /* Choose a random name for the temporary import buffer */
    import_file_fd = create_tempfile(&tmpname, "import");
    capfile_name_.append(tmpname);

    import_info_.wdh = wtap_dump_fdopen(import_file_fd, WTAP_FILE_TYPE_SUBTYPE_PCAP, import_info_.encapsulation, import_info_.max_frame_length, FALSE, &err);
    qDebug() << capfile_name_ << ":" << import_info_.wdh << import_info_.encapsulation << import_info_.max_frame_length;
    if (import_info_.wdh == NULL) {
        open_failure_alert_box(capfile_name_.toUtf8().constData(), err, TRUE);
        fclose(import_info_.import_text_file);
        setResult(QDialog::Rejected);
        return;
    }

    text_import_setup(&import_info_);

    text_importin = import_info_.import_text_file;

    text_importlex();

    text_import_cleanup();

    if (fclose(import_info_.import_text_file))
    {
        read_failure_alert_box(import_info_.import_text_filename, errno);
    }

    if (!wtap_dump_close(import_info_.wdh, &err))
    {
        write_failure_alert_box(capfile_name_.toUtf8().constData(), err);
    }
}
Пример #7
0
void opt_d(int argc, char **argv,int *arch, int *filecount, int *fcalled, file *info){
	int fbyte_max=1;
	int fbyte=0;
	int size = 0;
	int tsize = 0;
	int tempfile=0;
	int temparch =0;
	char cur_name[16];
	char *null_cur_name;
	char *null_info_name;
	char *str_buf;
	struct stat archinfo;
	struct stat temparch_info;


	fstat((*arch),&archinfo);

	temparch = open_file("temp_arch",1);

	fbyte_max = archinfo.st_size;
	//for fcalled goes here
	fbyte = 0;
	lseek((*arch),8,SEEK_SET);
	read_filename(argv,filecount,4,fcalled,info);

	for(fbyte=0; fbyte < fbyte_max; ){
		read((*arch),cur_name,16);
		null_cur_name = null_str(cur_name,16);
		null_cur_name = shrt_str(null_cur_name);
		null_info_name= null_str(info->name,16);
		null_info_name = shrt_str(null_info_name);

		(fbyte) += 60+atoi(info->size);

		if(fbyte < fbyte_max){
			if(!strcmp(null_cur_name,null_info_name)){//equal
				iter_arch((*arch), &fbyte, info);
				(fbyte) -= 60+atoi(info->size);
			}else{
				tempfile = 0;
				put_header((*arch), info);
				lseek((*arch),2,SEEK_CUR);

				/*printf("\ninfo->name: %.16s\n",info->name);
				  printf("cur name: %.16s\n",cur_name);
				  printf("info->time: %.12s\n",info->time);
				  printf("info->uid: %.6s\n",info->uid);
				  printf("info->gid: %.6s\n",info->gid);
				  printf("info->mode: %.8s\n",info->mode);
				  printf("info->size: %.10s\n",info->size);
				  */

				//so now the header are read correctly
				//Time to put info in files
				tempfile = create_tempfile();
				write_file_header2(tempfile,cur_name,info);
				info->desc = (*arch);
				write_file_content(tempfile,info);
				all_in_arch(tempfile,temparch,fcalled,info);

				if(tsize%2!=0){
					write(temparch,"\n",1);
				}

				(*fcalled)++;
				close(tempfile);
				if(atoi(info->size)%2!=0)
					lseek((*arch),1,SEEK_CUR);

			}
		}
	}
	//FIXME: the temp_arch has the correct info but when copy to arch itself has wrong info.	
	fstat(temparch,&temparch_info);
	size = temparch_info.st_size;
	printf("temparch.size: %d\n",size);
	str_buf = malloc(sizeof(char)*size);
	read(temparch,str_buf,size);
	//ftruncate((*arch),(sizeof(char))*size);
	lseek((*arch),0,SEEK_SET);
	write((*arch),str_buf,size);
	free(str_buf);
	close(temparch);
	//remove("temp_arch");
}
Пример #8
0
static void
exp_pdu_file_open(exp_pdu_t *exp_pdu_tap_data)
{
    int   import_file_fd;
    char *tmpname, *capfile_name;
    int   err;

    /* pcapng defs */
    wtapng_section_t            *shb_hdr;
    wtapng_iface_descriptions_t *idb_inf;
    wtapng_if_descr_t            int_data;
    GString                     *os_info_str;
    char                        *appname;

    /* Choose a random name for the temporary import buffer */
    import_file_fd = create_tempfile(&tmpname, "Wireshark_PDU_");
    capfile_name = g_strdup(tmpname);

    /* Create data for SHB  */
    os_info_str = g_string_new("");
    get_os_version_info(os_info_str);

    appname = g_strdup_printf("Wireshark %s", get_ws_vcs_version_info());

    shb_hdr = g_new(wtapng_section_t,1);
    shb_hdr->section_length = -1;
    /* options */
    shb_hdr->opt_comment    = g_strdup_printf("Dump of PDUs from %s", cfile.filename);
    shb_hdr->shb_hardware   = NULL;                    /* UTF-8 string containing the
                                                       * description of the hardware used to create this section.
                                                       */
    shb_hdr->shb_os         = os_info_str->str;        /* UTF-8 string containing the name
                                                       * of the operating system used to create this section.
                                                       */
    g_string_free(os_info_str, FALSE);                /* The actual string is not freed */
    shb_hdr->shb_user_appl  = appname;                /* UTF-8 string containing the name
                                                       *  of the application used to create this section.
                                                       */


    /* Create fake IDB info */
    idb_inf = g_new(wtapng_iface_descriptions_t,1);
    idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));

    /* create the fake interface data */
    int_data.wtap_encap            = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
    int_data.time_units_per_second = 1000000; /* default microsecond resolution */
    int_data.link_type             = wtap_wtap_encap_to_pcap_encap(WTAP_ENCAP_WIRESHARK_UPPER_PDU);
    int_data.snap_len              = WTAP_MAX_PACKET_SIZE;
    int_data.if_name               = g_strdup("Fake IF, PDU->Export");
    int_data.opt_comment           = NULL;
    int_data.if_description        = NULL;
    int_data.if_speed              = 0;
    int_data.if_tsresol            = 6;
    int_data.if_filter_str         = NULL;
    int_data.bpf_filter_len        = 0;
    int_data.if_filter_bpf_bytes   = NULL;
    int_data.if_os                 = NULL;
    int_data.if_fcslen             = -1;
    int_data.num_stat_entries      = 0;          /* Number of ISB:s */
    int_data.interface_statistics  = NULL;

    g_array_append_val(idb_inf->interface_data, int_data);

    exp_pdu_tap_data->wdh = wtap_dump_fdopen_ng(import_file_fd, WTAP_FILE_TYPE_SUBTYPE_PCAPNG, WTAP_ENCAP_WIRESHARK_UPPER_PDU, WTAP_MAX_PACKET_SIZE, FALSE, shb_hdr, idb_inf, &err);
    if (exp_pdu_tap_data->wdh == NULL) {
        open_failure_alert_box(capfile_name, err, TRUE);
        goto end;
    }


    /* Run the tap */
    cf_retap_packets(&cfile);


    if (!wtap_dump_close(exp_pdu_tap_data->wdh, &err)) {
        write_failure_alert_box(capfile_name, err);
    }

    remove_tap_listener(exp_pdu_tap_data);

    /* XXX: should this use the open_routine type in the cfile instead of WTAP_TYPE_AUTO? */
    if (cf_open(&cfile, capfile_name, WTAP_TYPE_AUTO, TRUE /* temporary file */, &err) != CF_OK) {
        open_failure_alert_box(capfile_name, err, FALSE);
        goto end;
    }

    switch (cf_read(&cfile, FALSE)) {
    case CF_READ_OK:
    case CF_READ_ERROR:
    /* Just because we got an error, that doesn't mean we were unable
       to read any of the file; we handle what we could get from the
       file. */
    break;

    case CF_READ_ABORTED:
    /* The user bailed out of re-reading the capture file; the
       capture file has been closed - just free the capture file name
       string and return (without changing the last containing
       directory). */
    break;
    }

end:
    g_free(capfile_name);
    g_free(shb_hdr);
    g_free(appname);
}
Пример #9
0
/*
 * Write the packed refs from the current snapshot to the packed-refs
 * tempfile, incorporating any changes from `updates`. `updates` must
 * be a sorted string list whose keys are the refnames and whose util
 * values are `struct ref_update *`. On error, rollback the tempfile,
 * write an error message to `err`, and return a nonzero value.
 *
 * The packfile must be locked before calling this function and will
 * remain locked when it is done.
 */
static int write_with_updates(struct packed_ref_store *refs,
			      struct string_list *updates,
			      struct strbuf *err)
{
	struct ref_iterator *iter = NULL;
	size_t i;
	int ok;
	FILE *out;
	struct strbuf sb = STRBUF_INIT;
	char *packed_refs_path;

	if (!is_lock_file_locked(&refs->lock))
		die("BUG: write_with_updates() called while unlocked");

	/*
	 * If packed-refs is a symlink, we want to overwrite the
	 * symlinked-to file, not the symlink itself. Also, put the
	 * staging file next to it:
	 */
	packed_refs_path = get_locked_file_path(&refs->lock);
	strbuf_addf(&sb, "%s.new", packed_refs_path);
	free(packed_refs_path);
	refs->tempfile = create_tempfile(sb.buf);
	if (!refs->tempfile) {
		strbuf_addf(err, "unable to create file %s: %s",
			    sb.buf, strerror(errno));
		strbuf_release(&sb);
		return -1;
	}
	strbuf_release(&sb);

	out = fdopen_tempfile(refs->tempfile, "w");
	if (!out) {
		strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
			    strerror(errno));
		goto error;
	}

	if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
		goto write_error;

	/*
	 * We iterate in parallel through the current list of refs and
	 * the list of updates, processing an entry from at least one
	 * of the lists each time through the loop. When the current
	 * list of refs is exhausted, set iter to NULL. When the list
	 * of updates is exhausted, leave i set to updates->nr.
	 */
	iter = packed_ref_iterator_begin(&refs->base, "",
					 DO_FOR_EACH_INCLUDE_BROKEN);
	if ((ok = ref_iterator_advance(iter)) != ITER_OK)
		iter = NULL;

	i = 0;

	while (iter || i < updates->nr) {
		struct ref_update *update = NULL;
		int cmp;

		if (i >= updates->nr) {
			cmp = -1;
		} else {
			update = updates->items[i].util;

			if (!iter)
				cmp = +1;
			else
				cmp = strcmp(iter->refname, update->refname);
		}

		if (!cmp) {
			/*
			 * There is both an old value and an update
			 * for this reference. Check the old value if
			 * necessary:
			 */
			if ((update->flags & REF_HAVE_OLD)) {
				if (is_null_oid(&update->old_oid)) {
					strbuf_addf(err, "cannot update ref '%s': "
						    "reference already exists",
						    update->refname);
					goto error;
				} else if (oidcmp(&update->old_oid, iter->oid)) {
					strbuf_addf(err, "cannot update ref '%s': "
						    "is at %s but expected %s",
						    update->refname,
						    oid_to_hex(iter->oid),
						    oid_to_hex(&update->old_oid));
					goto error;
				}
			}

			/* Now figure out what to use for the new value: */
			if ((update->flags & REF_HAVE_NEW)) {
				/*
				 * The update takes precedence. Skip
				 * the iterator over the unneeded
				 * value.
				 */
				if ((ok = ref_iterator_advance(iter)) != ITER_OK)
					iter = NULL;
				cmp = +1;
			} else {
				/*
				 * The update doesn't actually want to
				 * change anything. We're done with it.
				 */
				i++;
				cmp = -1;
			}
		} else if (cmp > 0) {
			/*
			 * There is no old value but there is an
			 * update for this reference. Make sure that
			 * the update didn't expect an existing value:
			 */
			if ((update->flags & REF_HAVE_OLD) &&
			    !is_null_oid(&update->old_oid)) {
				strbuf_addf(err, "cannot update ref '%s': "
					    "reference is missing but expected %s",
					    update->refname,
					    oid_to_hex(&update->old_oid));
				goto error;
			}
		}

		if (cmp < 0) {
			/* Pass the old reference through. */

			struct object_id peeled;
			int peel_error = ref_iterator_peel(iter, &peeled);

			if (write_packed_entry(out, iter->refname,
					       iter->oid,
					       peel_error ? NULL : &peeled))
				goto write_error;

			if ((ok = ref_iterator_advance(iter)) != ITER_OK)
				iter = NULL;
		} else if (is_null_oid(&update->new_oid)) {
			/*
			 * The update wants to delete the reference,
			 * and the reference either didn't exist or we
			 * have already skipped it. So we're done with
			 * the update (and don't have to write
			 * anything).
			 */
			i++;
		} else {
			struct object_id peeled;
			int peel_error = peel_object(&update->new_oid,
						     &peeled);

			if (write_packed_entry(out, update->refname,
					       &update->new_oid,
					       peel_error ? NULL : &peeled))
				goto write_error;

			i++;
		}
	}

	if (ok != ITER_DONE) {
		strbuf_addstr(err, "unable to write packed-refs file: "
			      "error iterating over old contents");
		goto error;
	}

	if (close_tempfile_gently(refs->tempfile)) {
		strbuf_addf(err, "error closing file %s: %s",
			    get_tempfile_path(refs->tempfile),
			    strerror(errno));
		strbuf_release(&sb);
		delete_tempfile(&refs->tempfile);
		return -1;
	}

	return 0;

write_error:
	strbuf_addf(err, "error writing to %s: %s",
		    get_tempfile_path(refs->tempfile), strerror(errno));

error:
	if (iter)
		ref_iterator_abort(iter);

	delete_tempfile(&refs->tempfile);
	return -1;
}
Пример #10
0
static int curl_download_internal(struct dload_payload *payload,
		const char *localpath, char **final_file, char **final_url)
{
	int ret = -1;
	FILE *localf = NULL;
	char *effective_url;
	char hostname[HOSTNAME_SIZE];
	char error_buffer[CURL_ERROR_SIZE] = {0};
	struct stat st;
	long timecond, remote_time = -1;
	double remote_size, bytes_dl;
	struct sigaction orig_sig_pipe, orig_sig_int;
	/* shortcut to our handle within the payload */
	alpm_handle_t *handle = payload->handle;
	CURL *curl = get_libcurl_handle(handle);
	handle->pm_errno = 0;

	/* make sure these are NULL */
	FREE(payload->tempfile_name);
	FREE(payload->destfile_name);
	FREE(payload->content_disp_name);

	payload->tempfile_openmode = "wb";
	if(!payload->remote_name) {
		STRDUP(payload->remote_name, get_filename(payload->fileurl),
				RET_ERR(handle, ALPM_ERR_MEMORY, -1));
	}
	if(curl_gethost(payload->fileurl, hostname, sizeof(hostname)) != 0) {
		_alpm_log(handle, ALPM_LOG_ERROR, _("url '%s' is invalid\n"), payload->fileurl);
		RET_ERR(handle, ALPM_ERR_SERVER_BAD_URL, -1);
	}

	if(payload->remote_name && strlen(payload->remote_name) > 0 &&
			strcmp(payload->remote_name, ".sig") != 0) {
		payload->destfile_name = get_fullpath(localpath, payload->remote_name, "");
		payload->tempfile_name = get_fullpath(localpath, payload->remote_name, ".part");
		if(!payload->destfile_name || !payload->tempfile_name) {
			goto cleanup;
		}
	} else {
		/* URL doesn't contain a filename, so make a tempfile. We can't support
		 * resuming this kind of download; partial transfers will be destroyed */
		payload->unlink_on_fail = 1;

		localf = create_tempfile(payload, localpath);
		if(localf == NULL) {
			goto cleanup;
		}
	}

	curl_set_handle_opts(payload, curl, error_buffer);

	if(localf == NULL) {
		localf = fopen(payload->tempfile_name, payload->tempfile_openmode);
		if(localf == NULL) {
			handle->pm_errno = ALPM_ERR_RETRIEVE;
			_alpm_log(handle, ALPM_LOG_ERROR,
					_("could not open file %s: %s\n"),
					payload->tempfile_name, strerror(errno));
			goto cleanup;
		}
	}

	_alpm_log(handle, ALPM_LOG_DEBUG,
			"opened tempfile for download: %s (%s)\n", payload->tempfile_name,
			payload->tempfile_openmode);

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, localf);

	/* Ignore any SIGPIPE signals. With libcurl, these shouldn't be happening,
	 * but better safe than sorry. Store the old signal handler first. */
	mask_signal(SIGPIPE, SIG_IGN, &orig_sig_pipe);
	mask_signal(SIGINT, &inthandler, &orig_sig_int);

	/* perform transfer */
	payload->curlerr = curl_easy_perform(curl);
	_alpm_log(handle, ALPM_LOG_DEBUG, "curl returned error %d from transfer\n",
			payload->curlerr);

	/* disconnect relationships from the curl handle for things that might go out
	 * of scope, but could still be touched on connection teardown.  This really
	 * only applies to FTP transfers. */
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, (char *)NULL);

	/* was it a success? */
	switch(payload->curlerr) {
		case CURLE_OK:
			/* get http/ftp response code */
			_alpm_log(handle, ALPM_LOG_DEBUG, "response code: %ld\n", payload->respcode);
			if(payload->respcode >= 400) {
				payload->unlink_on_fail = 1;
				/* non-translated message is same as libcurl */
				snprintf(error_buffer, sizeof(error_buffer),
						"The requested URL returned error: %ld", payload->respcode);
				_alpm_log(handle, ALPM_LOG_ERROR,
						_("failed retrieving file '%s' from %s : %s\n"),
						payload->remote_name, hostname, error_buffer);
				goto cleanup;
			}
			break;
		case CURLE_ABORTED_BY_CALLBACK:
			/* handle the interrupt accordingly */
			if(dload_interrupted == ABORT_OVER_MAXFILESIZE) {
				payload->curlerr = CURLE_FILESIZE_EXCEEDED;
				handle->pm_errno = ALPM_ERR_LIBCURL;
				/* use the 'size exceeded' message from libcurl */
				_alpm_log(handle, ALPM_LOG_ERROR,
						_("failed retrieving file '%s' from %s : %s\n"),
						payload->remote_name, hostname,
						curl_easy_strerror(CURLE_FILESIZE_EXCEEDED));
			}
			goto cleanup;
		default:
			/* delete zero length downloads */
			if(fstat(fileno(localf), &st) == 0 && st.st_size == 0) {
				payload->unlink_on_fail = 1;
			}
			if(!payload->errors_ok) {
				handle->pm_errno = ALPM_ERR_LIBCURL;
				_alpm_log(handle, ALPM_LOG_ERROR,
						_("failed retrieving file '%s' from %s : %s\n"),
						payload->remote_name, hostname, error_buffer);
			} else {
				_alpm_log(handle, ALPM_LOG_DEBUG,
						"failed retrieving file '%s' from %s : %s\n",
						payload->remote_name, hostname, error_buffer);
			}
			goto cleanup;
	}

	/* retrieve info about the state of the transfer */
	curl_easy_getinfo(curl, CURLINFO_FILETIME, &remote_time);
	curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &remote_size);
	curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &bytes_dl);
	curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &timecond);
	curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);

	if(final_url != NULL) {
		*final_url = effective_url;
	}

	/* time condition was met and we didn't download anything. we need to
	 * clean up the 0 byte .part file that's left behind. */
	if(timecond == 1 && DOUBLE_EQ(bytes_dl, 0)) {
		_alpm_log(handle, ALPM_LOG_DEBUG, "file met time condition\n");
		ret = 1;
		unlink(payload->tempfile_name);
		goto cleanup;
	}

	/* remote_size isn't necessarily the full size of the file, just what the
	 * server reported as remaining to download. compare it to what curl reported
	 * as actually being transferred during curl_easy_perform() */
	if(!DOUBLE_EQ(remote_size, -1) && !DOUBLE_EQ(bytes_dl, -1) &&
			!DOUBLE_EQ(bytes_dl, remote_size)) {
		handle->pm_errno = ALPM_ERR_RETRIEVE;
		_alpm_log(handle, ALPM_LOG_ERROR, _("%s appears to be truncated: %jd/%jd bytes\n"),
				payload->remote_name, (intmax_t)bytes_dl, (intmax_t)remote_size);
		goto cleanup;
	}

	if (payload->trust_remote_name) {
		if(payload->content_disp_name) {
			/* content-disposition header has a better name for our file */
			free(payload->destfile_name);
			payload->destfile_name = get_fullpath(localpath, payload->content_disp_name, "");
		} else {
			const char *effective_filename = strrchr(effective_url, '/');
			if(effective_filename && strlen(effective_filename) > 2) {
				effective_filename++;

				/* if destfile was never set, we wrote to a tempfile. even if destfile is
				 * set, we may have followed some redirects and the effective url may
				 * have a better suggestion as to what to name our file. in either case,
				 * refactor destfile to this newly derived name. */
				if(!payload->destfile_name || strcmp(effective_filename,
							strrchr(payload->destfile_name, '/') + 1) != 0) {
					free(payload->destfile_name);
					payload->destfile_name = get_fullpath(localpath, effective_filename, "");
				}
			}
		}
	}

	ret = 0;

cleanup:
	if(localf != NULL) {
		fclose(localf);
		utimes_long(payload->tempfile_name, remote_time);
	}

	if(ret == 0) {
		const char *realname = payload->tempfile_name;
		if(payload->destfile_name) {
			realname = payload->destfile_name;
			if(rename(payload->tempfile_name, payload->destfile_name)) {
				_alpm_log(handle, ALPM_LOG_ERROR, _("could not rename %s to %s (%s)\n"),
						payload->tempfile_name, payload->destfile_name, strerror(errno));
				ret = -1;
			}
		}
		if(ret != -1 && final_file) {
			STRDUP(*final_file, strrchr(realname, '/') + 1,
					RET_ERR(handle, ALPM_ERR_MEMORY, -1));
		}
	}

	if((ret == -1 || dload_interrupted) && payload->unlink_on_fail &&
			payload->tempfile_name) {
		unlink(payload->tempfile_name);
	}

	/* restore the old signal handlers */
	unmask_signal(SIGINT, &orig_sig_int);
	unmask_signal(SIGPIPE, &orig_sig_pipe);
	/* if we were interrupted, trip the old handler */
	if(dload_interrupted) {
		raise(SIGINT);
	}

	return ret;
}
Пример #11
0
/*
 * Opens an .xml file with Trace data formated according to 3GPP TS 32.423 and converts it to
 * an "Exported PDU type file with the entire xml file as the first "packet" appending the
 * raw messages as subsequent packages to be dissected by wireshark.
 */
static wtap_open_return_val
create_temp_pcapng_file(wtap *wth, int *err, gchar **err_info, nettrace_3gpp_32_423_file_info_t *file_info)
{
	int import_file_fd;
	wtap_dumper* wdh_exp_pdu;
	int   exp_pdu_file_err;

	/* pcapng defs */
	wtapng_section_t            *shb_hdr;
	wtapng_iface_descriptions_t *idb_inf;
	wtapng_if_descr_t            int_data;
	GString                     *os_info_str;
	char                        *appname;
	gint64 file_size;
	int packet_size;
	guint8 *packet_buf;
	int wrt_err;
	gchar *wrt_err_info;
	struct wtap_pkthdr phdr;

	gboolean do_random = FALSE;
	char *curr_pos, *next_pos;

	import_file_fd = create_tempfile(&(file_info->tmpname), "Wireshark_PDU_");

	/* Now open a file and dump to it */
	/* Create data for SHB  */
	os_info_str = g_string_new("");
	get_os_version_info(os_info_str);

	appname = g_strdup_printf("Wireshark %s", get_ws_vcs_version_info());

	shb_hdr = g_new(wtapng_section_t, 1);
	shb_hdr->section_length = -1;
	/* options */
	shb_hdr->opt_comment = g_strdup_printf("File converted to Exported PDU format during opening");
	/*
	* UTF-8 string containing the description of the hardware used to create
	* this section.
	*/
	shb_hdr->shb_hardware = NULL;
	/*
	* UTF-8 string containing the name of the operating system used to create
	* this section.
	*/
	shb_hdr->shb_os = g_string_free(os_info_str, FALSE);
	/*
	* UTF-8 string containing the name of the application used to create
	* this section.
	*/
	shb_hdr->shb_user_appl = appname;

	/* Create fake IDB info */
	idb_inf = g_new(wtapng_iface_descriptions_t, 1);
	idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));

	/* create the fake interface data */
	int_data.wtap_encap = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
	int_data.time_units_per_second = 1000000; /* default microsecond resolution */
	int_data.link_type = wtap_wtap_encap_to_pcap_encap(WTAP_ENCAP_WIRESHARK_UPPER_PDU);
	int_data.snap_len = WTAP_MAX_PACKET_SIZE;
	int_data.if_name = g_strdup("Fake IF");
	int_data.opt_comment = NULL;
	int_data.if_description = NULL;
	int_data.if_speed = 0;
	int_data.if_tsresol = 6;
	int_data.if_filter_str = NULL;
	int_data.bpf_filter_len = 0;
	int_data.if_filter_bpf_bytes = NULL;
	int_data.if_os = NULL;
	int_data.if_fcslen = -1;
	int_data.num_stat_entries = 0;          /* Number of ISB:s */
	int_data.interface_statistics = NULL;

	g_array_append_val(idb_inf->interface_data, int_data);

	wdh_exp_pdu = wtap_dump_fdopen_ng(import_file_fd, WTAP_FILE_TYPE_SUBTYPE_PCAPNG, WTAP_ENCAP_WIRESHARK_UPPER_PDU,
					  WTAP_MAX_PACKET_SIZE, FALSE, shb_hdr, idb_inf, NULL, &exp_pdu_file_err);
	if (wdh_exp_pdu == NULL) {
		return WTAP_OPEN_ERROR;
	}

	g_free(shb_hdr);
	g_free(appname);

	/* OK we've opend a new pcap-ng file and written the headers, time to do the packets, strt by finding the file size */

	if ((file_size = wtap_file_size(wth, err)) == -1)
		return WTAP_OPEN_ERROR;

	if (file_size > MAX_FILE_SIZE) {
		/*
		* Don't blow up trying to allocate space for an
		* immensely-large file.
		*/
		*err = WTAP_ERR_BAD_FILE;
		*err_info = g_strdup_printf("mime_file: File has %" G_GINT64_MODIFIER "d-byte packet, bigger than maximum of %u",
			file_size, MAX_FILE_SIZE);
		return WTAP_OPEN_ERROR;
	}
	packet_size = (int)file_size;
	/* Allocate the packet buffer
	* (the whole file + Exported PDU tag "protocol" and
	* the string "xml" + 1 filler to end on 4 byte boundary for the tag
	* + End of options 4 bytes
	*/
	/* XXX add the length of exported bdu tag(s) here */
	packet_buf = (guint8 *)g_malloc(packet_size + 12);

	packet_buf[0] = 0;
	packet_buf[1] = 12; /* EXP_PDU_TAG_PROTO_NAME */
	packet_buf[2] = 0;
	packet_buf[3] = 4;
	packet_buf[4] = 0x78; /* "x" */
	packet_buf[5] = 0x6d; /* "m" */
	packet_buf[6] = 0x6c; /* "l" */
	packet_buf[7] = 0;
	/* End of options */
	packet_buf[8] = 0;
	packet_buf[9] = 0;
	packet_buf[10] = 0;
	packet_buf[11] = 0;


	if (!wtap_read_bytes(wth->fh, packet_buf + 12, packet_size, &wrt_err, &wrt_err_info)){
		return WTAP_OPEN_ERROR;
	}

	/* Create the packet header */
	memset(&phdr, 0, sizeof(struct wtap_pkthdr));
	phdr.rec_type = REC_TYPE_PACKET;
	phdr.presence_flags = 0; /* yes, we have no bananas^Wtime stamp */

	phdr.caplen = packet_size + 12;
	phdr.len = packet_size + 12;

	phdr.ts.secs = 0;
	phdr.ts.nsecs = 0;

	/* XXX: report errors! */
	if (!wtap_dump(wdh_exp_pdu, &phdr, packet_buf, &wrt_err, &wrt_err_info)) {
		switch (wrt_err) {

		case WTAP_ERR_UNWRITABLE_REC_DATA:
			g_free(wrt_err_info);
			break;

		default:
			break;
		}
		g_free(packet_buf);
		return WTAP_OPEN_ERROR;
	}

	/* Advance *packet_buf to point at the raw file data */
	curr_pos = packet_buf + 12;
	/* Lets add the raw messages as packets after the main "packet" with the whole file */
	while ((curr_pos = strstr(curr_pos, "<msg")) != NULL){
		wtap_open_return_val temp_val;

		curr_pos = curr_pos + 4;
		next_pos = strstr(curr_pos, "</msg>");
		if (!next_pos){
			/* Somethings wrong, bail out */
			break;
		}
		next_pos = next_pos + 6;
		/* Do we have a raw msg?) */
		curr_pos = strstr(curr_pos, "<rawMsg");
		if (!curr_pos){
			/* No rawMsg, continue */
			curr_pos = next_pos;
			continue;
		}
		curr_pos = curr_pos + 7;
		/* Add the raw msg*/
		temp_val = write_packet_data(wdh_exp_pdu, &phdr, &wrt_err, &wrt_err_info, curr_pos);
		if (temp_val != WTAP_OPEN_MINE){
			g_free(packet_buf);
			return temp_val;
		}
		curr_pos = next_pos;
	}

	/* Close the written file*/
	if (!wtap_dump_close(wdh_exp_pdu, err)){
		g_free(packet_buf);
		return WTAP_OPEN_ERROR;
	}

	g_free(packet_buf);
	/* Now open the file for reading */

	/* Find out if random read was requested */
	if (wth->random_fh){
		do_random = TRUE;
	}
	file_info->wth_tmp_file =
		wtap_open_offline(file_info->tmpname, WTAP_TYPE_AUTO, err, err_info, do_random);

	if (!file_info->wth_tmp_file){
		return WTAP_OPEN_ERROR;
	}

	return WTAP_OPEN_MINE;
}
Пример #12
0
/*
 * install --
 *	build a path name and install the file
 */
static void
install(const char *from_name, const char *to_name, u_long fset, u_long fclr,
	u_int flags)
{
	struct stat from_sb, temp_sb, to_sb;
	struct utimbuf utb;
	int devnull, files_match, from_fd, serrno, target;
	int tempcopy, temp_fd, to_fd;
	u_long nfset;
	char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];

	files_match = 0;
	from_fd = -1;

	/* If try to install NULL file to a directory, fails. */
	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
		if (stat(from_name, &from_sb))
			err(EX_OSERR, "%s", from_name);
		if (!S_ISREG(from_sb.st_mode)) {
			errno = EFTYPE;
			err(EX_OSERR, "%s", from_name);
		}
		/* Build the target path. */
		if (flags & DIRECTORY) {
			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
			    to_name,
			    (p = strrchr(from_name, '/')) ? ++p : from_name);
			to_name = pathbuf;
		}
		devnull = 0;
	} else {
		devnull = 1;
	}

	target = stat(to_name, &to_sb) == 0;

	/* Only install to regular files. */
	if (target && !S_ISREG(to_sb.st_mode)) {
		errno = EFTYPE;
		warn("%s", to_name);
		return;
	}

	/* Only copy safe if the target exists. */
	tempcopy = safecopy && target;

	if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
		err(EX_OSERR, "%s", from_name);

	/* If we don't strip, we can compare first. */
	if (docompare && !dostrip && target) {
		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
			err(EX_OSERR, "%s", to_name);
		if (devnull)
			files_match = to_sb.st_size == 0;
		else
			files_match = !(compare(from_fd, from_name,
			    (size_t)from_sb.st_size, to_fd,
			    to_name, (size_t)to_sb.st_size));

		/* Close "to" file unless we match. */
		if (!files_match)
			(void)close(to_fd);
	}

	if (!files_match) {
		if (tempcopy) {
			to_fd = create_tempfile(to_name, tempfile,
			    sizeof(tempfile));
			if (to_fd < 0)
				err(EX_OSERR, "%s", tempfile);
		} else {
			if ((to_fd = create_newfile(to_name, target,
			    &to_sb)) < 0)
				err(EX_OSERR, "%s", to_name);
			if (verbose)
				(void)printf("install: %s -> %s\n",
				    from_name, to_name);
		}
		if (!devnull)
			copy(from_fd, from_name, to_fd,
			     tempcopy ? tempfile : to_name, from_sb.st_size);
	}

	if (dostrip) {
		strip(tempcopy ? tempfile : to_name);

		/*
		 * Re-open our fd on the target, in case we used a strip
		 * that does not work in-place -- like GNU binutils strip.
		 */
		close(to_fd);
		to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
		if (to_fd < 0)
			err(EX_OSERR, "stripping %s", to_name);
	}

	/*
	 * Compare the stripped temp file with the target.
	 */
	if (docompare && dostrip && target) {
		temp_fd = to_fd;

		/* Re-open to_fd using the real target name. */
		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
			err(EX_OSERR, "%s", to_name);

		if (fstat(temp_fd, &temp_sb)) {
			serrno = errno;
			(void)unlink(tempfile);
			errno = serrno;
			err(EX_OSERR, "%s", tempfile);
		}

		if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
			    to_name, (size_t)to_sb.st_size) == 0) {
			/*
			 * If target has more than one link we need to
			 * replace it in order to snap the extra links.
			 * Need to preserve target file times, though.
			 */
			if (to_sb.st_nlink != 1) {
				utb.actime = to_sb.st_atime;
				utb.modtime = to_sb.st_mtime;
				utime(tempfile, &utb);
			} else {
				files_match = 1;
				(void)unlink(tempfile);
			}
			(void) close(temp_fd);
		}
	}

	/*
	 * Move the new file into place if doing a safe copy
	 * and the files are different (or just not compared).
	 */
	if (tempcopy && !files_match) {
		/* Try to turn off the immutable bits. */
		if (to_sb.st_flags & NOCHANGEBITS)
			(void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
		if (dobackup) {
			if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
			    suffix) != strlen(to_name) + strlen(suffix)) {
				unlink(tempfile);
				errx(EX_OSERR, "%s: backup filename too long",
				    to_name);
			}
			if (verbose)
				(void)printf("install: %s -> %s\n", to_name, backup);
			if (rename(to_name, backup) < 0) {
				serrno = errno;
				unlink(tempfile);
				errno = serrno;
				err(EX_OSERR, "rename: %s to %s", to_name,
				     backup);
			}
		}
		if (verbose)
			(void)printf("install: %s -> %s\n", from_name, to_name);
		if (rename(tempfile, to_name) < 0) {
			serrno = errno;
			unlink(tempfile);
			errno = serrno;
			err(EX_OSERR, "rename: %s to %s",
			    tempfile, to_name);
		}

		/* Re-open to_fd so we aren't hosed by the rename(2). */
		(void) close(to_fd);
		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
			err(EX_OSERR, "%s", to_name);
	}

	/*
	 * Preserve the timestamp of the source file if necessary.
	 */
	if (dopreserve && !files_match && !devnull) {
		utb.actime = from_sb.st_atime;
		utb.modtime = from_sb.st_mtime;
		utime(to_name, &utb);
	}

	if (fstat(to_fd, &to_sb) == -1) {
		serrno = errno;
		(void)unlink(to_name);
		errno = serrno;
		err(EX_OSERR, "%s", to_name);
	}

	/*
	 * Set owner, group, mode for target; do the chown first,
	 * chown may lose the setuid bits.
	 */
	if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
	    (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
	    (mode != to_sb.st_mode))) {
		/* Try to turn off the immutable bits. */
		if (to_sb.st_flags & NOCHANGEBITS)
			(void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
	}

	if (!dounpriv && (
	    (gid != (gid_t)-1 && gid != to_sb.st_gid) ||
	    (uid != (uid_t)-1 && uid != to_sb.st_uid)))
		if (fchown(to_fd, uid, gid) == -1) {
			serrno = errno;
			(void)unlink(to_name);
			errno = serrno;
			err(EX_OSERR,"%s: chown/chgrp", to_name);
		}

	if (mode != to_sb.st_mode) {
		if (fchmod(to_fd,
		     dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) {
			serrno = errno;
			(void)unlink(to_name);
			errno = serrno;
			err(EX_OSERR, "%s: chmod", to_name);
		}
	}

	/*
	 * If provided a set of flags, set them, otherwise, preserve the
	 * flags, except for the dump and history flags.  The dump flag
	 * is left clear on the target while the history flag from when
	 * the target was created (which is inherited from the target's
	 * parent directory) is retained.
	 */
	if (flags & SETFLAGS) {
		nfset = (to_sb.st_flags | fset) & ~fclr;
	} else {
		nfset = (from_sb.st_flags & ~(UF_NODUMP | UF_NOHISTORY)) |
			(to_sb.st_flags & UF_NOHISTORY);
	}

	/*
	 * NFS does not support flags.  Ignore EOPNOTSUPP flags if we're just
	 * trying to turn off UF_NODUMP.  If we're trying to set real flags,
	 * then warn if the fs doesn't support it, otherwise fail.
	 */
	if (!dounpriv && !devnull && fchflags(to_fd, nfset)) {
		if (flags & SETFLAGS) {
			if (errno == EOPNOTSUPP)
				warn("%s: chflags", to_name);
			else {
				serrno = errno;
				(void)unlink(to_name);
				errno = serrno;
				err(EX_OSERR, "%s: chflags", to_name);
			}
		}
	}

	(void)close(to_fd);
	if (!devnull)
		(void)close(from_fd);
}
Пример #13
0
bool FollowStreamDialog::follow(QString previous_filter, bool use_stream_index)
{
    int                 tmp_fd;
    QString             follow_filter;
    const char          *hostname0 = NULL, *hostname1 = NULL;
    char                *port0 = NULL, *port1 = NULL;
    QString             server_to_client_string;
    QString             client_to_server_string;
    QString             both_directions_string;
    follow_stats_t      stats;
    tcp_stream_chunk    sc;
    size_t              nchars;
    gboolean is_tcp = FALSE, is_udp = FALSE;

    beginRetapPackets();
    resetStream();

    if (file_closed_)
    {
        QMessageBox::warning(this, tr("No capture file."), tr("Please make sure you have a capture file opened."));
        return false;
    }

    if (cap_file_.capFile()->edt == NULL)
    {
        QMessageBox::warning(this, tr("Error following stream."), tr("Capture file invalid."));
        return false;
    }

    proto_get_frame_protocols(cap_file_.capFile()->edt->pi.layers, NULL, &is_tcp, &is_udp, NULL, NULL, NULL, NULL);

    switch (follow_type_)
    {
    case FOLLOW_TCP:
        if (!is_tcp) {
            QMessageBox::warning(this, tr("Error following stream."), tr("Please make sure you have a TCP packet selected."));
            return false;
        }
        break;
    case FOLLOW_UDP:
        if (!is_udp) {
            QMessageBox::warning(this, tr("Error following stream."), tr("Please make sure you have a UDP packet selected."));
            return false;
        }
        break;
    case FOLLOW_SSL:
        /* we got ssl so we can follow */
        removeStreamControls();
        if (!epan_dissect_packet_contains_field(cap_file_.capFile()->edt, "ssl")) {
            QMessageBox::critical(this, tr("Error following stream."),
                               tr("Please make sure you have an SSL packet selected."));
            return false;
        }
        break;
    }

    if (follow_type_ == FOLLOW_TCP || follow_type_ == FOLLOW_SSL)
    {
        /* Create a new filter that matches all packets in the TCP stream,
           and set the display filter entry accordingly */
        reset_tcp_reassembly();
    } else {
        reset_udp_follow();
    }

    if (use_stream_index) {
        follow_filter = gchar_free_to_qstring(
            build_follow_index_filter((follow_type_ == FOLLOW_TCP) ? TCP_STREAM : UDP_STREAM));
    } else {
        follow_filter = gchar_free_to_qstring(build_follow_conv_filter(&cap_file_.capFile()->edt->pi));
    }
    if (follow_filter.isEmpty()) {
        QMessageBox::warning(this,
                             tr("Error creating filter for this stream."),
                             tr("A transport or network layer header is needed."));
        return false;
    }

    if (follow_type_ == FOLLOW_TCP || follow_type_ == FOLLOW_SSL)
    {
        /* Create a temporary file into which to dump the reassembled data
           from the TCP stream, and set "data_out_file" to refer to it, so
           that the TCP code will write to it.

           XXX - it might be nicer to just have the TCP code directly
           append stuff to the text widget for the TCP stream window,
           if we can arrange that said window not pop up until we're
           done. */
        gchar *data_out_filename;
        tmp_fd = create_tempfile(&data_out_filename, "follow");
        data_out_filename_ = data_out_filename;

        if (tmp_fd == -1) {
            QMessageBox::warning(this, "Error",
                                 "Could not create temporary file %1: %2",
                                 data_out_filename_, g_strerror(errno));
            data_out_filename_.clear();
            return false;
        }

        data_out_file = fdopen(tmp_fd, "w+b");
        if (data_out_file == NULL) {
            QMessageBox::warning(this, "Error",
                                 "Could not create temporary file %1: %2",
                                 data_out_filename_, g_strerror(errno));
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }
    }

    /* append the negation */
    if(!previous_filter.isEmpty()) {
        filter_out_filter_ = QString("%1 and !(%2)")
                .arg(previous_filter).arg(follow_filter);
    }
    else
    {
        filter_out_filter_ = QString("!(%1)").arg(follow_filter);
    }

    switch (follow_type_)
    {
    case FOLLOW_TCP:
    {
        int stream_count = get_tcp_stream_count() - 1;
        ui->streamNumberSpinBox->blockSignals(true);
        ui->streamNumberSpinBox->setMaximum(stream_count);
        ui->streamNumberSpinBox->setValue(get_follow_index(TCP_STREAM));
        ui->streamNumberSpinBox->blockSignals(false);
        ui->streamNumberSpinBox->setToolTip(tr("%Ln total stream(s).", "", stream_count));
        ui->streamNumberLabel->setToolTip(ui->streamNumberSpinBox->toolTip());

        break;
    }
    case FOLLOW_UDP:
    {
        /* data will be passed via tap callback*/
        if (!registerTapListener("udp_follow", &follow_info_,
                                 follow_filter.toUtf8().constData(),
                                 0, NULL, udp_queue_packet_data, NULL)) {
            return false;
        }

        int stream_count = get_udp_stream_count() - 1;
        ui->streamNumberSpinBox->blockSignals(true);
        ui->streamNumberSpinBox->setMaximum(stream_count);
        ui->streamNumberSpinBox->setValue(get_follow_index(UDP_STREAM));
        ui->streamNumberSpinBox->blockSignals(false);
        ui->streamNumberSpinBox->setToolTip(tr("%Ln total stream(s).", "", stream_count));
        ui->streamNumberLabel->setToolTip(ui->streamNumberSpinBox->toolTip());

        break;
    }
    case FOLLOW_SSL:
        /* we got ssl so we can follow */
        if (!registerTapListener("ssl", &follow_info_,
                                 follow_filter.toUtf8().constData(), 0,
                                 NULL, ssl_queue_packet_data, NULL)) {
            return false;
        }
        break;
    }

    /* Run the display filter so it goes in effect - even if it's the
       same as the previous display filter. */
    emit updateFilter(follow_filter, TRUE);

    switch (follow_type_)
    {
    case FOLLOW_TCP:

        break;
    case FOLLOW_UDP:
    case FOLLOW_SSL:
        removeTapListeners();
        break;
    }

    if (follow_type_ == FOLLOW_TCP)
    {
        /* Check whether we got any data written to the file. */
        if (empty_tcp_stream) {
            QMessageBox::warning(this, "Error",
                                 "The packets in the capture file for that stream have no data.");
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }

        /* Go back to the top of the file and read the first tcp_stream_chunk
         * to ensure that the IP addresses and port numbers in the drop-down
         * list are tied to the correct lines displayed by follow_read_stream()
         * later on (which also reads from this file).  Close the file when
         * we're done.
         *
         * We read the data now, before we pop up a window, in case the
         * read fails.  We use the data later.
         */

        rewind(data_out_file);
        nchars=fread(&sc, 1, sizeof(sc), data_out_file);
        if (nchars != sizeof(sc)) {
            if (ferror(data_out_file)) {
                QMessageBox::warning(this, "Error",
                                     QString(tr("Could not read from temporary file %1: %2"))
                                     .arg(data_out_filename_)
                                     .arg(g_strerror(errno)));
            } else {
                QMessageBox::warning(this, "Error",
                                     QString(tr("Short read from temporary file %1: expected %2, got %3"))
                                     .arg(data_out_filename_)
                                     .arg((unsigned long)sizeof(sc))
                                     .arg((unsigned long)nchars));

            }
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }
        fclose(data_out_file);
        data_out_file = NULL;
    }

    /* Stream to show */
    follow_stats(&stats);

    if (stats.is_ipv6) {
        struct e_in6_addr ipaddr;
        memcpy(&ipaddr, stats.ip_address[0], 16);
        hostname0 = get_hostname6(&ipaddr);
        memcpy(&ipaddr, stats.ip_address[1], 16);
        hostname1 = get_hostname6(&ipaddr);
    } else {
        guint32 ipaddr;
        memcpy(&ipaddr, stats.ip_address[0], 4);
        hostname0 = get_hostname(ipaddr);
        memcpy(&ipaddr, stats.ip_address[1], 4);
        hostname1 = get_hostname(ipaddr);
    }

    switch (follow_type_)
    {
    case FOLLOW_TCP:
        port0 = tcp_port_to_display(NULL, stats.port[0]);
        port1 = tcp_port_to_display(NULL, stats.port[1]);
        break;
    case FOLLOW_UDP:
        port0 = udp_port_to_display(NULL, stats.port[0]);
        port1 = udp_port_to_display(NULL, stats.port[1]);
        break;
    case FOLLOW_SSL:
        port0 = tcp_port_to_display(NULL, stats.port[0]);
        port1 = tcp_port_to_display(NULL, stats.port[1]);
        break;
    }

    follow_info_.is_ipv6 = stats.is_ipv6;

    if (follow_type_ == FOLLOW_TCP)
    {
        /* Host 0 --> Host 1 */
        if ((sc.src_port == stats.port[0]) &&
            ((stats.is_ipv6 && (memcmp(sc.src_addr, stats.ip_address[0], 16) == 0)) ||
             (!stats.is_ipv6 && (memcmp(sc.src_addr, stats.ip_address[0], 4) == 0)))) {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }

        /* Host 1 --> Host 0 */
        if ((sc.src_port == stats.port[1]) &&
            ((stats.is_ipv6 && (memcmp(sc.src_addr, stats.ip_address[1], 16) == 0)) ||
             (!stats.is_ipv6 && (memcmp(sc.src_addr, stats.ip_address[1], 4) == 0)))) {
            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }

    }
    else
    {
        if ((follow_info_.client_port == stats.port[0]) &&
            ((stats.is_ipv6 && (memcmp(follow_info_.client_ip.data, stats.ip_address[0], 16) == 0)) ||
             (!stats.is_ipv6 && (memcmp(follow_info_.client_ip.data, stats.ip_address[0], 4) == 0)))) {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));

            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));

            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }
    }

    wmem_free(NULL, port0);
    wmem_free(NULL, port1);

    /* Both Stream Directions */
    switch (follow_type_)
    {
    case FOLLOW_TCP:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               stats.bytes_written[0] + stats.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        setWindowSubtitle(tr("Follow TCP Stream (%1)").arg(follow_filter));
        break;
    case FOLLOW_UDP:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               follow_info_.bytes_written[0] + follow_info_.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        setWindowSubtitle(tr("Follow UDP Stream (%1)").arg(follow_filter));
        break;
    case FOLLOW_SSL:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               follow_info_.bytes_written[0] + follow_info_.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        setWindowSubtitle(tr("Follow SSL Stream (%1)").arg(follow_filter));
        break;
    }

    ui->cbDirections->clear();
    ui->cbDirections->addItem(both_directions_string);
    ui->cbDirections->addItem(client_to_server_string);
    ui->cbDirections->addItem(server_to_client_string);

    followStream();
    fillHintLabel(-1);

    if (data_out_file) {
        fclose(data_out_file);
        data_out_file = NULL;
    }

    endRetapPackets();
    return true;
}
Пример #14
0
/*
    on first sight it may look if this function solves an easy problem
    the hard way, just reading the output one line at a time should
    be enough right?

    wrong... the number of interfaces determines how long the lines
    are... so we read a number of bytes and try to analyse it...

    if days is 0, we don't limit the number of days.

    returncodes:
        -1: error
         0: ok, but no data
         1: ok
*/
int
bandwidth_get_iface(const int debuglvl, char *device, int year, int month,
            int start_day, int days, char only_total, d_list *list)
{
    char            bw_buf[512] = "",
                    sect_buf[32] = "",
                    sect_buf_stripped[32] = "",
                    tmpfile[] = "/tmp/vuurmuur-iptrafvol-XXXXXX";
    char            done = FALSE;
    int             fd = 0;
    int             result = 0;
    ssize_t         readsize = 0;

    char            data_month = 0;
    int             data_day = 0;

    unsigned int    i = 0,
                    k = 0;

    int             act_border = 0;

    int             device_column = 0; /* column where our
                                    device can be found. */
    int             cur_column = 0;

    int             line_num = 0;

    char            buf_done = 0;

    char            parsing_device_line = 0,
                    parsing_total_line = 0;

    char            parsing_data = 0;

    char            month_str[4] = "";

    unsigned int    recv = 0,
                    recv_sub = 0,
                    send = 0,
                    send_sub = 0;

    int             retval = 0;

    char            cmd_year_str[5] = "",
                    cmd_month_str[3] = "",
                    cmd_start_day_str[3] = "",
                    cmd_num_days_str[8] = "";

    /* safety */
    if(device == NULL || list == NULL)
    {
        (void)vrprint.error(-1, VR_INTERR, "parameter problem "
                "(in: %s:%d).", __FUNC__, __LINE__);
        return(-1);
    }

    /* setup the list */
    d_list_setup(debuglvl, list, free);

    if(debuglvl >= LOW)
        (void)vrprint.debug(__FUNC__, "looking for data for '%s'.", device);

    /* create the tempfile */
    fd = create_tempfile(debuglvl, tmpfile);
    if(fd == -1)
        return(-1);
    else
        close(fd);

    snprintf(cmd_year_str, sizeof(cmd_year_str), "%d", year);
    snprintf(cmd_month_str, sizeof(cmd_month_str), "%d", month);
    snprintf(cmd_start_day_str, sizeof(cmd_start_day_str), "%d", start_day);

    /* see if we need to pass the -s option to iptrafvol*/
    if(days > 0) {
        snprintf(cmd_num_days_str, sizeof(cmd_num_days_str), "%d", days);
        char *args[] = { vccnf.iptrafvol_location,
                         "-d", "-y", cmd_year_str,
                         "-m", cmd_month_str,
                         "-b", cmd_start_day_str,
                         "-s", cmd_num_days_str, NULL };
        char *outputs[] = { tmpfile, "/dev/null", NULL };
        result = libvuurmuur_exec_command(debuglvl, &conf, vccnf.iptrafvol_location, args, outputs);
    } else {
        char *args[] = { vccnf.iptrafvol_location,
                         "-d", "-y", cmd_year_str,
                         "-m", cmd_month_str,
                         "-b", cmd_start_day_str, NULL };
        char *outputs[] = { tmpfile, "/dev/null", NULL };
        result = libvuurmuur_exec_command(debuglvl, &conf, vccnf.iptrafvol_location, args, outputs);
    }
    if(result != 0)
    {
        return(-1);
    }

    /* open the file for reaing */
    fd = open(tmpfile, 0);
    if(fd < 0)
    {
        (void)vrprint.error(-1, VR_ERR,
                gettext("opening '%s' failed: %s (in: %s:%d)."),
                tmpfile, strerror(errno), __FUNC__, __LINE__);
        return(-1);
    }

    while(done == FALSE)
    {
        memset(bw_buf, 0, sizeof(bw_buf));

        readsize = read(fd, bw_buf, sizeof(bw_buf));
        if(readsize > 0)
        {
            //fprintf(stdout, "bw_buf: '%s'.\n", bw_buf);

            for(i = 0; i < (unsigned int)readsize; i++)
            {
                //(void)vrprint.info(__FUNC__, "bw_buf[%d] = '%c', k = %d", i, bw_buf[i], k);

                if(bw_buf[i] == '\n')
                {
                    line_num++;

                    act_border = 0;

                    sect_buf[k] = '\0';
                    k = 0;

                    //(void)vrprint.info(__FUNC__, "newline (act_border: %d, k: %d, line_num: %d, sect_buf '%s'.)", act_border, k, line_num, sect_buf);

                    if(parsing_device_line == 1)
                    {
                        parsing_device_line = 0;
                    }
                    if(parsing_total_line == 1)
                    {
                        //retval = 1;
                        done = 1;
                        break;
                    }

                    buf_done = 1;
                }
                else if(bw_buf[i] == '|')
                {
                    act_border++;
                    sect_buf[k] = '\0';
                    k = 0;

                    //(void)vrprint.info(__FUNC__, "border  (act_border: %d, k: %d, line_num: %d, sect_buf '%s'.)", act_border, k, line_num, sect_buf);
                    buf_done = 1;
                }
                else
                {
                    if(k < (unsigned int)sizeof(sect_buf) - 1)
                    {
                        sect_buf[k] = bw_buf[i];
                        k++;
                    }
                    else
                    {
                        sect_buf[k] = '\0';
                    }
                }

                if(line_num > 5)
                    parsing_data = 1;

                if(buf_done == 1)
                {
                    buf_done = 0;

                    /* strip the buffer from the starting whitespaces */
                    strip_buf(sect_buf, sect_buf_stripped, sizeof(sect_buf_stripped));

                    /* get the current column */
                    cur_column = act_border - 1;

                    if(line_num == 1)
                    {
                        if(debuglvl >= HIGH)
                            (void)vrprint.debug(__FUNC__, "line_num == 1: '%s'", sect_buf_stripped);

                        if(strncmp("no data", sect_buf_stripped, 7) == 0)
                        {
                            retval = 0;
                            done = TRUE;
                            break;
                        }
                    }

                    /* the deviceline starts with MBytes */
                    if(strncmp(sect_buf_stripped, "MBytes", 6) == 0)
                        parsing_device_line = 1;

                    /* this is the total line */
                    if(strcmp(sect_buf_stripped, "Total:") == 0)
                        parsing_total_line = 1;

                    /* date column */
                    if( parsing_data == 1 && cur_column == 1 && only_total == 0)
                    {
                        sscanf(sect_buf_stripped, "%d %3s", &data_day, month_str);

                        /* parse the month */
                        if(strcmp(month_str, "Jan") == 0)       data_month = 1;
                        else if(strcmp(month_str, "Feb") == 0)  data_month = 2;
                        else if(strcmp(month_str, "Mar") == 0)  data_month = 3;
                        else if(strcmp(month_str, "Apr") == 0)  data_month = 4;
                        else if(strcmp(month_str, "May") == 0)  data_month = 5;
                        else if(strcmp(month_str, "Jun") == 0)  data_month = 6;
                        else if(strcmp(month_str, "Jul") == 0)  data_month = 7;
                        else if(strcmp(month_str, "Aug") == 0)  data_month = 8;
                        else if(strcmp(month_str, "Sep") == 0)  data_month = 9;
                        else if(strcmp(month_str, "Oct") == 0)  data_month = 10;
                        else if(strcmp(month_str, "Nov") == 0)  data_month = 11;
                        else if(strcmp(month_str, "Dec") == 0)  data_month = 12;
                        else
                        {
                            (void)vrprint.error(-1, VR_ERR, gettext("could not parse month '%s' (in: %s:%d)."),
                                                    month_str,
                                                    __FUNC__, __LINE__);
                            return(-1);
                        }

                        //(void)vrprint.info(__FUNC__, "day: '%d', month: '%d'", data_day, data_month);
                    }
                    /* device column */
                    if( parsing_data == 1 && device_column > 1 && cur_column == device_column &&
                        ((only_total == 1 && parsing_total_line == 1) || only_total == 0))
                    {
                        sscanf(sect_buf_stripped, "%u.%u %u.%u", &recv, &recv_sub, &send, &send_sub);

                        recv = ((recv * 10) + recv_sub) / 10;
                        send = ((send * 10) + send_sub) / 10;

                        if(debuglvl >= LOW)
                            (void)vrprint.info(__FUNC__, "recv = %.1u, send = %.1u.", recv, send);

                        retval = 1;

                        /* we asume that the date is already parsed */
                        result = bandwidth_store(debuglvl, list, year, data_month, data_day, parsing_total_line, recv, send);
                        if(result < 0)
                        {
                            (void)vrprint.error(-1, VR_INTERR, "bandwidth_store() failed (in: %s:%d).", __FUNC__, __LINE__);

                            done = TRUE;
                            retval = -1;
                        }
                    }

                    /* parse the deviceline to determine the column */
                    if(parsing_device_line == 1)
                    {
                        if(strcmp(sect_buf_stripped, device) == 0)
                        {
                            /* act border includes the last borderline, so -1. */
                            device_column = cur_column;

                            if(debuglvl >= LOW)
                                (void)vrprint.info(__FUNC__, "sect_buf_stripped '%s' match! (device: %s) column = %d.", sect_buf_stripped, device, device_column);
                        }
                    }
                }
            }
        }
        else
        {
            done = TRUE;
        }
    }

    /* close the file again */
    if(close(fd) == -1)
    {
        (void)vrprint.error(-1, VR_ERR,
                gettext("closing of '%s' failed: %s (in: %s:%d)."),
                tmpfile, strerror(errno), __FUNC__, __LINE__);
        return(-1);
    }

    /* remove the file */
    if(unlink(tmpfile) == -1)
    {
        (void)vrprint.error(-1, VR_ERR,
                gettext("removing '%s' failed (unlink): %s (in: %s:%d)."),
                tmpfile, strerror(errno), __FUNC__, __LINE__);
        return(-1);
    }

    return(retval);
}
Пример #15
0
int main(int argc, char **argv)
{
  char *mydir;
  char *temp_fname[5000];
  int i;
  size_t fsize;
  DIR *dir;
  struct dirent *ent;
  struct stat stat_buf;
  char path[1024];
  int fd, ret, filecount;
  int c;
  struct timespec ns;

  ns.tv_sec = 0;
  ns.tv_nsec = 250000000;

  /* Flag set by `--verbose'. */
  static int verbose_flag;

  /*  Initialize temporary file list so we know when it ends */
  for (i = 0; i < 5000; i++) {
    temp_fname[i] = NULL;
  }

  while (1) {
    static struct option long_options[] = {
      /* These options set a flag. */
      {"verbose",   no_argument, &verbose_flag, 1},
      {"brief",     no_argument, &verbose_flag, 0},
      /* The following options don't set a flag. */
      {"count",     required_argument, NULL, 'c'},
      {"dirname",   required_argument, NULL, 'd'},
      {0, 0, 0, 0}
    };
    /* getopt_long stores the option index here. */
    int option_index = 0;

    c = getopt_long (argc, argv, "c:d:",
        long_options, &option_index);

    /* Detect the end of the options. */
    if (c == -1)
      break;

    switch (c) {
      case 0:
        /* (In this example) only options which set */
        /* a flag return zero, so do nothing. */
        break;

      case 'c':
        printf ("option --count (-c) with value `%s'\n", optarg);
        filecount = atoi(optarg);
        break;

      case 'd':
        printf ("option --dirname (-d) with value `%s'\n", optarg);
        mydir = optarg;
        break;

      case '?':
        /* getopt_long already printed an error message. */
        break;

      default:
        abort ();
    }
  }

  /* Instead of reporting `--verbose'
     and `--brief' as they are encountered,
     we report the final status resulting from them. */
  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc) {
    printf ("non-option ARGV-elements: ");
    while (optind < argc)
      printf ("%s ", argv[optind++]);
    putchar ('\n');
  }


  for (i = 0; i < filecount; i++) {
    fsize = rand_tempfile_size();
    temp_fname[i] = create_tempfile(mydir,fsize);
  }

  dir = opendir(mydir);
  if (dir != NULL) {
    /* skip '.' and '..' */
    if ((readdir(dir) != NULL) && (readdir(dir) != NULL)) {
      while((ent = readdir(dir)) != NULL) {
        snprintf(path, 1024, "%s/%s", mydir, ent->d_name);
        if (lstat(path, &stat_buf) == -1) {
          perror("lstat failed");
          continue;
        }
        switch (stat_buf.st_mode & S_IFMT) {
          case S_IFREG:
            /* Test: ftruncate to 256 KB, regardless */
            if ((fd = open(path,O_RDWR)) == -1) {
              printf("Unable to open file for truncation\n");
              continue;
            }
            if ((ret = ftruncate(fd,(off_t)(256 * 1024))) == -1) {
              printf("Failed to ftruncate %s\n",path);
            }
            close(fd);
            /* 4 per sec (Hz) */
            nanosleep(&ns,(struct timespec *)NULL);
            break;

          default:
            continue;
        }
      }
    }
  }

  for (i = 0; i < 5000; i++) {
    if (temp_fname[i] == NULL) break;
    printf("Unlinking %s\n",temp_fname[i]);
    unlink(temp_fname[i]);
    free(temp_fname[i]);  /* was allocated when temp file created, so free here */
  }
}
Пример #16
0
void opt_d(int argc, char **argv,int *arch, int *filecount, int *fcalled, file *info){
	int fbyte_max=1;
	int fbyte=0;
	int size = 0;
	int tempfile=0;
	int temparch =0;
	char cur_name[16];
	char *null_cur_name;
	char *null_info_name;
	char *str_buf;
	struct stat archinfo;
	struct stat temparch_info;
	

	fstat((*arch),&archinfo);

	temparch = create_tempfile();
	write(temparch,"!<arch>\n",8);
	fstat(temparch,&temparch_info);

	fbyte_max = archinfo.st_size;
	
	fbyte = 0;
	lseek((*arch),8,SEEK_SET);
	read_filename(argv,filecount,4,fcalled,info);

	for(fbyte=0; fbyte < fbyte_max; fbyte++){
		read((*arch),cur_name,16);
		null_cur_name = null_str(cur_name,16);
		null_cur_name = shrt_str(null_cur_name);
		null_info_name= null_str(info->name,16);
		null_info_name = shrt_str(null_info_name);

		(fbyte) += 60+atoi(info->size);

		if(fbyte < fbyte_max){
			if(!strcmp(null_cur_name,null_info_name)){
				iter_arch((*arch), &fbyte, info);

				if(atoi(info->size)%2!=0){
					lseek((*arch),1,SEEK_CUR);
					(fbyte)++;
				}
			}else{
				read_header(argc, argv, filecount, 4, fcalled, info);
				tempfile = create_tempfile();
				write_file_header(tempfile,info);
				info->desc = (*arch);
				write_file_content(tempfile,info);
				all_in_arch(tempfile,temparch,fcalled,info);
				close(tempfile);
			}
		}
	}

	remove(argv[1]);
	(*arch) = open_file(argv[1],1);
	size = temparch_info.st_size;
	str_buf = malloc(sizeof(char)*size);
	read(temparch,str_buf,size);
	close(temparch);
}