Пример #1
0
/*
 NAME:allocate_shot_memory
 PURPOSE: Create files to store final preconditioner and gradient results. Must be initialized with zeroes.
 
 outputfolder     (in) folder where snapshot data is store
 VolumeMemory     (in) memory needed to store the domain
 
 RETURN none
 */
void create_output_volumes(char *outputfolder, integer VolumeMemory)
{
    log_info ( "Creating output files in %s", outputfolder);

#ifndef DO_NOT_PERFOM_IO    
    char fnamePrecond[300], fnameGradient[300];
    
    sprintf( fnameGradient, "%s/resultGradient.res", outputfolder);
    sprintf( fnamePrecond , "%s/resultPrecond.res", outputfolder);
    
    FILE *fGradient = safe_fopen( fnameGradient, "wb", __FILE__, __LINE__ );
    FILE *fPrecond  = safe_fopen( fnamePrecond , "wb", __FILE__, __LINE__ );
     
    int numIts = ceil( VolumeMemory / IO_CHUNK_SIZE );
    
    /* create buffer array */
    real *tmparray = (real*) __malloc( ALIGN_INT, IO_CHUNK_SIZE );
    
    /* perform the accumulation of the chunks */
    for (int i=0; i<numIts; i++) {
        safe_fwrite(tmparray, 1, IO_CHUNK_SIZE, fGradient, __FILE__, __LINE__ );
        safe_fwrite(tmparray, 1, IO_CHUNK_SIZE, fPrecond , __FILE__, __LINE__ );
    }
    
    __free(tmparray);
    
    // close files
    safe_fclose( fnameGradient, fGradient, __FILE__, __LINE__ );
    safe_fclose( fnamePrecond , fPrecond , __FILE__, __LINE__ );
#endif

		log_info ("Output volumes created correctly");
}
Пример #2
0
/*
 * This routine does RfC3676 space stuffing since it's a MUST.
 * Space stuffing means that we have to add leading spaces to
 * certain lines:
 *   - lines starting with a space
 *   - lines starting with 'From '
 * This routine is only called once right after editing the
 * initial message so it's up to the user to take care of stuffing
 * when editing the message several times before actually sending it
 *
 * This is more or less a hack as it replaces the message's content with
 * a freshly created copy in a tempfile and modifies the file's mtime
 * so we don't trigger code paths watching for mtime changes
 */
void rfc3676_space_stuff (HEADER* hdr)
{
#if DEBUG
  int lc = 0;
  size_t len = 0;
  unsigned char c = '\0';
#endif
  FILE *in = NULL, *out = NULL;
  char buf[LONG_STRING];
  char tmpfile[_POSIX_PATH_MAX];

  if (!hdr || !hdr->content || !hdr->content->filename)
    return;

  dprint (2, (debugfile, "f=f: postprocess %s\n", hdr->content->filename));

  if ((in = safe_fopen (hdr->content->filename, "r")) == NULL)
    return;

  mutt_mktemp (tmpfile, sizeof (tmpfile));
  if ((out = safe_fopen (tmpfile, "w+")) == NULL)
  {
    safe_fclose (&in);
    return;
  }

  while (fgets (buf, sizeof (buf), in))
  {
    if (ascii_strncmp ("From ", buf, 5) == 0 || buf[0] == ' ') {
      fputc (' ', out);
#if DEBUG
      lc++;
      len = mutt_strlen (buf);
      if (len > 0)
      {
        c = buf[len-1];
        buf[len-1] = '\0';
      }
      dprint (4, (debugfile, "f=f: line %d needs space-stuffing: '%s'\n",
                  lc, buf));
      if (len > 0)
        buf[len-1] = c;
#endif
    }
    fputs (buf, out);
  }
  safe_fclose (&in);
  safe_fclose (&out);
  mutt_set_mtime (hdr->content->filename, tmpfile);
  unlink (hdr->content->filename);
  mutt_str_replace (&hdr->content->filename, tmpfile);
}
Пример #3
0
void pager_close(void) {

        if (pager_pid <= 0)
                return;

        /* Inform pager that we are done */
        stdout = safe_fclose(stdout);
        stderr = safe_fclose(stderr);

        (void) kill(pager_pid, SIGCONT);
        (void) wait_for_terminate(pager_pid, NULL);
        pager_pid = 0;
}
Пример #4
0
static int tls_check_stored_hostname (const gnutls_datum *cert,
                                      const char *hostname)
{
  char buf[80];
  FILE *fp;
  char *linestr = NULL;
  size_t linestrsize;
  int linenum = 0;
  regex_t preg;
  regmatch_t pmatch[3];

  /* try checking against names stored in stored certs file */
  if ((fp = fopen (SslCertFile, "r")))
  {
    if (REGCOMP(&preg, "^#H ([a-zA-Z0-9_\\.-]+) ([0-9A-F]{4}( [0-9A-F]{4}){7})[ \t]*$",
                REG_ICASE) != 0)
    {
       return 0;
    }

    buf[0] = '\0';
    tls_fingerprint (GNUTLS_DIG_MD5, buf, sizeof (buf), cert);
    while ((linestr = mutt_read_line(linestr, &linestrsize, fp, &linenum, 0)) != NULL)
    {
      if(linestr[0] == '#' && linestr[1] == 'H')
      {
        if (regexec(&preg, linestr, 3, pmatch, 0) == 0)
        {
          linestr[pmatch[1].rm_eo] = '\0';
          linestr[pmatch[2].rm_eo] = '\0';
          if (strcmp(linestr + pmatch[1].rm_so, hostname) == 0 &&
              strcmp(linestr + pmatch[2].rm_so, buf) == 0)
          {
            regfree(&preg);
            FREE(&linestr);
            safe_fclose (&fp);
            return 1;
          }
        }
      }
    }

    regfree(&preg);
    safe_fclose (&fp);
  }

  /* not found a matching name */
  return 0;
}
Пример #5
0
static int check_certificate_by_digest (X509 *peercert)
{
  unsigned char peermd[EVP_MAX_MD_SIZE];
  unsigned int peermdlen;
  X509 *cert = NULL;
  int pass = 0;
  FILE *fp;

  /* expiration check */
  if (option (OPTSSLVERIFYDATES) != M_NO)
  {
    if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
    {
      dprint (2, (debugfile, "Server certificate is not yet valid\n"));
      mutt_error (_("Server certificate is not yet valid"));
      mutt_sleep (2);
      return 0;
    }
    if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
    {
      dprint (2, (debugfile, "Server certificate has expired"));
      mutt_error (_("Server certificate has expired"));
      mutt_sleep (2);
      return 0;
    }
  }

  if ((fp = fopen (SslCertFile, "rt")) == NULL)
    return 0;

  if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
  {
    safe_fclose (&fp);
    return 0;
  }

  while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
  {
    pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;

    if (pass)
      break;
  }
  X509_free (cert);
  safe_fclose (&fp);

  return pass;
}
Пример #6
0
void load_shot_parameters( int    shotid,
                          int     *stacki,
                          real    *dt,
                          int     *nt_fwd,
                          int     *nt_bwd,
                          real    *dz,
                          real    *dx,
                          real    *dy,
                          integer *dimmz,
                          integer *dimmx,
                          integer *dimmy,
                          char    *outputfolder)
{
    char name[200];
    
    sprintf(name, "%s/shotparams_%05d.dat",outputfolder, shotid);
    log_info ( "Storing parameters for shot %d into %s", shotid, name);

    FILE *fp = safe_fopen(name, "r", __FILE__, __LINE__);
    
    fscanf(fp, "%f\n",  (real*   ) dz     );
    fscanf(fp, "%f\n",  (real*   ) dx     );
    fscanf(fp, "%f\n",  (real*   ) dy     );
    fscanf(fp,  I"\n", (integer*) dimmz  );
    fscanf(fp,  I"\n", (integer*) dimmx  );
    fscanf(fp,  I"\n", (integer*) dimmy  );
    fscanf(fp, "%d\n",  (int*    ) nt_fwd );
    fscanf(fp, "%d\n",  (int*    ) nt_bwd );
    fscanf(fp, "%f\n",  (real*   ) dt     );
    fscanf(fp, "%d\n",  (int*    ) stacki );
    
    safe_fclose( name, fp, __FILE__, __LINE__);
};
Пример #7
0
void log_error (const char *fmt, ...) 
{

		/* locate myself into the MPI world */
		int mpi_rank;
		MPI_Comm_rank( MPI_COMM_WORLD, &mpi_rank);

		/* build log file name */
		char logname[50];
		sprintf( logname, "mpi_%02d.log", mpi_rank);
		FILE* flog = safe_fopen( logname, "a+", __FILE__, __LINE__ );
	
		/* create the string from variadic input arguments */
		char str[1000];
    va_list args;
    va_start(args, fmt);
    vsprintf(str, fmt, args);
    va_end(args);

		/* create time string */
		char timestr[20];
    struct tm *sTm;
    time_t now = time (0);
    sTm = gmtime (&now);
    strftime ( timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", sTm);

		/* print actual line to log file  */
   	fprintf( flog, "-----> ERROR :: %s: %s\n", timestr, str);

		/*  close file  */
		safe_fclose( logname, flog, __FILE__, __LINE__ );
};
Пример #8
0
static void
session_read_data(struct session *s, char *line)
{
	size_t datalen;
	size_t len;
	size_t i;

	if (strcmp(line, ".") == 0) {
		s->s_datalen = ftell(s->datafp);
		if (! safe_fclose(s->datafp))
			s->s_dstatus |= DS_TEMPFAILURE;
		s->datafp = NULL;

		if (s->s_dstatus & DS_PERMFAILURE) {
			session_respond(s, "554 5.0.0 Transaction failed");
			session_enter_state(s, S_HELO);
		} else if (s->s_dstatus & DS_TEMPFAILURE) {
			session_respond(s, "421 4.0.0 Temporary failure");
			session_enter_state(s, S_QUIT);
			stat_increment("smtp.tempfail", 1);
		} else {
			session_imsg(s, PROC_QUEUE, IMSG_QUEUE_COMMIT_MESSAGE,
			    0, 0, -1, &s->s_msg, sizeof(s->s_msg));
			session_enter_state(s, S_DONE);
		}
		return;
	}

	/* Don't waste resources on message if it's going to bin anyway. */
	if (s->s_dstatus & (DS_PERMFAILURE|DS_TEMPFAILURE))
		return;

	/* "If the first character is a period and there are other characters
	 *  on the line, the first character is deleted." [4.5.2]
	 */
	if (*line == '.')
		line++;

	len = strlen(line);

	/* If size of data overflows a size_t or exceeds max size allowed
	 * for a message, set permanent failure.
	 */
	datalen = ftell(s->datafp);
	if (SIZE_MAX - datalen < len + 1 ||
	    datalen + len + 1 > env->sc_maxsize) {
		s->s_dstatus |= DS_PERMFAILURE;
		return;
	}

	if (! (s->s_flags & F_8BITMIME)) {
		for (i = 0; i < len; ++i)
			if (line[i] & 0x80)
				line[i] = line[i] & 0x7f;
	}

	if (fprintf(s->datafp, "%s\n", line) != (int)len + 1)
		s->s_dstatus |= DS_TEMPFAILURE;
}
Пример #9
0
int safe_fsync_close (FILE **f)
{
  int r = 0;

  if (*f)
  {
    if (fflush (*f) || fsync (fileno (*f)))
    {
      r = -1;
      safe_fclose (f);
    }
    else
      r = safe_fclose (f);
  }

  return r;
}
Пример #10
0
static QUERY *run_query (char *s, int quiet)
{
        FILE *fp;
        QUERY *first = NULL;
        QUERY *cur = NULL;
        char cmd[_POSIX_PATH_MAX];
        char *buf = NULL;
        size_t buflen;
        int dummy = 0;
        char msg[STRING];
        char *p;
        pid_t thepid;

        mutt_expand_file_fmt (cmd, sizeof(cmd), QueryCmd, s);

        if ((thepid = mutt_create_filter (cmd, NULL, &fp, NULL)) < 0) {
                dprint (1, (debugfile, "unable to fork command: %s", cmd));
                return 0;
        }
        if (!quiet)
                mutt_message _("Waiting for response...");
        fgets (msg, sizeof (msg), fp);
        if ((p = strrchr (msg, '\n')))
                *p = '\0';
        while ((buf = mutt_read_line (buf, &buflen, fp, &dummy, 0)) != NULL) {
                if ((p = strtok(buf, "\t\n"))) {
                        if (first == NULL) {
                                first = (QUERY *) safe_calloc (1, sizeof (QUERY));
                                cur = first;
                        }
                        else {
                                cur->next = (QUERY *) safe_calloc (1, sizeof (QUERY));
                                cur = cur->next;
                        }

                        cur->addr = rfc822_parse_adrlist (cur->addr, p);
                        p = strtok(NULL, "\t\n");
                        if (p) {
                                cur->name = safe_strdup (p);
                                p = strtok(NULL, "\t\n");
                                if (p)
                                        cur->other = safe_strdup (p);
                        }
                }
        }
        FREE (&buf);
        safe_fclose (&fp);
        if (mutt_wait_filter (thepid)) {
                dprint (1, (debugfile, "Error: %s\n", msg));
                if (!quiet)  mutt_error ("%s", msg);
        }
        else {
                if (!quiet)
                        mutt_message ("%s", msg);
        }

        return first;
}
Пример #11
0
int imap_commit_message (CONTEXT *ctx, MESSAGE *msg)
{
  int r = safe_fclose (&msg->fp);

  if (r)
    return r;

  return imap_append_message (ctx, msg);
}
Пример #12
0
void DMALogClose()
{
	safe_fclose(DMA4LogFile);
	safe_fclose(DMA7LogFile);
	safe_fclose(REGWRTLogFile[0]);
	safe_fclose(REGWRTLogFile[1]);
	safe_fclose(ADMA4LogFile);
	safe_fclose(ADMA7LogFile);
	safe_fclose(ADMAOutLogFile);
}
Пример #13
0
static void fix_end_of_file (const char *data)
{
  FILE *fp;
  int c;
  
  if ((fp = safe_fopen (data, "a+")) == NULL)
    return;
  fseek (fp,-1,SEEK_END);
  if ((c = fgetc(fp)) != '\n')
    fputc ('\n', fp);
  safe_fclose (&fp);
}
Пример #14
0
static int
fsqueue_envelope_update(enum queue_kind qkind, struct envelope *ep)
{
	char temp[MAXPATHLEN];
	char dest[MAXPATHLEN];
	FILE *fp;
	u_int64_t batch_id;

	batch_id = ep->batch_id;
	ep->batch_id = 0;

	if (! bsnprintf(temp, sizeof(temp), "%s/envelope.tmp", PATH_QUEUE))
		fatalx("fsqueue_envelope_update");

	if (! bsnprintf(dest, sizeof(dest), "%s/%03x/%08x%s/%016llx",
		fsqueue_getpath(qkind),
		evpid_to_msgid(ep->id) & 0xfff,
		evpid_to_msgid(ep->id),
		PATH_ENVELOPES, ep->id))
		fatal("fsqueue_envelope_update: snprintf");

	fp = fopen(temp, "w");
	if (fp == NULL) {
		if (errno == ENOSPC || errno == ENFILE)
			goto tempfail;
		fatal("fsqueue_envelope_update: open");
	}
	if (! fsqueue_dump_envelope_ascii(fp, ep)) {
		if (errno == ENOSPC)
			goto tempfail;
		fatal("fsqueue_dump_envelope_ascii: fwrite");
	}
	if (! safe_fclose(fp))
		goto tempfail;

	if (rename(temp, dest) == -1) {
		if (errno == ENOSPC)
			goto tempfail;
		fatal("fsqueue_envelope_update: rename");
	}

	ep->batch_id = batch_id;
	return 1;

tempfail:
	if (unlink(temp) == -1)
		fatal("fsqueue_envelope_update: unlink");
	if (fp)
		fclose(fp);

	ep->batch_id = batch_id;
	return 0;
}
Пример #15
0
int mutt_rename_file (char *oldfile, char *newfile)
{
  FILE *ofp, *nfp;

  if (access (oldfile, F_OK) != 0)
    return 1;
  if (access (newfile, F_OK) == 0)
    return 2;
  if ((ofp = fopen (oldfile,"r")) == NULL)
    return 3;
  if ((nfp = safe_fopen (newfile,"w")) == NULL)
  {
    safe_fclose (&ofp);
    return 3;
  }
  mutt_copy_stream (ofp,nfp);
  safe_fclose (&nfp);
  safe_fclose (&ofp);
  mutt_unlink (oldfile);
  return 0;
}
Пример #16
0
int mutt_get_tmp_attachment (BODY *a)
{
  char type[STRING];
  char tempfile[_POSIX_PATH_MAX];
  rfc1524_entry *entry = rfc1524_new_entry();
  FILE *fpin = NULL, *fpout = NULL;
  struct stat st;
  
  if(a->unlink)
    return 0;

  snprintf(type, sizeof(type), "%s/%s", TYPE(a), a->subtype);
  rfc1524_mailcap_lookup(a, type, entry, 0);
  rfc1524_expand_filename(entry->nametemplate, a->filename, 
			  tempfile, sizeof(tempfile));
  
  rfc1524_free_entry(&entry);

  if(stat(a->filename, &st) == -1)
    return -1;

  if((fpin = fopen(a->filename, "r")) && (fpout = safe_fopen(tempfile, "w")))  /* __FOPEN_CHECKED__ */
  {
    mutt_copy_stream (fpin, fpout);
    mutt_str_replace (&a->filename, tempfile);
    a->unlink = 1;

    if(a->stamp >= st.st_mtime)
      mutt_stamp_attachment(a);
  }
  else
    mutt_perror(fpin ? tempfile : a->filename);
  
  if(fpin)  safe_fclose (&fpin);
  if(fpout) safe_fclose (&fpout);
  
  return a->unlink ? 0 : -1;
}
Пример #17
0
void btd_config_populate(struct btd_config *config, int argc, char **argv)
{
	FILE *fp;
	char *key, *line = NULL;
	size_t len, sep;

	config->configpath = NULL;

	config->socket = NULL;

	config->filefmt = safe_strdup(".pdf");
	config->check_fields = true;
	config->multithread = true;
	config->pidfile = safe_strdup("");

	argp_parse(&argp, argc, argv, 0, 0, config);
	btd_log(2, "Arguments parsed. Loglevel set to %d\n",
		get_btd_log_level());

	if (config->configpath == NULL)
		config->configpath = btd_get_config_path();

	config->datadir = btd_get_data_path();
	key = safe_strcat(2, config->datadir, "/btd.socket");
	printf("config.socket: %p\n", (void *)config->socket);
	config->socket = btd_get_addrinfo(key);
	printf("config.socket: %p\n", (void *)config->socket);
	free(key);

	btd_log(2, "Opening config at '%s'\n", config->configpath);
	fp = safe_fopen(config->configpath, "r");

	while (getline(&line, &len, fp) != -1) {
		sep = strcspn(line, "=");
		key = strndup(line, sep);
		if (key == NULL){
			die("strndup() failed\n");
		}
		update_config(config, key, line+sep+1);
		free(line);
		free(key);
		line = NULL;
	}
	free(line);
	btd_log(2, "Done parsing\n");
	config->db = safe_strcat(2, config->datadir, "/db.sqlite");
	config->filesdir = safe_strcat(2, config->datadir, "/files/");

	safe_fclose(fp);
}
Пример #18
0
static void append_signature (FILE *f)
{
  FILE *tmpfp;
  pid_t thepid;

  if (Signature && (tmpfp = mutt_open_read (Signature, &thepid)))
  {
    if (option (OPTSIGDASHES))
      fputs ("\n-- \n", f);
    mutt_copy_stream (tmpfp, f);
    safe_fclose (&tmpfp);
    if (thepid != -1)
      mutt_wait_filter (thepid);
  }
}
Пример #19
0
void mutt_help (int menu)
{
  char t[_POSIX_PATH_MAX];
  char buf[SHORT_STRING];
  const char *desc;
  FILE *f;
  const struct binding_t *funcs;

  mutt_mktemp (t, sizeof (t));

  funcs = km_get_table (menu);
  desc = mutt_getnamebyvalue (menu, Menus);
  if (!desc)
    desc = _("<UNKNOWN>");
  
  do {
    if ((f = safe_fopen (t, "w")) == NULL)
    {
      mutt_perror (t);
      return;
    }
  
    dump_menu (f, menu);
    if (menu != MENU_EDITOR && menu != MENU_PAGER)
    {
      fputs (_("\nGeneric bindings:\n\n"), f);
      dump_menu (f, MENU_GENERIC);
    }
  
    fputs (_("\nUnbound functions:\n\n"), f);
    if (funcs)
      dump_unbound (f, funcs, Keymaps[menu], NULL);
    if (menu != MENU_PAGER)
      dump_unbound (f, OpGeneric, Keymaps[MENU_GENERIC], Keymaps[menu]);
  
    safe_fclose (&f);
  
    snprintf (buf, sizeof (buf), _("Help for %s"), desc);
  }
  while
    (mutt_do_pager (buf, t,
		    M_PAGER_RETWINCH | M_PAGER_MARKER | M_PAGER_NSKIP | M_PAGER_NOWRAP,
		    NULL)
     == OP_REFORMAT_WINCH);
}
Пример #20
0
Файл: mh.c Проект: hww3/pexts
int maildir_commit_message (CONTEXT *ctx, MESSAGE *msg, HEADER *hdr)
{
  char subdir[4];
  char suffix[16];
  char path[_POSIX_PATH_MAX];
  char full[_POSIX_PATH_MAX];
  char *s;

  if (safe_fclose (&msg->fp) != 0)
    return -1;
  
  /* extract the subdir */
  s = strrchr (msg->path, '/') + 1;
  strfcpy (subdir, s, 4);

  /* extract the flags */  
  if ((s = strchr (s, ':')))
    strfcpy (suffix, s, sizeof (suffix));
  else
    suffix[0] = '\0';

  /* construct a new file name. */
  FOREVER
  {
    snprintf (path, _POSIX_PATH_MAX, "%s/%ld.%d_%d.%s%s", subdir,
	      time (NULL), getpid(), Counter++, NONULL (Hostname), suffix);
    snprintf (full, _POSIX_PATH_MAX, "%s/%s", ctx->path, path);

    dprint (2, (debugfile, "maildir_commit_message (): renaming %s to %s.\n",
		msg->path, full));

    if (safe_rename (msg->path, full) == 0)
    {
      if (hdr) 
	mutt_str_replace (&hdr->path, path);
      FREE (&msg->path);
      return 0;
    }
    else if (errno != EEXIST)
    {
      mutt_perror (ctx->path);
      return -1;
    }
  }
}
int main(){
	char *file_name = safe_malloc(sizeof(char) * MAX_FILENAME);
	char *chunk = safe_malloc(sizeof(char)*READSIZE);
	//read file name from the master process and call map function
	//on that file, return the result to the master process
	while(safe_read(STDIN_FILENO, file_name, MAX_FILENAME) > 0){
		FILE *file = safe_fopen(file_name, "r");	
		while(fread(chunk, READSIZE-1, 1, file) > 0){
			//make sure the chunk is null-terminated
			chunk[READSIZE-1] = '\0';
			map(chunk, STDOUT_FILENO);
		}
		safe_fclose(file);
	}
	free(file_name);
	free(chunk);
	return 0;
}
Пример #22
0
Файл: mh.c Проект: hww3/pexts
static void mh_read_sequences (struct mh_sequences *mhs, const char *path)
{
  FILE *fp;
  int line = 1;
  char *buff = NULL;
  char *t;
  size_t sz = 0;
  
  short f;
  int first, last;

  char pathname[_POSIX_PATH_MAX];
  snprintf (pathname, sizeof (pathname),  "%s/.mh_sequences", path);

  if (!(fp = fopen (pathname, "r")))
    return;

  while ((buff = mutt_read_line (buff, &sz, fp, &line)))
  {
    if (!(t = strtok (buff, " \t:")))
      continue;
    
    if (!mutt_strcmp (t, MhUnseen))
      f = MH_SEQ_UNSEEN;
    else if (!mutt_strcmp (t, MhFlagged))
      f = MH_SEQ_FLAGGED;
    else if (!mutt_strcmp (t, MhReplied))
      f = MH_SEQ_REPLIED;
    else	/* unknown sequence */
      continue;
    
    while ((t = strtok (NULL, " \t:")))
    {
      mh_read_token (t, &first, &last);
      for (; first <= last; first++)
	mhs_set (mhs, first, f);
    }
  }

  safe_free ((void **) &buff);
  safe_fclose (&fp);
}
Пример #23
0
/* Save the current image to disk */
bool factor_vm::save_image(const vm_char *saving_filename, const vm_char *filename)
{
	FILE* file;
	image_header h;

	file = OPEN_WRITE(saving_filename);
	if(file == NULL)
	{
		std::cout << "Cannot open image file: " << saving_filename << std::endl;
		std::cout << strerror(errno) << std::endl;
		return false;
	}

	h.magic = image_magic;
	h.version = image_version;
	h.data_relocation_base = data->tenured->start;
	h.data_size = data->tenured->occupied_space();
	h.code_relocation_base = code->seg->start;
	h.code_size = code->allocator->occupied_space();

	h.true_object = true_object;
	h.bignum_zero = bignum_zero;
	h.bignum_pos_one = bignum_pos_one;
	h.bignum_neg_one = bignum_neg_one;

	for(cell i = 0; i < special_object_count; i++)
		h.special_objects[i] = (save_special_p(i) ? special_objects[i] : false_object);

	bool ok = true;

	if(safe_fwrite(&h,sizeof(image_header),1,file) != 1) ok = false;
	if(safe_fwrite((void*)data->tenured->start,h.data_size,1,file) != 1) ok = false;
	if(safe_fwrite(code->allocator->first_block(),h.code_size,1,file) != 1) ok = false;
	safe_fclose(file);

	if(!ok)
		std::cout << "save-image failed: " << strerror(errno) << std::endl;
	else
		move_file(saving_filename,filename); 

	return ok;
}
Пример #24
0
void mutt_unlink (const char *s)
{
  int fd;
  int flags;
  FILE *f;
  struct stat sb, sb2;
  char buf[2048];

  /* Defend against symlink attacks */
  
#ifdef O_NOFOLLOW 
  flags = O_RDWR | O_NOFOLLOW;
#else
  flags = O_RDWR;
#endif
  
  if (lstat (s, &sb) == 0 && S_ISREG(sb.st_mode))
  {
    if ((fd = open (s, flags)) < 0)
      return;
    
    if ((fstat (fd, &sb2) != 0) || !S_ISREG (sb2.st_mode) 
	|| (sb.st_dev != sb2.st_dev) || (sb.st_ino != sb2.st_ino))
    {
      close (fd);
      return;
    }
    
    if ((f = fdopen (fd, "r+")))
    {
      unlink (s);
      memset (buf, 0, sizeof (buf));
      while (sb.st_size > 0)
      {
	fwrite (buf, 1, MIN (sizeof (buf), sb.st_size), f);
	sb.st_size -= MIN (sizeof (buf), sb.st_size);
      }
      safe_fclose (&f);
    }
  }
}
Пример #25
0
/* This function also initializes the data and code heaps */
void factor_vm::load_image(vm_parameters *p)
{
	FILE *file = OPEN_READ(p->image_path);
	if(file == NULL)
	{
		std::cout << "Cannot open image file: " << p->image_path << std::endl;
		std::cout << strerror(errno) << std::endl;
		exit(1);
	}

	image_header h;
	if(safe_fread(&h,sizeof(image_header),1,file) != 1)
		fatal_error("Cannot read image header",0);

	if(h.magic != image_magic)
		fatal_error("Bad image: magic number check failed",h.magic);

	if(h.version != image_version)
		fatal_error("Bad image: version number check failed",h.version);
	
	load_data_heap(file,&h,p);
	load_code_heap(file,&h,p);

	safe_fclose(file);

	init_objects(&h);

	cell data_offset = data->tenured->start - h.data_relocation_base;
	cell code_offset = code->seg->start - h.code_relocation_base;

	fixup_data(data_offset,code_offset);
	fixup_code(data_offset,code_offset);

	/* Store image path name */
	special_objects[OBJ_IMAGE] = allot_alien(false_object,(cell)p->image_path);
}
Пример #26
0
BODY *pgp_make_key_attachment (char *tempf)
{
  BODY *att;
  char buff[LONG_STRING];
  char tempfb[_POSIX_PATH_MAX], tmp[STRING];
  FILE *tempfp;
  FILE *devnull;
  struct stat sb;
  pid_t thepid;
  pgp_key_t key;
  unset_option (OPTPGPCHECKTRUST);

  key = pgp_ask_for_key (_("Please enter the key ID: "), NULL, 0, PGP_PUBRING);

  if (!key)    return NULL;

  snprintf (tmp, sizeof (tmp), "0x%s", pgp_fpr_or_lkeyid (pgp_principal_key (key)));
  pgp_free_key (&key);

  if (!tempf)
  {
    mutt_mktemp (tempfb, sizeof (tempfb));
    tempf = tempfb;
  }

  if ((tempfp = safe_fopen (tempf, tempf == tempfb ? "w" : "a")) == NULL)
  {
    mutt_perror _("Can't create temporary file");
    return NULL;
  }

  if ((devnull = fopen ("/dev/null", "w")) == NULL)	/* __FOPEN_CHECKED__ */
  {
    mutt_perror _("Can't open /dev/null");
    safe_fclose (&tempfp);
    if (tempf == tempfb)
      unlink (tempf);
    return NULL;
  }

  mutt_message _("Invoking PGP...");


  if ((thepid = 
       pgp_invoke_export (NULL, NULL, NULL, -1,
			   fileno (tempfp), fileno (devnull), tmp)) == -1)
  {
    mutt_perror _("Can't create filter");
    unlink (tempf);
    safe_fclose (&tempfp);
    safe_fclose (&devnull);
    return NULL;
  }

  mutt_wait_filter (thepid);

  safe_fclose (&tempfp);
  safe_fclose (&devnull);

  att = mutt_new_body ();
  att->filename = safe_strdup (tempf);
  att->unlink = 1;
  att->use_disp = 0;
  att->type = TYPEAPPLICATION;
  att->subtype = safe_strdup ("pgp-keys");
  snprintf (buff, sizeof (buff), _("PGP Key %s."), tmp);
  att->description = safe_strdup (buff);
  mutt_update_encoding (att);

  stat (tempf, &sb);
  att->length = sb.st_size;

  return att;
}
Пример #27
0
static pgp_key_t pgp_select_key (pgp_key_t keys,
                                 ADDRESS * p, const char *s)
{
  int keymax;
  pgp_uid_t **KeyTable;
  MUTTMENU *menu;
  int i, done = 0;
  char helpstr[LONG_STRING], buf[LONG_STRING], tmpbuf[STRING];
  char cmd[LONG_STRING], tempfile[_POSIX_PATH_MAX];
  FILE *fp, *devnull;
  pid_t thepid;
  pgp_key_t kp;
  pgp_uid_t *a;
  int (*f) (const void *, const void *);

  int unusable = 0;

  keymax = 0;
  KeyTable = NULL;

  for (i = 0, kp = keys; kp; kp = kp->next)
  {
    if (!option (OPTPGPSHOWUNUSABLE) && (kp->flags & KEYFLAG_CANTUSE))
    {
      unusable = 1;
      continue;
    }

    for (a = kp->address; a; a = a->next)
    {
      if (!option (OPTPGPSHOWUNUSABLE) && (a->flags & KEYFLAG_CANTUSE))
      {
	unusable = 1;
	continue;
      }

      if (i == keymax)
      {
	keymax += 5;
	safe_realloc (&KeyTable, sizeof (pgp_uid_t *) * keymax);
      }

      KeyTable[i++] = a;
    }
  }

  if (!i && unusable)
  {
    mutt_error _("All matching keys are expired, revoked, or disabled.");
    mutt_sleep (1);
    return NULL;
  }

  switch (PgpSortKeys & SORT_MASK)
  {
    case SORT_DATE:
      f = pgp_compare_date;
      break;
    case SORT_KEYID:
      f = pgp_compare_keyid;
      break;
    case SORT_ADDRESS:
      f = pgp_compare_address;
      break;
    case SORT_TRUST:
    default:
      f = pgp_compare_trust;
      break;
  }
  qsort (KeyTable, i, sizeof (pgp_uid_t *), f);

  helpstr[0] = 0;
  mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_PGP, OP_EXIT);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */
  mutt_make_help (buf, sizeof (buf), _("Select  "), MENU_PGP,
		  OP_GENERIC_SELECT_ENTRY);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */
  mutt_make_help (buf, sizeof (buf), _("Check key  "), MENU_PGP, OP_VERIFY_KEY);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */
  mutt_make_help (buf, sizeof (buf), _("Help"), MENU_PGP, OP_HELP);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */

  menu = mutt_new_menu (MENU_PGP);
  menu->max = i;
  menu->make_entry = pgp_entry;
  menu->help = helpstr;
  menu->data = KeyTable;

  if (p)
    snprintf (buf, sizeof (buf), _("PGP keys matching <%s>."), p->mailbox);
  else
    snprintf (buf, sizeof (buf), _("PGP keys matching \"%s\"."), s);


  menu->title = buf;

  kp = NULL;

  mutt_clear_error ();

  while (!done)
  {
    switch (mutt_menuLoop (menu))
    {

    case OP_VERIFY_KEY:

      mutt_mktemp (tempfile, sizeof (tempfile));
      if ((devnull = fopen ("/dev/null", "w")) == NULL)	/* __FOPEN_CHECKED__ */
      {
	mutt_perror _("Can't open /dev/null");
	break;
      }
      if ((fp = safe_fopen (tempfile, "w")) == NULL)
      {
	safe_fclose (&devnull);
	mutt_perror _("Can't create temporary file");
	break;
      }

      mutt_message _("Invoking PGP...");

      snprintf (tmpbuf, sizeof (tmpbuf), "0x%s",
          pgp_fpr_or_lkeyid (pgp_principal_key (KeyTable[menu->current]->parent)));

      if ((thepid = pgp_invoke_verify_key (NULL, NULL, NULL, -1,
		    fileno (fp), fileno (devnull), tmpbuf)) == -1)
      {
	mutt_perror _("Can't create filter");
	unlink (tempfile);
	safe_fclose (&fp);
	safe_fclose (&devnull);
      }

      mutt_wait_filter (thepid);
      safe_fclose (&fp);
      safe_fclose (&devnull);
      mutt_clear_error ();
      snprintf (cmd, sizeof (cmd), _("Key ID: 0x%s"), 
		pgp_keyid (pgp_principal_key (KeyTable[menu->current]->parent)));
      mutt_do_pager (cmd, tempfile, 0, NULL);
      menu->redraw = REDRAW_FULL;

      break;

    case OP_VIEW_ID:

      mutt_message ("%s", NONULL (KeyTable[menu->current]->addr));
      break;

    case OP_GENERIC_SELECT_ENTRY:


      /* XXX make error reporting more verbose */

      if (option (OPTPGPCHECKTRUST))
	if (!pgp_key_is_valid (KeyTable[menu->current]->parent))
	{
	  mutt_error _("This key can't be used: expired/disabled/revoked.");
	  break;
	}

      if (option (OPTPGPCHECKTRUST) &&
	  (!pgp_id_is_valid (KeyTable[menu->current])
	   || !pgp_id_is_strong (KeyTable[menu->current])))
      {
	char *s = "";
	char buff[LONG_STRING];
	
	if (KeyTable[menu->current]->flags & KEYFLAG_CANTUSE)
	  s = N_("ID is expired/disabled/revoked.");
	else switch (KeyTable[menu->current]->trust & 0x03)
	{
	  case 0:
	    s = N_("ID has undefined validity.");
	    break;
	  case 1:
	    s = N_("ID is not valid.");
	    break;
	  case 2:
	    s = N_("ID is only marginally valid.");
	    break;
	}

	snprintf (buff, sizeof (buff), _("%s Do you really want to use the key?"),
		  _(s));

	if (mutt_yesorno (buff, M_NO) != M_YES)
	{
	  mutt_clear_error ();
	  break;
	}
      }

# if 0
      kp = pgp_principal_key (KeyTable[menu->current]->parent);
# else
      kp = KeyTable[menu->current]->parent;
# endif
      done = 1;
      break;

    case OP_EXIT:

      kp = NULL;
      done = 1;
      break;
    }
  }

  mutt_menuDestroy (&menu);
  FREE (&KeyTable);

  set_option (OPTNEEDREDRAW);

  return (kp);
}
Пример #28
0
static void load_skin_bitmap (char *filespec, screen *texture, int size)
{
	FILE
		*fp;

	BITMAPFILEHEADER
		bmfh;

	BITMAPINFOHEADER
		bmih;

	char
		*buffer,
		*p;

	int
		buffer_size,
		x,
		y;

	rgb_colour
		col;

	ASSERT (filespec);

	ASSERT (texture);

	fp = safe_fopen (filespec, "rb");

	//
	// file header
	//

	fread (&bmfh, sizeof (bmfh), 1, fp);

	if (bmfh.bfType != BITMAP_ID)
	{
		safe_fclose (fp);

		debug_fatal ("%s is not a BMP file!", filespec);
	}

	//
	// info header
	//

	fread (&bmih, sizeof (bmih), 1, fp);

	if (bmih.biCompression != BI_RGB)
	{
		safe_fclose (fp);

		debug_fatal ("%s is not uncompressed RGB!", filespec);
	}

	if (bmih.biBitCount != 24)
	{
		safe_fclose (fp);

		debug_fatal ("%s is not 24 bit!", filespec);
	}

	if (bmih.biWidth != size)
	{
		safe_fclose (fp);

		debug_fatal ("%s is not %d pixels wide", filespec, size);
	}

	if (bmih.biHeight != size)
	{
		safe_fclose (fp);

		debug_fatal ("%s is not %d pixels high", filespec, size);
	}

	//
	// texture
	//

	buffer_size = size * size * 3;

	buffer = safe_malloc (buffer_size);

	fread (buffer, buffer_size, 1, fp);

	set_active_screen (texture);

	if (lock_screen (texture))
	{
		p = buffer;

		for (y = size - 1; y >= 0; y--)
		{
			for (x = 0; x < size; x++)
			{
				col.b = *p++;
				col.g = *p++;
				col.r = *p++;
				col.a = 255;

				set_pixel (x, y, col);
			}
		}

		unlock_screen (texture);
	}

	set_active_screen (video_screen);

	safe_free (buffer);

	safe_fclose (fp);
}
Пример #29
0
void read_motion_values (char *filespec, int num_frames, motion_data *array)
{
	FILE
		*fp;

	char
		s[200];

	int
		num_frames_in_file,
		frame,
		i_value;

	float
		f_value;

	ASSERT (filespec);

	ASSERT (num_frames > 0);

	ASSERT (array);

	fp = safe_fopen (filespec, "r");

	//
	// check for 'LWMO' file
	//

	fscanf (fp, "%s", s);

	if (strcmp (s, "LWMO") != 0)
	{
		debug_fatal ("%s is not a Lightwave motion file", filespec);
	}

	//
	// read off unwanted values
	//

	fscanf (fp, "%d", &i_value);

	fscanf (fp, "%d", &i_value);

	//
	// check number of frames
	//

	fscanf (fp, "%d", &num_frames_in_file);

	if (num_frames_in_file != num_frames)
	{
		debug_fatal ("Incorrect number of frames in motion file %s (expected = %d, actual = %d)", num_frames, num_frames_in_file);
	}

	//
	// read motion values
	//

	for (frame = 0; frame < num_frames; frame++)
	{
		fscanf (fp, "%f %f %f %f %f %f %f %f %f", &array->x, &array->y, &array->z, &array->heading, &array->pitch, &array->roll, &f_value, &f_value, &f_value);

		array->heading = rad (array->heading);

		array->pitch = rad (array->pitch);

		array->roll = rad (array->roll);

		fscanf (fp, "%d %d %d %d %d", &i_value, &i_value, &i_value, &i_value, &i_value);

		array++;
	}

	safe_fclose (fp);
}
Пример #30
0
int coredump_make_stack_trace(int fd, const char *executable, char **ret) {

        static const Dwfl_Callbacks callbacks = {
                .find_elf = dwfl_build_id_find_elf,
                .find_debuginfo = dwfl_standard_find_debuginfo,
        };

        struct stack_context c = {};
        char *buf = NULL;
        size_t sz = 0;
        int r;

        assert(fd >= 0);
        assert(ret);

        if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
                return -errno;

        c.f = open_memstream(&buf, &sz);
        if (!c.f)
                return -ENOMEM;

        elf_version(EV_CURRENT);

        c.elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
        if (!c.elf) {
                r = -EINVAL;
                goto finish;
        }

        c.dwfl = dwfl_begin(&callbacks);
        if (!c.dwfl) {
                r = -EINVAL;
                goto finish;
        }

        if (dwfl_core_file_report(c.dwfl, c.elf, executable) < 0) {
                r = -EINVAL;
                goto finish;
        }

        if (dwfl_report_end(c.dwfl, NULL, NULL) != 0) {
                r = -EINVAL;
                goto finish;
        }

        if (dwfl_core_file_attach(c.dwfl, c.elf) < 0) {
                r = -EINVAL;
                goto finish;
        }

        if (dwfl_getthreads(c.dwfl, thread_callback, &c) < 0) {
                r = -EINVAL;
                goto finish;
        }

        c.f = safe_fclose(c.f);

        *ret = buf;
        buf = NULL;

        r = 0;

finish:
        if (c.dwfl)
                dwfl_end(c.dwfl);

        if (c.elf)
                elf_end(c.elf);

        safe_fclose(c.f);

        free(buf);

        return r;
}