Ejemplo n.º 1
0
void readCoord(const char* filename, SOP& sop){
	//printf("Reading coordinates from '%s'.\n", filename);
	int is_xyz = 0;
	char buffer[BUF_SIZE+1];
	FILE* file = safe_fopen(filename, "r");
	if(file == NULL){
		DIE("ERROR: Coordinates file %s can not be found.\n", filename);
	}
	if (!strcmp(filename + strlen(filename)-4, ".xyz")) {
		is_xyz = 1;
		safe_fgets(buffer, BUF_SIZE, file);
		safe_fgets(buffer, BUF_SIZE, file);
	}
	int index = 0;
	while(fgets(buffer, BUF_SIZE, file) != NULL){
		if(is_xyz){
			char *pch = strtok(buffer, " \t\r\n");
			pch = strtok(NULL, " \t\r\n");
			sop.aminos[index].x = atof(pch);
			pch = strtok(NULL, " \t\r\n");
			sop.aminos[index].y = atof(pch);
			pch = strtok(NULL, " \t\r\n");
			sop.aminos[index].z = atof(pch);
			index++;
		}
		if(!is_xyz && strncmp(buffer, "ATOM", 4) == 0){
            PDBAtom tmp;
            tmp.parse(buffer);
			sop.aminos[index].x = tmp.x;
			sop.aminos[index].y = tmp.y;
			sop.aminos[index].z = tmp.z;
#ifdef DEBUG
			printf("%d: %f, %f, %f\n", index, sop.aminos[index].x, sop.aminos[index].y, sop.aminos[index].z);
#endif
			index++;
		}
	}
	fclose(file);
	if(index == 0){
		DIE("Can't read pdb file.\n");
	}
	if(index != sop.aminos.size()){
		DIE("Read coordinates for %d beads, yet topology has %zu beads.\n", index, sop.aminos.size());
	}
	//printf("Done reading coordinates.\n");
}
Ejemplo n.º 2
0
void parse_bam_list( parameters** params)
{
	FILE* bam_list;
	char next_path[1024];
	int i;

	bam_list = safe_fopen( ( *params)->bam_list_path, "r");

	i = 0;
	while( fscanf( bam_list, "%s\n", next_path) == 1)
	{
		set_str( &( ( *params)->bam_file_list)[i], next_path);
		i = i + 1;
	}

	fclose( bam_list);
}
Ejemplo n.º 3
0
void LogHashChange(const char *file, FileState status, char *msg, const Promise *pp)
{
    FILE *fp;
    char fname[CF_BUFSIZE];
    time_t now = time(NULL);
    mode_t perm = 0600;
    static char prevFile[CF_MAXVARSIZE] = ""; /* GLOBAL_X */

// we might get called twice..
    if (strcmp(file, prevFile) == 0)
    {
        return;
    }

    strlcpy(prevFile, file, CF_MAXVARSIZE);

/* This is inefficient but we don't want to lose any data */

    snprintf(fname, CF_BUFSIZE, "%s/state/%s", CFWORKDIR, CF_FILECHANGE_NEW);
    MapName(fname);

#ifndef __MINGW32__
    struct stat sb;
    if (stat(fname, &sb) != -1)
    {
        if (sb.st_mode & (S_IWGRP | S_IWOTH))
        {
            Log(LOG_LEVEL_ERR, "File '%s' (owner %ju) is writable by others (security exception)", fname, (uintmax_t)sb.st_uid);
        }
    }
#endif /* !__MINGW32__ */

    if ((fp = safe_fopen(fname, "a")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Could not write to the hash change log. (fopen: %s)", GetErrorStr());
        return;
    }

    const char *handle = PromiseID(pp);

    fprintf(fp, "%ld,%s,%s,%c,%s\n", (long) now, handle, file, FileStateToChar(status), msg);
    fclose(fp);

    safe_chmod(fname, perm);
}
Ejemplo n.º 4
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);
}
Ejemplo n.º 5
0
Archivo: parser.c Proyecto: awsiv/core
Policy *ParserParseFile(AgentType agent_type, const char *path, unsigned int warnings, unsigned int warnings_error)
{
    ParserStateReset(&P, false);

    P.agent_type = agent_type;
    P.policy = PolicyNew();

    P.warnings = warnings;
    P.warnings_error = warnings_error;

    strncpy(P.filename, path, CF_MAXVARSIZE);

    yyin = safe_fopen(path, "rt");
    if (yyin == NULL)
    {
        Log(LOG_LEVEL_ERR, "While opening file '%s' for parsing. (fopen: %s)", path, GetErrorStr());
        exit(EXIT_FAILURE);
    }

    while (!feof(yyin))
    {
        yyparse();

        if (ferror(yyin))
        {
            perror("cfengine");
            exit(EXIT_FAILURE);
        }
    }

    fclose(yyin);

    if (P.error_count > 0)
    {
        PolicyDestroy(P.policy);
        ParserStateReset(&P, true);
        ParserStateClean(&P);
        return NULL;
    }

    Policy *policy = P.policy;
    ParserStateReset(&P, false);
    ParserStateClean(&P);
    return policy;
}
Ejemplo n.º 6
0
FILE* mutt_bcache_get(body_cache_t *bcache, const char *id)
{
  char path[_POSIX_PATH_MAX];
  FILE* fp = NULL;

  if (!id || !*id || !bcache)
    return NULL;

  path[0] = '\0';
  safe_strncat (path, sizeof (path), bcache->path, bcache->pathlen);
  safe_strncat (path, sizeof (path), id, mutt_strlen (id));

  fp = safe_fopen (path, "r");

  dprint (3, (debugfile, "bcache: get: '%s': %s\n", path, fp == NULL ? "no" : "yes"));

  return fp;
}
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;
}
Ejemplo n.º 8
0
void EvalFileWrite(const void *mode, qCtx *ctx, qStr *out, qArgAry *args)
{
	CStr path = ctx->ParseStr((*args)[0]);
	FILE *fp;
	int err = 0;

#ifndef WIN32
	CStr perm_str = ctx->ParseStr((*args)[2]);
	int perms = strtol(perm_str.SafeP(),(char **)NULL, 0);
	mode_t prev_perms;
	if (perms) {
		prev_perms = umask((mode_t)~perms);
		printf("umask: %d (%d)\n", perms, prev_perms);
	}
	try {	
#endif

	if (path.IsEmpty())
		return;

	fp = safe_fopen(ctx, path, (const char *) mode);

	if (!fp) err = GetLastError();

#ifndef WIN32
	} catch (qCtxEx ex) {
	        if (perms) umask(prev_perms);
		throw ex;
	}
        if (perms) umask(prev_perms);
#endif

	if (!fp) {
		ctx->ThrowF(out, 601, "Failed to open file for writing. %y", err);
		return;
	}

	qStrFileO fo(fp, true);

	qCtxTmp sub(ctx);
	sub.MapObj(fp, EvalFileFlush,"flush");
	sub.Parse(args->GetAt(1), &fo);
}
Ejemplo n.º 9
0
static bool PrintFile(const char *filename, size_t max_lines)
{
    if (!filename)
    {
        Log(LOG_LEVEL_VERBOSE, "Printfile promise was incomplete, with no filename.");
        return false;
    }

    FILE *fp = safe_fopen(filename, "r");
    if (!fp)
    {
        Log(LOG_LEVEL_ERR, "Printing of file '%s' was not possible. (fopen: %s)", filename, GetErrorStr());
        return false;
    }

    size_t line_size = CF_BUFSIZE;
    char *line = xmalloc(line_size);

    for (size_t i = 0; i < max_lines; i++)
    {
        if (CfReadLine(&line, &line_size, fp) == -1)
        {
            if (ferror(fp))
            {
                Log(LOG_LEVEL_ERR, "Failed to read line from stream, (getline: %s)", GetErrorStr());
                free(line);
                return false;
            }
            else
            {
                break;
            }
        }

        ReportToLog(line);
    }

    fclose(fp);
    free(line);

    return true;
}
Ejemplo n.º 10
0
int _mutt_rename_file (char *oldfile, char *newfile, int overwrite)
{
  FILE *ofp, *nfp;

  if (access (oldfile, F_OK) != 0)
    return 1;
  if (!overwrite && access (newfile, F_OK) == 0)
    return 2;
  if ((ofp = fopen (oldfile, "r")) == NULL)
    return 3;
  if ((nfp = safe_fopen (newfile, "w")) == NULL) {
    fclose (ofp);
    return 3;
  }
  mutt_copy_stream (ofp, nfp);
  fclose (nfp);
  fclose (ofp);
  mutt_unlink (oldfile);
  return 0;
}
Ejemplo n.º 11
0
static void PrintFile(EvalContext *ctx, Attributes a, Promise *pp)
{
    FILE *fp;
    char buffer[CF_BUFSIZE];
    int lines = 0;

    if (a.report.filename == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Printfile promise was incomplete, with no filename.");
        return;
    }

    if ((fp = safe_fopen(a.report.filename, "r")) == NULL)
    {
        cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, "Printing of file '%s' was not possible. (fopen: %s)", a.report.filename, GetErrorStr());
        return;
    }

    while ((lines < a.report.numlines))
    {
        if (fgets(buffer, sizeof(buffer), fp) == NULL)
        {
            if (ferror(fp))
            {
                UnexpectedError("Failed to read line from stream");
                break;
            }
            else /* feof */
            {
                break;
            }
        }
        Log(LOG_LEVEL_ERR, "R: %s", buffer);
        lines++;
    }

    fclose(fp);
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
0
void initialise_3d_displacement_maps ( char *filename )
{

	FILE
		*fp;

	int
		count;

	fp = safe_fopen ( filename, "rb" );

	fread ( &number_of_displacement_maps, sizeof ( int ), 1, fp );

	if ( number_of_displacement_maps )
	{

		displacement_maps = safe_malloc ( sizeof ( displacement_map ) * number_of_displacement_maps );
	
		for ( count = 0; count < number_of_displacement_maps; count++ )
		{

			int
				width,
				height;
	
			fread ( &width, sizeof ( int ), 1, fp );
			fread ( &height, sizeof ( int ), 1, fp );

			displacement_maps[count].width = width;
			displacement_maps[count].height = height;

			displacement_maps[count].data = safe_malloc ( width * height );

			fread ( displacement_maps[count].data, width, height, fp );
		}
	}
}
Ejemplo n.º 14
0
void PDB::read(const char* filename){
	printf("Reading %s.\n", filename);
	this->is_xyz = (!strcmp(filename + strlen(filename)-4, ".xyz"));
	if (this->is_xyz) {
		this->readXYZ(filename);
		return;
	}

	char buffer[BUF_SIZE];
	FILE* file = safe_fopen(filename, "r");

	while(fgets(buffer, BUF_SIZE, file) != NULL){
		if(strncmp(buffer,"SSBOND",6) == 0){
            this->ssbonds.push_back(PDBSSBond(buffer));
		}
		if(strncmp(buffer, "ATOM", 4) == 0){
            this->atoms.push_back(PDBAtom(buffer));
		}
	}

	printf("Found %zu atoms and %zu SS-bonds.\n", this->atoms.size(), this->ssbonds.size());
	printf("Done reading '%s'.\n", filename);
	fclose(file);
}
Ejemplo n.º 15
0
/* returns 0 on success, -1 on error */
int mutt_decode_save_attachment (FILE *fp, BODY *m, char *path,
				 int displaying, int flags)
{
  STATE s;
  unsigned int saved_encoding = 0;
  BODY *saved_parts = NULL;
  HEADER *saved_hdr = NULL;

  memset (&s, 0, sizeof (s));
  s.flags = displaying;

  if (flags == M_SAVE_APPEND)
    s.fpout = fopen (path, "a");
  else if (flags == M_SAVE_OVERWRITE)
    s.fpout = fopen (path, "w");	/* __FOPEN_CHECKED__ */
  else
    s.fpout = safe_fopen (path, "w");

  if (s.fpout == NULL)
  {
    mutt_perror ("fopen");
    return (-1);
  }

  if (fp == NULL)
  {
    /* When called from the compose menu, the attachment isn't parsed,
     * so we need to do it here. */
    struct stat st;

    if (stat (m->filename, &st) == -1)
    {
      mutt_perror ("stat");
      safe_fclose (&s.fpout);
      return (-1);
    }

    if ((s.fpin = fopen (m->filename, "r")) == NULL)
    {
      mutt_perror ("fopen");
      return (-1);
    }

    saved_encoding = m->encoding;
    if (!is_multipart (m))
      m->encoding = ENC8BIT;
    
    m->length = st.st_size;
    m->offset = 0;
    saved_parts = m->parts;
    saved_hdr = m->hdr;
    mutt_parse_part (s.fpin, m);

    if (m->noconv || is_multipart (m))
      s.flags |= M_CHARCONV;
  }
  else
  {
    s.fpin = fp;
    s.flags |= M_CHARCONV;
  }

  mutt_body_handler (m, &s);

  safe_fclose (&s.fpout);
  if (fp == NULL)
  {
    m->length = 0;
    m->encoding = saved_encoding;
    if (saved_parts)
    {
      mutt_free_header (&m->hdr);
      m->parts = saved_parts;
      m->hdr = saved_hdr;
    }
    safe_fclose (&s.fpin);
  }

  return (0);
}
Ejemplo n.º 16
0
int mutt_prepare_template (FILE *fp, CONTEXT *ctx, HEADER *newhdr, HEADER *hdr,
			       short weed)
{
  MESSAGE *msg = NULL;
  char file[_POSIX_PATH_MAX];
  BODY *b;
  FILE *bfp;

  int rv = -1;
  STATE s;

  memset (&s, 0, sizeof (s));

  if (!fp && (msg = mx_open_message (ctx, hdr->msgno)) == NULL)
    return (-1);

  if (!fp) fp = msg->fp;

  bfp = fp;

  /* parse the message header and MIME structure */

  fseeko (fp, hdr->offset, 0);
  newhdr->offset = hdr->offset;
  newhdr->env = mutt_read_rfc822_header (fp, newhdr, 1, weed);
  newhdr->content->length = hdr->content->length;
  mutt_parse_part (fp, newhdr->content);

  /* If message_id is set, then we are resending a message and don't want
   * message_id or mail_followup_to. Otherwise, we are resuming a
   * postponed message, and want to keep the mail_followup_to.
   */
  if (newhdr->env->message_id != NULL)
  {
    FREE (&newhdr->env->message_id);
    FREE (&newhdr->env->mail_followup_to);
  }

  /* decrypt pgp/mime encoded messages */

  if ((WithCrypto & (APPLICATION_PGP|APPLICATION_SMIME) & hdr->security)
      && mutt_is_multipart_encrypted (newhdr->content))
  {
    int ccap = WithCrypto & (APPLICATION_PGP|APPLICATION_SMIME) & hdr->security;
    newhdr->security |= ENCRYPT | ccap;
    if (!crypt_valid_passphrase (ccap))
      goto err;

    mutt_message _("Decrypting message...");
    if (((ccap & APPLICATION_PGP) && crypt_pgp_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
	|| ((ccap & APPLICATION_SMIME) && crypt_smime_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
	|| b == NULL)
    {
 err:
      mx_close_message (&msg);
      mutt_free_envelope (&newhdr->env);
      mutt_free_body (&newhdr->content);
      mutt_error _("Decryption failed.");
      return -1;
    }

    mutt_free_body (&newhdr->content);
    newhdr->content = b;

    mutt_clear_error ();
  }

  /*
   * remove a potential multipart/signed layer - useful when
   * resending messages
   */

  if (WithCrypto && mutt_is_multipart_signed (newhdr->content))
  {
    newhdr->security |= SIGN;
    if ((WithCrypto & APPLICATION_PGP)
        && ascii_strcasecmp (mutt_get_parameter ("protocol", newhdr->content->parameter), "application/pgp-signature") == 0)
      newhdr->security |= APPLICATION_PGP;
    else if ((WithCrypto & APPLICATION_SMIME))
      newhdr->security |= APPLICATION_SMIME;

    /* destroy the signature */
    mutt_free_body (&newhdr->content->parts->next);
    newhdr->content = mutt_remove_multipart (newhdr->content);
  }


  /*
   * We don't need no primary multipart.
   * Note: We _do_ preserve messages!
   *
   * XXX - we don't handle multipart/alternative in any
   * smart way when sending messages.  However, one may
   * consider this a feature.
   *
   */

  if (newhdr->content->type == TYPEMULTIPART)
    newhdr->content = mutt_remove_multipart (newhdr->content);

  s.fpin = bfp;

  /* create temporary files for all attachments */
  for (b = newhdr->content; b; b = b->next)
  {

    /* what follows is roughly a receive-mode variant of
     * mutt_get_tmp_attachment () from muttlib.c
     */

    file[0] = '\0';
    if (b->filename)
    {
      strfcpy (file, b->filename, sizeof (file));
      b->d_filename = safe_strdup (b->filename);
    }
    else
    {
      /* avoid Content-Disposition: header with temporary filename */
      b->use_disp = 0;
    }

    /* set up state flags */

    s.flags = 0;

    if (b->type == TYPETEXT)
    {
      if (!ascii_strcasecmp ("yes", mutt_get_parameter ("x-mutt-noconv", b->parameter)))
	b->noconv = 1;
      else
      {
	s.flags |= M_CHARCONV;
	b->noconv = 0;
      }

      mutt_delete_parameter ("x-mutt-noconv", &b->parameter);
    }

    mutt_adv_mktemp (file, sizeof(file));
    if ((s.fpout = safe_fopen (file, "w")) == NULL)
      goto bail;


    if ((WithCrypto & APPLICATION_PGP)
	&& (mutt_is_application_pgp (b) & (ENCRYPT|SIGN)))
    {

      mutt_body_handler (b, &s);

      newhdr->security |= mutt_is_application_pgp (newhdr->content);

      b->type = TYPETEXT;
      mutt_str_replace (&b->subtype, "plain");
      mutt_delete_parameter ("x-action", &b->parameter);
    }
    else
      mutt_decode_attachment (b, &s);

    if (safe_fclose (&s.fpout) != 0)
      goto bail;

    mutt_str_replace (&b->filename, file);
    b->unlink = 1;

    mutt_stamp_attachment (b);

    mutt_free_body (&b->parts);
    if (b->hdr) b->hdr->content = NULL; /* avoid dangling pointer */
  }

  /* Fix encryption flags. */

  /* No inline if multipart. */
  if (WithCrypto && (newhdr->security & INLINE) && newhdr->content->next)
    newhdr->security &= ~INLINE;

  /* Do we even support multiple mechanisms? */
  newhdr->security &= WithCrypto | ~(APPLICATION_PGP|APPLICATION_SMIME);

  /* Theoretically, both could be set. Take the one the user wants to set by default. */
  if ((newhdr->security & APPLICATION_PGP) && (newhdr->security & APPLICATION_SMIME))
  {
    if (option (OPTSMIMEISDEFAULT))
      newhdr->security &= ~APPLICATION_PGP;
    else
      newhdr->security &= ~APPLICATION_SMIME;
  }

  rv = 0;

  bail:

  /* that's it. */
  if (bfp != fp) safe_fclose (&bfp);
  if (msg) mx_close_message (&msg);

  if (rv == -1)
  {
    mutt_free_envelope (&newhdr->env);
    mutt_free_body (&newhdr->content);
  }

  return rv;
}
Ejemplo n.º 17
0
int main(int argc, char** argv) {
    int32_t opt,nqrys,qrylen,i;
    char* idxname;char* textname;
    uint8_t* T;
    uint32_t n;
    FILE* f;
    FM* FMIdx;
	uint8_t** queries;
	char buf[4096];
	uint32_t start,stop,cnt;
    
    /* parse command line parameter */
    if (argc <= 3) {
        print_usage(argv[0]);
        exit(EXIT_FAILURE);
    }
    
	opt = -1;
    idxname = textname = NULL;
    while ((opt = getopt(argc, argv, "vhi:l:t:n:")) != -1) {
        switch (opt) {
            case 'l':
                qrylen = atoi(optarg);
                break;
            case 'n':
                nqrys = atoi(optarg);
                break;
            case 't':
                textname = optarg;
                break;
			case 'i':
				idxname = optarg;
				break;
			case 'v':
				FM::verbose = 1;
				break;
            case 'h':
            default:
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }
	
		
	/* load index */
	FMIdx = FM::load(idxname);
	if(!FMIdx) {
		perror("error loading index from file");
		exit(EXIT_FAILURE);
	}
	
	/* generate queries */
    f = safe_fopen(textname,"r");
    n = safe_filesize(f);
    T = (uint8_t*) safe_malloc(n*sizeof(uint8_t));
    if( fread(T,1,n,f) != n ) {
        perror("error reading text");
        exit(EXIT_FAILURE);
    }
	fclose(f);

	FM::info("generating queries");
	srand( gettime() );
	queries = (uint8_t**) safe_malloc(nqrys * sizeof(uint8_t*));
	for(i=0;i<nqrys;i++) {
	    start = (rand()*rand()) % (n-qrylen-1);
        memcpy(buf,(uint8_t*)(T+start),qrylen);
        queries[i] = (uint8_t*) safe_strdup(buf);
    }
	
	start = gettime();
	for(i=0;i<nqrys;i++) {
		cnt = FMIdx->count(queries[i],strlen((char*)queries[i]));
	}
	stop = gettime();
	FM::info("finished processing %d queries: %f sec",nqrys,((float)(stop-start))/1000000);
	
	/* clean up */
	for(i=0;i<nqrys;i++) free(queries[i]);
	free(queries);
	free(T);
	delete FMIdx;
    
    return (EXIT_SUCCESS);
}
Ejemplo n.º 18
0
static int CompareResult(const char *filename, const char *prev_file)
{
    Log(LOG_LEVEL_VERBOSE, "Comparing files  %s with %s", prev_file, filename);

    int rtn = 0;

    FILE *old_fp = safe_fopen(prev_file, "r");
    FILE *new_fp = safe_fopen(filename, "r");
    if (old_fp && new_fp)
    {
        const char *errptr;
        int erroffset;
        pcre_extra *regex_extra = NULL;
        // Match timestamps and remove them. Not Y21K safe! :-)
        pcre *regex = pcre_compile(LOGGING_TIMESTAMP_REGEX, PCRE_MULTILINE, &errptr, &erroffset, NULL);
        if (!regex)
        {
            UnexpectedError("Compiling regular expression failed");
            rtn = 1;
        }
        else
        {
            regex_extra = pcre_study(regex, 0, &errptr);
        }

        while (regex)
        {
            char old_line[CF_BUFSIZE];
            char new_line[CF_BUFSIZE];
            char *old_msg = old_line;
            char *new_msg = new_line;
            if (CfReadLine(old_line, sizeof(old_line), old_fp) <= 0)
            {
                old_msg = NULL;
            }
            if (CfReadLine(new_line, sizeof(new_line), new_fp) <= 0)
            {
                new_msg = NULL;
            }
            if (!old_msg || !new_msg)
            {
                if (old_msg != new_msg)
                {
                    rtn = 1;
                }
                break;
            }

            char *index;
            if (pcre_exec(regex, regex_extra, old_msg, strlen(old_msg), 0, 0, NULL, 0) >= 0)
            {
                index = strstr(old_msg, ": ");
                if (index != NULL)
                {
                    old_msg = index + 2;
                }
            }
            if (pcre_exec(regex, regex_extra, new_msg, strlen(new_msg), 0, 0, NULL, 0) >= 0)
            {
                index = strstr(new_msg, ": ");
                if (index != NULL)
                {
                    new_msg = index + 2;
                }
            }

            if (strcmp(old_msg, new_msg) != 0)
            {
                rtn = 1;
                break;
            }
        }

        if (regex_extra)
        {
            free(regex_extra);
        }
        free(regex);
    }
    else
    {
        /* no previous file */
        rtn = 1;
    }

    if (old_fp)
    {
        fclose(old_fp);
    }
    if (new_fp)
    {
        fclose(new_fp);
    }

    if (!ThreadLock(cft_count))
    {
        Log(LOG_LEVEL_ERR, "Severe lock error when mailing in exec");
        return 1;
    }

/* replace old file with new*/

    unlink(prev_file);

    if (!LinkOrCopy(filename, prev_file, true))
    {
        Log(LOG_LEVEL_INFO, "Could not symlink or copy '%s' to '%s'", filename, prev_file);
        rtn = 1;
    }

    ThreadUnlock(cft_count);
    return rtn;
}
Ejemplo n.º 19
0
/* imap_read_headers:
 * Changed to read many headers instead of just one. It will return the
 * msgno of the last message read. It will return a value other than
 * msgend if mail comes in while downloading headers (in theory).
 */
int imap_read_headers (IMAP_DATA* idata, int msgbegin, int msgend)
{
  CONTEXT* ctx;
  char *hdrreq = NULL;
  FILE *fp;
  char tempfile[_POSIX_PATH_MAX];
  int msgno, idx = msgbegin - 1;
  IMAP_HEADER h;
  IMAP_STATUS* status;
  int rc, mfhrc, oldmsgcount;
  int fetchlast = 0;
  int maxuid = 0;
  static const char * const want_headers = "DATE FROM SUBJECT TO CC MESSAGE-ID REFERENCES CONTENT-TYPE CONTENT-DESCRIPTION IN-REPLY-TO REPLY-TO LINES LIST-POST X-LABEL";
  progress_t progress;
  int retval = -1;

#if USE_HCACHE
  char buf[LONG_STRING];
  unsigned int *uid_validity = NULL;
  unsigned int *puidnext = NULL;
  unsigned int uidnext = 0;
  int evalhc = 0;
#endif /* USE_HCACHE */

  ctx = idata->ctx;

  if (mutt_bit_isset (idata->capabilities,IMAP4REV1))
  {
    safe_asprintf (&hdrreq, "BODY.PEEK[HEADER.FIELDS (%s%s%s)]",
                           want_headers, ImapHeaders ? " " : "", NONULL (ImapHeaders));
  }
  else if (mutt_bit_isset (idata->capabilities,IMAP4))
  {
    safe_asprintf (&hdrreq, "RFC822.HEADER.LINES (%s%s%s)",
                           want_headers, ImapHeaders ? " " : "", NONULL (ImapHeaders));
  }
  else
  {	/* Unable to fetch headers for lower versions */
    mutt_error _("Unable to fetch headers from this IMAP server version.");
    mutt_sleep (2);	/* pause a moment to let the user see the error */
    goto error_out_0;
  }

  /* instead of downloading all headers and then parsing them, we parse them
   * as they come in. */
  mutt_mktemp (tempfile, sizeof (tempfile));
  if (!(fp = safe_fopen (tempfile, "w+")))
  {
    mutt_error (_("Could not create temporary file %s"), tempfile);
    mutt_sleep (2);
    goto error_out_0;
  }
  unlink (tempfile);

  /* make sure context has room to hold the mailbox */
  while ((msgend) >= idata->ctx->hdrmax)
    mx_alloc_memory (idata->ctx);

  oldmsgcount = ctx->msgcount;
  idata->reopen &= ~(IMAP_REOPEN_ALLOW|IMAP_NEWMAIL_PENDING);
  idata->newMailCount = 0;

#if USE_HCACHE
  idata->hcache = imap_hcache_open (idata, NULL);

  if (idata->hcache && !msgbegin)
  {
    uid_validity = mutt_hcache_fetch_raw (idata->hcache, "/UIDVALIDITY", imap_hcache_keylen);
    puidnext = mutt_hcache_fetch_raw (idata->hcache, "/UIDNEXT", imap_hcache_keylen);
    if (puidnext)
    {
      uidnext = *puidnext;
      FREE (&puidnext);
    }
    if (uid_validity && uidnext && *uid_validity == idata->uid_validity)
      evalhc = 1;
    FREE (&uid_validity);
  }
  if (evalhc)
  {
    /* L10N:
       Comparing the cached data with the IMAP server's data */
    mutt_progress_init (&progress, _("Evaluating cache..."),
			MUTT_PROGRESS_MSG, ReadInc, msgend + 1);

    snprintf (buf, sizeof (buf),
      "UID FETCH 1:%u (UID FLAGS)", uidnext - 1);

    imap_cmd_start (idata, buf);

    rc = IMAP_CMD_CONTINUE;
    for (msgno = msgbegin; rc == IMAP_CMD_CONTINUE; msgno++)
    {
      mutt_progress_update (&progress, msgno + 1, -1);

      memset (&h, 0, sizeof (h));
      h.data = safe_calloc (1, sizeof (IMAP_HEADER_DATA));
      do
      {
        mfhrc = 0;

        rc = imap_cmd_step (idata);
        if (rc != IMAP_CMD_CONTINUE)
	{
	  imap_free_header_data (&h.data);
          break;
	}

        /* hole in the header cache */
        if (!evalhc)
          continue;

        if ((mfhrc = msg_fetch_header (ctx, &h, idata->buf, NULL)) == -1)
          continue;
        else if (mfhrc < 0)
	{
	  imap_free_header_data (&h.data);
          break;
	}

        if (!h.data->uid)
        {
          dprint (2, (debugfile, "imap_read_headers: skipping hcache FETCH "
                      "response for unknown message number %d\n", h.sid));
          mfhrc = -1;
          continue;
        }

        idx++;
        ctx->hdrs[idx] = imap_hcache_get (idata, h.data->uid);
        if (ctx->hdrs[idx])
        {
  	  ctx->hdrs[idx]->index = idx;
  	  /* messages which have not been expunged are ACTIVE (borrowed from mh
  	   * folders) */
  	  ctx->hdrs[idx]->active = 1;
          ctx->hdrs[idx]->read = h.data->read;
          ctx->hdrs[idx]->old = h.data->old;
          ctx->hdrs[idx]->deleted = h.data->deleted;
          ctx->hdrs[idx]->flagged = h.data->flagged;
          ctx->hdrs[idx]->replied = h.data->replied;
          ctx->hdrs[idx]->changed = h.data->changed;
          /*  ctx->hdrs[msgno]->received is restored from mutt_hcache_restore */
          ctx->hdrs[idx]->data = (void *) (h.data);

          ctx->msgcount++;
          ctx->size += ctx->hdrs[idx]->content->length;
        }
	else
        {
	  /* bad header in the cache, we'll have to refetch. */
          dprint (3, (debugfile, "bad cache entry at %d, giving up\n", h.sid - 1));
          imap_free_header_data(&h.data);
          evalhc = 0;
          idx--;
        }
      }
      while (rc != IMAP_CMD_OK && mfhrc == -1);
      if (rc == IMAP_CMD_OK)
        break;
      if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK)))
      {
        imap_free_header_data (&h.data);
        imap_hcache_close (idata);
	goto error_out_1;
      }
    }
    /* could also look for first null header in case hcache is holey */
    msgbegin = ctx->msgcount;
  }
#endif /* USE_HCACHE */

  mutt_progress_init (&progress, _("Fetching message headers..."),
		      MUTT_PROGRESS_MSG, ReadInc, msgend + 1);

  for (msgno = msgbegin; msgno <= msgend ; msgno++)
  {
    mutt_progress_update (&progress, msgno + 1, -1);

    /* we may get notification of new mail while fetching headers */
    if (msgno + 1 > fetchlast)
    {
      char *cmd;

      fetchlast = msgend + 1;
      safe_asprintf (&cmd, "FETCH %d:%d (UID FLAGS INTERNALDATE RFC822.SIZE %s)",
                     msgno + 1, fetchlast, hdrreq);
      imap_cmd_start (idata, cmd);
      FREE (&cmd);
    }

    rewind (fp);
    memset (&h, 0, sizeof (h));
    h.data = safe_calloc (1, sizeof (IMAP_HEADER_DATA));

    /* this DO loop does two things:
     * 1. handles untagged messages, so we can try again on the same msg
     * 2. fetches the tagged response at the end of the last message.
     */
    do
    {
      mfhrc = 0;

      rc = imap_cmd_step (idata);
      if (rc != IMAP_CMD_CONTINUE)
	break;

      if ((mfhrc = msg_fetch_header (ctx, &h, idata->buf, fp)) == -1)
	continue;
      else if (mfhrc < 0)
	break;

      if (!ftello (fp))
      {
        dprint (2, (debugfile, "msg_fetch_header: ignoring fetch response with no body\n"));
        mfhrc = -1;
        msgend--;
        continue;
      }

      /* make sure we don't get remnants from older larger message headers */
      fputs ("\n\n", fp);

      idx++;
      if (idx > msgend)
      {
        dprint (1, (debugfile, "imap_read_headers: skipping FETCH response for "
                    "unknown message number %d\n", h.sid));
        mfhrc = -1;
        idx--;
        continue;
      }
      /* May receive FLAGS updates in a separate untagged response (#2935) */
      if (idx < ctx->msgcount)
      {
	dprint (2, (debugfile, "imap_read_headers: message %d is not new\n",
		    h.sid));
        idx--;
	continue;
      }

      ctx->hdrs[idx] = mutt_new_header ();

      ctx->hdrs[idx]->index = h.sid - 1;
      /* messages which have not been expunged are ACTIVE (borrowed from mh
       * folders) */
      ctx->hdrs[idx]->active = 1;
      ctx->hdrs[idx]->read = h.data->read;
      ctx->hdrs[idx]->old = h.data->old;
      ctx->hdrs[idx]->deleted = h.data->deleted;
      ctx->hdrs[idx]->flagged = h.data->flagged;
      ctx->hdrs[idx]->replied = h.data->replied;
      ctx->hdrs[idx]->changed = h.data->changed;
      ctx->hdrs[idx]->received = h.received;
      ctx->hdrs[idx]->data = (void *) (h.data);

      if (maxuid < h.data->uid)
        maxuid = h.data->uid;

      rewind (fp);
      /* NOTE: if Date: header is missing, mutt_read_rfc822_header depends
       *   on h.received being set */
      ctx->hdrs[idx]->env = mutt_read_rfc822_header (fp, ctx->hdrs[idx],
        0, 0);
      /* content built as a side-effect of mutt_read_rfc822_header */
      ctx->hdrs[idx]->content->length = h.content_length;
      ctx->size += h.content_length;

#if USE_HCACHE
      imap_hcache_put (idata, ctx->hdrs[idx]);
#endif /* USE_HCACHE */

      ctx->msgcount++;
    }
    while ((rc != IMAP_CMD_OK) && ((mfhrc == -1) ||
      ((msgno + 1) >= fetchlast)));

    if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK)))
    {
      imap_free_header_data (&h.data);
#if USE_HCACHE
      imap_hcache_close (idata);
#endif
      goto error_out_1;
    }

    /* in case we get new mail while fetching the headers */
    if (idata->reopen & IMAP_NEWMAIL_PENDING)
    {
      msgend = idata->newMailCount - 1;
      while ((msgend) >= ctx->hdrmax)
	mx_alloc_memory (ctx);
      idata->reopen &= ~IMAP_NEWMAIL_PENDING;
      idata->newMailCount = 0;
    }
  }

  if (maxuid && (status = imap_mboxcache_get (idata, idata->mailbox, 0)) &&
      (status->uidnext < maxuid + 1))
    status->uidnext = maxuid + 1;

#if USE_HCACHE
  mutt_hcache_store_raw (idata->hcache, "/UIDVALIDITY", &idata->uid_validity,
                         sizeof (idata->uid_validity), imap_hcache_keylen);
  if (maxuid && idata->uidnext < maxuid + 1)
  {
    dprint (2, (debugfile, "Overriding UIDNEXT: %u -> %u\n", idata->uidnext, maxuid + 1));
    idata->uidnext = maxuid + 1;
  }
  if (idata->uidnext > 1)
    mutt_hcache_store_raw (idata->hcache, "/UIDNEXT", &idata->uidnext,
			   sizeof (idata->uidnext), imap_hcache_keylen);

  imap_hcache_close (idata);
#endif /* USE_HCACHE */

  if (ctx->msgcount > oldmsgcount)
  {
    mx_alloc_memory(ctx);
    mx_update_context (ctx, ctx->msgcount - oldmsgcount);
  }

  idata->reopen |= IMAP_REOPEN_ALLOW;

  retval = msgend;

error_out_1:
  safe_fclose (&fp);

error_out_0:
  FREE (&hdrreq);

  return retval;
}
Ejemplo n.º 20
0
int imap_fetch_message (CONTEXT *ctx, MESSAGE *msg, int msgno)
{
  IMAP_DATA* idata;
  HEADER* h;
  ENVELOPE* newenv;
  char buf[LONG_STRING];
  char path[_POSIX_PATH_MAX];
  char *pc;
  long bytes;
  progress_t progressbar;
  int uid;
  int cacheno;
  IMAP_CACHE *cache;
  int read;
  int rc;
  /* Sam's weird courier server returns an OK response even when FETCH
   * fails. Thanks Sam. */
  short fetched = 0;

  idata = (IMAP_DATA*) ctx->data;
  h = ctx->hdrs[msgno];

  if ((msg->fp = msg_cache_get (idata, h)))
  {
    if (HEADER_DATA(h)->parsed)
      return 0;
    else
      goto parsemsg;
  }

  /* we still do some caching even if imap_cachedir is unset */
  /* see if we already have the message in our cache */
  cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN;
  cache = &idata->cache[cacheno];

  if (cache->path)
  {
    /* don't treat cache errors as fatal, just fall back. */
    if (cache->uid == HEADER_DATA(h)->uid &&
        (msg->fp = fopen (cache->path, "r")))
      return 0;
    else
    {
      unlink (cache->path);
      FREE (&cache->path);
    }
  }

  if (!isendwin())
    mutt_message _("Fetching message...");

  if (!(msg->fp = msg_cache_put (idata, h)))
  {
    cache->uid = HEADER_DATA(h)->uid;
    mutt_mktemp (path, sizeof (path));
    cache->path = safe_strdup (path);
    if (!(msg->fp = safe_fopen (path, "w+")))
    {
      FREE (&cache->path);
      return -1;
    }
  }

  /* mark this header as currently inactive so the command handler won't
   * also try to update it. HACK until all this code can be moved into the
   * command handler */
  h->active = 0;

  snprintf (buf, sizeof (buf), "UID FETCH %u %s", HEADER_DATA(h)->uid,
	    (mutt_bit_isset (idata->capabilities, IMAP4REV1) ?
	     (option (OPTIMAPPEEK) ? "BODY.PEEK[]" : "BODY[]") :
	     "RFC822"));

  imap_cmd_start (idata, buf);
  do
  {
    if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
      break;

    pc = idata->buf;
    pc = imap_next_word (pc);
    pc = imap_next_word (pc);

    if (!ascii_strncasecmp ("FETCH", pc, 5))
    {
      while (*pc)
      {
	pc = imap_next_word (pc);
	if (pc[0] == '(')
	  pc++;
	if (ascii_strncasecmp ("UID", pc, 3) == 0)
	{
	  pc = imap_next_word (pc);
	  uid = atoi (pc);
	  if (uid != HEADER_DATA(h)->uid)
	    mutt_error (_("The message index is incorrect. Try reopening the mailbox."));
	}
	else if ((ascii_strncasecmp ("RFC822", pc, 6) == 0) ||
		 (ascii_strncasecmp ("BODY[]", pc, 6) == 0))
	{
	  pc = imap_next_word (pc);
	  if (imap_get_literal_count(pc, &bytes) < 0)
	  {
	    imap_error ("imap_fetch_message()", buf);
	    goto bail;
	  }
	  mutt_progress_init (&progressbar, _("Fetching message..."),
			      MUTT_PROGRESS_SIZE, NetInc, bytes);
	  if (imap_read_literal (msg->fp, idata, bytes, &progressbar) < 0)
	    goto bail;
	  /* pick up trailing line */
	  if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
	    goto bail;
	  pc = idata->buf;

	  fetched = 1;
	}
	/* UW-IMAP will provide a FLAGS update here if the FETCH causes a
	 * change (eg from \Unseen to \Seen).
	 * Uncommitted changes in mutt take precedence. If we decide to
	 * incrementally update flags later, this won't stop us syncing */
	else if ((ascii_strncasecmp ("FLAGS", pc, 5) == 0) && !h->changed)
	{
	  if ((pc = imap_set_flags (idata, h, pc)) == NULL)
	    goto bail;
	}
      }
    }
  }
  while (rc == IMAP_CMD_CONTINUE);

  /* see comment before command start. */
  h->active = 1;

  fflush (msg->fp);
  if (ferror (msg->fp))
  {
    mutt_perror (cache->path);
    goto bail;
  }

  if (rc != IMAP_CMD_OK)
    goto bail;

  if (!fetched || !imap_code (idata->buf))
    goto bail;

  msg_cache_commit (idata, h);

  parsemsg:
  /* Update the header information.  Previously, we only downloaded a
   * portion of the headers, those required for the main display.
   */
  rewind (msg->fp);
  /* It may be that the Status header indicates a message is read, but the
   * IMAP server doesn't know the message has been \Seen. So we capture
   * the server's notion of 'read' and if it differs from the message info
   * picked up in mutt_read_rfc822_header, we mark the message (and context
   * changed). Another possibility: ignore Status on IMAP?*/
  read = h->read;
  newenv = mutt_read_rfc822_header (msg->fp, h, 0, 0);
  mutt_merge_envelopes(h->env, &newenv);

  /* see above. We want the new status in h->read, so we unset it manually
   * and let mutt_set_flag set it correctly, updating context. */
  if (read != h->read)
  {
    h->read = read;
    mutt_set_flag (ctx, h, MUTT_NEW, read);
  }

  h->lines = 0;
  fgets (buf, sizeof (buf), msg->fp);
  while (!feof (msg->fp))
  {
    h->lines++;
    fgets (buf, sizeof (buf), msg->fp);
  }

  h->content->length = ftell (msg->fp) - h->content->offset;

  /* This needs to be done in case this is a multipart message */
#if defined(HAVE_PGP) || defined(HAVE_SMIME)
  h->security = crypt_query (h->content);
#endif

  mutt_clear_error();
  rewind (msg->fp);
  HEADER_DATA(h)->parsed = 1;

  return 0;

bail:
  safe_fclose (&msg->fp);
  imap_cache_del (idata, h);
  if (cache->path)
  {
    unlink (cache->path);
    FREE (&cache->path);
  }

  return -1;
}
Ejemplo n.º 21
0
int LoadFileAsItemList(Item **liststart, const char *file, EditDefaults edits)
{
    {
        struct stat statbuf;
        if (stat(file, &statbuf) == -1)
        {
            Log(LOG_LEVEL_VERBOSE, "The proposed file '%s' could not be loaded. (stat: %s)", file, GetErrorStr());
            return false;
        }

        if (edits.maxfilesize != 0 && statbuf.st_size > edits.maxfilesize)
        {
            Log(LOG_LEVEL_INFO, "File '%s' is bigger than the limit edit.max_file_size = %jd > %d bytes", file,
                  (intmax_t) statbuf.st_size, edits.maxfilesize);
            return (false);
        }

        if (!S_ISREG(statbuf.st_mode))
        {
            Log(LOG_LEVEL_INFO, "%s is not a plain file", file);
            return false;
        }
    }

    FILE *fp = safe_fopen(file, "r");
    if (!fp)
    {
        Log(LOG_LEVEL_INFO, "Couldn't read file '%s' for editing. (fopen: %s)", file, GetErrorStr());
        return false;
    }

    Buffer *concat = BufferNew();

    size_t line_size = CF_BUFSIZE;
    char *line = xmalloc(line_size);
    bool result = true;

    for (;;)
    {
        ssize_t num_read = CfReadLine(&line, &line_size, fp);
        if (num_read == -1)
        {
            if (!feof(fp))
            {
                Log(LOG_LEVEL_ERR,
                    "Unable to read contents of '%s'. (fread: %s)",
                    file, GetErrorStr());
                result = false;
            }
            break;
        }

        if (edits.joinlines && *(line + strlen(line) - 1) == '\\')
        {
            *(line + strlen(line) - 1) = '\0';

            BufferAppend(concat, line, num_read);
        }
        else
        {
            BufferAppend(concat, line, num_read);
            if (!feof(fp) || (BufferSize(concat) > 0))
            {
                AppendItem(liststart, BufferData(concat), NULL);
            }
        }

        BufferZero(concat);
    }

    free(line);
    BufferDestroy(concat);
    fclose(fp);
    return result;
}
Ejemplo n.º 22
0
}

// WARNING: filename like ".gitignore" will treat all things after "." as a suffix
tCString getfilesuffix(tCString filename)
{
    tCString dot = strrchr(filename, '.');
    return dot ? mystrdup(dot + 1) : NULL;
}

DATA_BLOCK read_file_into_memory(tCString path)
{
    DATA_BLOCK datablock = {
        .data = NULL,
        .len = 0
    };
    FILE *fp = safe_fopen(path, "rb");
    size_t data_len = getfilesize(fp);
    // is a empty file ?
    if (!data_len) {
        fclose(fp);
        return datablock;
    }

    tByte *data = mymalloc(data_len);
    if (fread((tVar)data, 1, data_len, fp) != data_len) {
        fclose(fp);
        mylogging("Couldn't read entire file into memory: %s", path);
        return datablock;
    }

    fclose(fp);
Ejemplo n.º 23
0
/** Computes all the Voronoi cells and saves customized
 * information about them
 * \param[in] format the custom output string to use.
 * \param[in] filename the name of the file to write to. */
void container_periodic_poly::print_custom(const char *format,const char *filename) {
	FILE *fp=safe_fopen(filename,"w");
	print_custom(format,fp);
	fclose(fp);
}
Ejemplo n.º 24
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);
}
Ejemplo n.º 25
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);
}
Ejemplo n.º 26
0
static void test_safe_fopen(void)
{
    setup_tempfiles();

    FILE *fptr;

    char buf = 'a';

    assert_true(fptr = safe_fopen(TEST_FILE, "r"));
    assert_int_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_not_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_true(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    assert_true(fptr = safe_fopen(TEST_FILE, "a"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_true(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    assert_true(fptr = safe_fopen(TEST_FILE, "r+"));
    assert_int_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    assert_true(fptr = safe_fopen(TEST_FILE, "a+"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    assert_true(fptr = safe_fopen(TEST_FILE, "w"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_true(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    assert_true(fptr = safe_fopen(TEST_FILE, "w+"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    unlink(TEST_FILE);
    assert_false(fptr = safe_fopen(TEST_FILE, "r"));

    unlink(TEST_FILE);
    assert_true(fptr = safe_fopen(TEST_FILE, "a"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_true(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    unlink(TEST_FILE);
    assert_true(fptr = safe_fopen(TEST_FILE, "w"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_true(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    unlink(TEST_FILE);
    assert_false(fptr = safe_fopen(TEST_FILE, "r+"));

    unlink(TEST_FILE);
    assert_true(fptr = safe_fopen(TEST_FILE, "a+"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    unlink(TEST_FILE);
    assert_true(fptr = safe_fopen(TEST_FILE, "w+"));
    assert_int_not_equal(fread(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    assert_int_equal(fwrite(&buf, 1, 1, fptr), 1);
    assert_false(ferror(fptr));
    clearerr(fptr);
    fclose(fptr);

    return_to_test_dir();
}
Ejemplo n.º 27
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);
}
Ejemplo n.º 28
0
/* return 1 if require full screen redraw, 0 otherwise */
int mutt_compose_attachment (BODY *a)
{
  char type[STRING];
  char command[STRING];
  char newfile[_POSIX_PATH_MAX] = "";
  rfc1524_entry *entry = rfc1524_new_entry ();
  short unlink_newfile = 0;
  int rc = 0;
  
  snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
  if (rfc1524_mailcap_lookup (a, type, entry, M_COMPOSE))
  {
    if (entry->composecommand || entry->composetypecommand)
    {

      if (entry->composetypecommand)
	strfcpy (command, entry->composetypecommand, sizeof (command));
      else 
	strfcpy (command, entry->composecommand, sizeof (command));
      if (rfc1524_expand_filename (entry->nametemplate,
				      a->filename, newfile, sizeof (newfile)))
      {
	dprint(1, (debugfile, "oldfile: %s\t newfile: %s\n",
				  a->filename, newfile));
	if (safe_symlink (a->filename, newfile) == -1)
	{
	  if (mutt_yesorno (_("Can't match nametemplate, continue?"), M_YES) != M_YES)
	    goto bailout;
	}
	else
	  unlink_newfile = 1;
      }
      else
	strfcpy(newfile, a->filename, sizeof(newfile));
      
      if (rfc1524_expand_command (a, newfile, type,
				      command, sizeof (command)))
      {
	/* For now, editing requires a file, no piping */
	mutt_error _("Mailcap compose entry requires %%s");
      }
      else
      {
	int r;

	mutt_endwin (NULL);
	if ((r = mutt_system (command)) == -1)
	  mutt_error (_("Error running \"%s\"!"), command);
	
	if (r != -1 && entry->composetypecommand)
	{
	  BODY *b;
	  FILE *fp, *tfp;
	  char tempfile[_POSIX_PATH_MAX];

	  if ((fp = safe_fopen (a->filename, "r")) == NULL)
	  {
	    mutt_perror _("Failure to open file to parse headers.");
	    goto bailout;
	  }

	  b = mutt_read_mime_header (fp, 0);
	  if (b)
	  {
	    if (b->parameter)
	    {
	      mutt_free_parameter (&a->parameter);
	      a->parameter = b->parameter;
	      b->parameter = NULL;
	    }
	    if (b->description) {
	      FREE (&a->description);
	      a->description = b->description;
	      b->description = NULL;
	    }
	    if (b->form_name)
	    {
	      FREE (&a->form_name);
	      a->form_name = b->form_name;
	      b->form_name = NULL;
	    }

	    /* Remove headers by copying out data to another file, then 
	     * copying the file back */
	    fseeko (fp, b->offset, 0);
	    mutt_mktemp (tempfile, sizeof (tempfile));
	    if ((tfp = safe_fopen (tempfile, "w")) == NULL)
	    {
	      mutt_perror _("Failure to open file to strip headers.");
	      goto bailout;
	    }
	    mutt_copy_stream (fp, tfp);
	    safe_fclose (&fp);
	    safe_fclose (&tfp);
	    mutt_unlink (a->filename);  
	    if (mutt_rename_file (tempfile, a->filename) != 0) 
	    {
	      mutt_perror _("Failure to rename file.");
	      goto bailout;
	    }

	    mutt_free_body (&b);
	  }
	}
      }
    }
  }
  else
  {
    rfc1524_free_entry (&entry);
    mutt_message (_("No mailcap compose entry for %s, creating empty file."),
		   type);
    return 1;
  }

  rc = 1;
  
  bailout:
  
  if(unlink_newfile)
    unlink(newfile);

  rfc1524_free_entry (&entry);
  return rc;
}
Ejemplo n.º 29
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;
}
Ejemplo n.º 30
0
/**
 * Divet file is read and loaded into the linked lists
 * After running this method, the values of g_headDivet, g_tailDivet and g_divetRowLinkedListSize are set
 */
DivetRow *vh_loadDivetFile (LibraryInfo * libInfo)
{
  FILE *divetFile = safe_fopen (libInfo->libFileAdrs, "r");
  int i;
  
  if (divetFile == NULL)
    {
      sprintf (g_error_message, "Divet file '%s' could not be opened!",
	       libInfo->libFileAdrs);
      vh_quitProgram (EXIT_CODE_DIVET_ERROR);
    }

  char line[400];
  int counter = 0;
  char *token;

  //Initializing the linked list of divet rows
  libInfo->head = NULL;
  libInfo->tail = NULL;
  libInfo->size = 0;

  int counterDivetRow = 0;
  while (!feof (divetFile))
    {

      if (fgets (line, 400, divetFile) > 0)
	;

      if (line == NULL)
	continue;
      // If the read line is empty    
      int isEmpty = 1;
      int len = strlen (line);
      for (i = 0; i < len; i++)
	{
	  if (!isspace (line[i]))
	    {
	      isEmpty = 0;
	      break;
	    }
	}
      if (isEmpty)
	continue;

      DivetRow *newRow = vh_loadDivetRowFromString (libInfo->hash, line, libInfo, counterDivetRow);

      //fixOrientation(newRow);

      if (vh_notInRepeat (newRow) == 1)
	{
	  if (libInfo->head == NULL || libInfo->tail == NULL)
	    {
	      libInfo->head = newRow;
	      libInfo->tail = newRow;
	    }
	  else
	    {
	      libInfo->tail->next = newRow;
	      libInfo->tail = newRow;
	    }
	  libInfo->size++;
	  counterDivetRow++;
	}
      else
	free (newRow);

      line[0] = '\0';

    }

  vh_logInfo ("Finished reading the file");
  fclose (divetFile);
  return libInfo->head;
}