Example #1
0
int pgpdb_close(KEYRING *keydb)
{
  int err = 0;

  if (keydb->modified) {
    FILE *f;
#ifdef DEBUG
    assert(keydb->writer);
#endif
    if (keydb->encryptkey && keydb->encryptkey->length)
      pgp_encrypt(PGP_NCONVENTIONAL | PGP_NOARMOR, keydb->db,
		  keydb->encryptkey, NULL, NULL, NULL, NULL);
    assert(keydb->type == PGP_TYPE_PRIVATE || keydb->type == PGP_TYPE_PUBLIC);
    if (keydb->filetype == ARMORED)
      pgp_armor(keydb->db, keydb->type == PGP_TYPE_PUBLIC ? PGP_ARMOR_KEY : PGP_ARMOR_SECKEY);
    if (keydb->filetype == -1 || (f = mix_openfile(keydb->filename,
						   keydb->filetype ==
						   ARMORED ? "w" : "wb"))
	== NULL)
      err = -1;
    else {
      err = buf_write(keydb->db, f);
      fclose(f);
    }
  }
  if (keydb->lock)
    unlockfile(keydb->lock);
  if (keydb->encryptkey)
    buf_free(keydb->encryptkey);
  buf_free(keydb->db);
  free(keydb);
  return (err);
}
Example #2
0
void fileaccess(int fd, int count){
   void lockfile (void);
   void unlockfile (void);

   int i, k, value; pid_t pid;
   char buff[MAXSIZE];

   shmid = shmget(SHMKEY, sizeof(syncvars), PERMS | IPC_CREAT);
   shmptr = (syncvars *) shmat(shmid, (void *) NULL, 0);

   pid = getpid();

   for(i = 0; i < count; i++){
      lockfile();
      while(shmptr->turn == 0 && shmptr->flag[0] == TRUE );

      //critical stuff
      lseek(fd, 0L, 0);
      k = read(fd, buff, MAXSIZE); buff[k] = '\0';
      sscanf(buff, "%d\n", &value);
      value++;

      sprintf(buff, "%10d\n", value);
      lseek(fd, 0l, 0);
      k = strlen(buff); write(fd, buff, k);
      printf("pid = %d, new value = %d\n", pid, value);
      unlockfile();
   }
}
Example #3
0
/* Converts old versions of the filedb to the newest. Returns 1 if all went
 * well and otherwise 0. The new db is first written to a temporary place
 * and then moved over to the original db's position.
 *
 * Note: Unfortunately there is a small time-frame where aren't locking the
 *       DB, but want to replace it with a new one, using movefile().
 *       TODO: Copy old db to tmp file and then build the new db directly
 *             in the original file. This solves the tiny locking problem.
 *
 * Also remember to check the returned *fdb_s on failure, as it could be
 * NULL.
 */
static int convert_old_db(FILE ** fdb_s, char *filedb)
{
    filedb_top fdbt;
    FILE *fdb_t;
    int ret = 0;                  /* Default to 'failure' */

    filedb_readtop(*fdb_s, &fdbt);
    /* Old DB version? */
    if (fdbt.version > 0 && fdbt.version < FILEDB_VERSION3) {
        char *tempdb;

        putlog(LOG_MISC, "*", "Converting old filedb %s to newest format.",
               filedb);
        /* Create temp DB name */
        tempdb = nmalloc(strlen(filedb) + 5);
        simple_sprintf(tempdb, "%s-tmp", filedb);

        fdb_t = fopen(tempdb, "w+b");       /* Open temp DB         */
        if (fdb_t) {
            filedb_initdb(fdb_t);     /* Initialise new DB    */

            /* Convert old database to new one, saving
             * in temporary db file
             */
            if (fdbt.version == FILEDB_VERSION1)
                convert_version1(*fdb_s, fdb_t);        /* v1 -> v3             */
            else
                convert_version2(*fdb_s, fdb_t);        /* v2 -> v3             */

            unlockfile(*fdb_s);
            fclose(fdb_t);
            fclose(*fdb_s);

            /* Move over db to new location */
            if (movefile(tempdb, filedb))
                putlog(LOG_MISC, "*", "(!) Moving file db from %s to %s failed.",
                       tempdb, filedb);

            *fdb_s = fopen(filedb, "r+b");    /* Reopen new db        */
            if (*fdb_s) {
                lockfile(*fdb_s);
                /* Now we should have recreated the original situation,
                 * with the file pointer just pointing to the new version
                 * of the DB instead of the original one.
                 */
                ret = 1;
            } else
                putlog(LOG_MISC, "*", "(!) Reopening db %s failed.", filedb);
        }
        my_free(tempdb);
        /* Database already at the newest version? */
    } else if (fdbt.version == FILEDB_VERSION3)
        ret = 1;
    else
        putlog(LOG_MISC, "*", "(!) Unknown db version: %d", fdbt.version);
    if (!ret)
        putlog(LOG_MISC, "*", "Conversion of filedb %s failed.", filedb);
    return ret;
}
Example #4
0
/* Closes the filedb. Also removes the lock and updates the
 * timestamp.
 */
static void filedb_close(FILE *fdb)
{
    filedb_timestamp(fdb);
    fseek(fdb, 0L, SEEK_END);
    count--;
    unlockfile(fdb);
    fclose(fdb);
}
Example #5
0
int handle_upload(connection *con, uint32_t size, void* data) {
	uploadfilemsg_req *msg = (uploadfilemsg_req*)data;

	//cat & validate filename
	char realpath[MAX_STORAGED_PATH_LEN+1];
	assert(NULL != concatpath(realpath, msg->data, msg->filename_len));

	char *err;
        bool r = isvalidfile(&realpath[scontent_len], &err);
	if(!r){
		L_DEBUG("refuse invalid filename");
		return false;
	}
	
	L_DEBUG("recv upload file req %s\n", realpath);
	//lock file then write
	lockfile(realpath, scontent_len + msg->filename_len);
	
	//TODO
	assert(true == mkdirs(realpath));
	int fd = open(realpath ,O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
	//TODO deal with write result
	int w_len = write(fd, (void*)&msg->data[msg->filename_len], msg->data_len);
	fsync(fd);
	close(fd);

	unlockfile(realpath, scontent_len + msg->filename_len);
	

	//send res packet
	int rp_size =msg->filename_len + uploadfilemsg_res_packetsize;
	packet_header *head = generatebuffer(rp_size, CLIENT_PROTO_RES_UPLOAD_FILE);
	//TODO
	assert(NULL != head);
	uploadfilemsg_res *rp = (uploadfilemsg_res *)head->data;
	rp->filename_len = msg->filename_len;
	//TODO define result value
	rp->result = 0;
	memcpy(rp->data, msg->data, msg->filename_len);
	//TODO deal with send result
	sendpacket(con, head);
}
Example #6
0
int handle_download(connection *con, uint32_t size, void* data) {
	downloadfilemsg_req *msg = (downloadfilemsg_req *)data;
	
	//cat & validate filename
	char realpath[MAX_STORAGED_PATH_LEN+1];
	assert(NULL != concatpath(realpath, msg->data, msg->filename_len));

	char *err;
        bool r = isvalidfile(&realpath[scontent_len],&err);
	if(!r){
		L_DEBUG("refuse invalid filename");
		return false;
	}

	L_DEBUG("recv download file req %s\n", realpath);
	//get file length
	lockfile(realpath, scontent_len + msg->filename_len);
	int fd = open(realpath ,O_RDONLY);
	int rpdata_len = lseek(fd, 0, SEEK_END);
	//TODO
	assert(rpdata_len >= 0);

	//send res packet
	int rp_size =rpdata_len + downloadfilemsg_res_packetsize;
	packet_header *head = generatebuffer(rp_size, CLIENT_PROTO_RES_DOWNLOAD_FILE);
	//TODO
        assert(NULL != head);
	uploadfilemsg_res *rp = (downloadfilemsg_res *)head->data;
	rp->filename_len = msg->filename_len;
	memcpy(rp->data, msg->data, msg->filename_len);

	int r_len = read(fd, (void *)&rp->data[msg->filename_len], rpdata_len);	
	//TODO
	assert(r_len >= 0);
	close(fd);

	//TODO deal with send result
        sendpacket(con, head);

	unlockfile(realpath, scontent_len + msg->filename_len);
}
Example #7
0
/* Opens the filedb responsible to the specified directory.
 */
static FILE *filedb_open(char *path, int sort)
{
    char *s, *npath;
    FILE *fdb;
    filedb_top fdbt;
    struct stat st;

    if (count >= 2)
        putlog(LOG_MISC, "*", "(@) warning: %d open filedb's", count);
    npath = nmalloc(strlen(dccdir) + strlen(path) + 1);
    simple_sprintf(npath, "%s%s", dccdir, path);
    /* Use alternate filename if requested */
    if (filedb_path[0]) {
        char *s2;

        s2 = make_point_path(path);
        s = nmalloc(strlen(filedb_path) + strlen(s2) + 8);
        simple_sprintf(s, "%sfiledb.%s", filedb_path, s2);
        my_free(s2);
    } else {
        s = nmalloc(strlen(npath) + 10);
        simple_sprintf(s, "%s/.filedb", npath);
    }
    fdb = fopen(s, "r+b");
    if (!fdb) {
        if (convert_old_files(npath, s)) {
            fdb = fopen(s, "r+b");
            if (fdb == NULL) {
                putlog(LOG_MISC, "*", FILES_NOCONVERT, npath);
                my_free(s);
                my_free(npath);
                return NULL;
            }
            lockfile(fdb);
            filedb_update(npath, fdb, sort);
            count++;
            my_free(s);
            my_free(npath);
            return fdb;
        } else {
            filedb_top fdbt;

            /* Create new database and fix it up */
            fdb = fopen(s, "w+b");
            if (!fdb) {
                my_free(s);
                my_free(npath);
                return NULL;
            }
            lockfile(fdb);
            fdbt.version = FILEDB_NEWEST_VER;
            fdbt.timestamp = now;
            filedb_writetop(fdb, &fdbt);
            filedb_update(npath, fdb, sort);
            count++;
            my_free(s);
            my_free(npath);
            return fdb;
        }
    }

    lockfile(fdb);                /* Lock it from other bots */
    filedb_readtop(fdb, &fdbt);
    if (fdbt.version < FILEDB_NEWEST_VER) {
        if (!convert_old_db(&fdb, s)) {
            /* Conversion failed. Unlock file again and error out.
             * (convert_old_db() could have modified fdb, so check
             * for fdb != NULL.)
             */
            if (fdb)
                unlockfile(fdb);
            my_free(npath);
            my_free(s);
            return NULL;
        }
        filedb_update(npath, fdb, sort);
    }
    stat(npath, &st);
    /* Update filedb if:
     * + it's been 6 hours since it was last updated
     * + the directory has been visibly modified since then
     * (6 hours may be a bit often)
     */
    if (sort || ((now - fdbt.timestamp) > (6 * 3600)) ||
            (fdbt.timestamp < st.st_mtime) || (fdbt.timestamp < st.st_ctime))
        /* File database isn't up-to-date! */
        filedb_update(npath, fdb, sort & 1);
    else if ((now - fdbt.timestamp) > 300)
        filedb_mergeempty(fdb);

    count++;
    my_free(npath);
    my_free(s);
    return fdb;
}
Example #8
0
static int isnewid(BUFFER *id, char rsa1234, long timestamp)
/* return values:
 *   0: ignore message, no error
 *   1: ok, process message
 *  -1: bad message, send reply
 */
{
  FILE *f=NULL, *rf=NULL, *tf;
  int ret = 1;
  long now, old = 0;
  int old_day, now_day, ri, rj, flag;
  char queue[30][LINELEN];
  struct tm *gt;
  time_t od;
  LOCK *i = NULL;
  LOCK *j = NULL;
  idlog_t idbuf;
  struct {
    long time;
    int r[5];
  } rs;

  if (REMAIL == 0)
    return (1); /* don't keep statistics for the client */

  now = time(NULL);

  if ((f = mix_openfile(IDLOG, "rb+")) != NULL) {
    fread(&idbuf,1,sizeof(idlog_t),f);
    old = idbuf.time;
  } else {
    if (IDEXP == 0) {
      if (timestamp > 0 && timestamp <= now - 7 * SECONDSPERDAY) {
	errlog(LOG, "Ignoring old message.\n");
	return (0);
      }
    } else {
      if ((f = mix_openfile(IDLOG, "wb")) != NULL) {
	memset(idbuf.id,0,sizeof(idbuf.id));
	idbuf.time = now;
	fwrite(&idbuf,1,sizeof(idlog_t),f);
	memcpy(idbuf.id,id->data,sizeof(idbuf.id));
	idbuf.time = now;
	fwrite(&idbuf,1,sizeof(idlog_t),f);
	fclose(f);
        f=NULL;
	errlog(NOTICE, "Creating %s\n", IDLOG);
      } else {
	errlog(ERRORMSG, "Can't create %s\n", IDLOG);
      }
      return (1);
    }
  }

  if (now - old < 5 * SECONDSPERDAY)	/* never reject messages less than */
    old = now - 5 * SECONDSPERDAY;	/* 5 days old (== minimum IDEXP) */

  if (timestamp > 0 && timestamp <= old) {
    errlog(LOG, "Ignoring old message.\n");
    ret = 0;
    goto end;
  }
  i = lockfile(IDLOG);
  while (fread(&idbuf, 1, sizeof(idlog_t), f) == sizeof(idlog_t)) {
    if (!memcmp(idbuf.id, id->data, sizeof(idbuf.id))) {
      char idstr[33];
      id_encode(id->data, idstr);
      errlog(LOG, "Ignoring redundant message: %s.\n", idstr);
      ret = 0;
      goto end;
    }
  }
  if (timestamp > now) {
    errlog(LOG, "Ignoring message with future timestamp.\n");
    ret = -1;
    goto end;
  }
  if (ftell(f)%sizeof(idlog_t)) fseek(f,0-(ftell(f)%sizeof(idlog_t)),SEEK_CUR); /* make sure that we're on sizeof(idlog_t) byte boundary */
  memcpy(idbuf.id,id->data,sizeof(idbuf.id));
  idbuf.time = now;
  fwrite(&idbuf,1,sizeof(idlog_t),f);

  /* What key lengths are being used? */
  /* XXXXX TODO: The rest of this function is new code
   * that uses line endings and has not been tested on Windows.
   */
  if ((rf = mix_openfile(RSASTATSFILE, "rb+")) == NULL) {
    /* create it */
    if ((rf = mix_openfile(RSASTATSFILE, "wb+")) == NULL) {
        ret=-1;
        goto end;
    }
    memset(&rs, 0, sizeof(rs));
    fwrite(&rs,1,sizeof(rs),rf);
  } else {
    j = lockfile(RSASTATSFILE);
    fread(&rs,1,sizeof(rs),rf);
    fseek(rf,0,0);
    old = rs.time;
    old_day = old/SECONDSPERDAY;
    if (old_day<15706) old_day=15706;
    now_day = now/SECONDSPERDAY;
    if (old_day == now_day) {
        /* add current item to stats  */
        rs.r[rsa1234]++;
        fwrite(&rs,1,sizeof(rs),rf);
    } else {
        /* write text and restart the daily file */
        if ((tf = mix_openfile(RSATEXTFILE, "a")) != NULL) {
            od=old_day * (SECONDSPERDAY);
            gt = gmtime(&od);
            fprintf(tf, "%04d-%02d-%02d %6d %6d %6d %6d\n",
                 1900+gt->tm_year, 1+gt->tm_mon, gt->tm_mday,
                 rs.r[1], rs.r[2], rs.r[3], rs.r[4]);
            fclose(tf);
            ri=0,rj=0,flag=0;
            if ((tf = mix_openfile(RSATEXTFILE, "r")) != NULL) {
                while ( fgets (queue[ri], LINELEN, tf) ) {
                    queue[ri][LINELEN-1]='\0';
                    ri++; ri %= 30;
                    if (!ri) flag=1;
                }
                fclose(tf);
            }
            rj=ri;
            if (flag) {
                errlog(NOTICE, "rotating file %s from line %d\n", RSATEXTFILE, ri);
                if ((tf = mix_openfile(RSATEXTFILE, "w")) != NULL) {
                    do  {
                        fprintf(tf, "%s", queue[ri]);
                        ri++; ri %= 30;
                    } while (ri != rj);
                    fclose(tf);
                }
            }
        }
        memset(&rs, 0, sizeof(rs));
        rs.time = now_day * SECONDSPERDAY;
        rs.r[rsa1234]++;
        fwrite(&rs,1,sizeof(rs),rf);
    }
  }

end:
  if (i) unlockfile(i);
  if (j) unlockfile(j);
  if (f) fclose(f);
  if (rf) fclose(rf);
  return (ret);
}
Example #9
0
/*---------------------------------------------------------------------------
|  update_sample_info()/5
|
|  update_sample_info - 
|	Takes a automation directory and filename of sample_info structure (e.g., doneQ,enterq,sampleinfo)
|	Searches through the file for a match between the match_target value
|	  and the match_value;
|       Upon finding the match it then updates the update_target with the
|	  update_value;
|       For example: You want to update the doneQ  'STATUS' entry to Complete,
|		     for the experiment inwhich the DATA entry matches with
|		     '/vnmr/auto/greg.1201' (i.e. DATA is a unique identifier).
|       The call would be:
|	  update_sample_info("systemdir/auto","doneQ",
|			     "DATA:","/vnmr/auto/greg.1201",
|			     "STATUS","Complete");
|
|				Author:  Greg Brissey 1/28/88
+--------------------------------------------------------------------------*/
int update_sample_info(char *autodir, char *filename, char *match_target,
                       char *match_value, char *update_target, char *update_value)
{
    FILE *update_file,*tmp_file;
    char filepath[128],value[MAX_TEXT_LEN];
    struct sample_info	sample_entry;
    int stat,entryline,foundit;
    
    strncpy(filepath,autodir,110);
    strcat(filepath,"/");
    strcat(filepath,filename);

    /* if autoinfo mapping file hase not be read do so now */
    if (infomap.mapped != 1)		/* true if autoinfo has been read for mapping */
    {
	read_info_file(autodir);
    }


    if (lockfile(filepath) == ERROR) /* lock file for excusive use */
    {
        fprintf(stderr,"update_sample_info: could not lock '%s' file.\n",filepath);
    }
 
    update_file = fopen(filepath,"r");
    if (update_file == NULL)  /* does file exist? */
    {
        unlockfile(filepath);   /* unlock file */
        fprintf(stderr,"update_sample_info: '%s' file is not present for reading.\n",
			filepath);
        return(ERROR);
    }

    tmp_file = fopen("/tmp/update_sample_info.tmp","w");
    if (tmp_file == NULL)  /* does file exist? */
    {
        unlockfile(filepath);   /* unlock file */
        fclose(update_file);
        fprintf(stderr,
	    "update_sample_info: temp file '/tmp/update_sample_info.tmp' could not be created.\n");
        return(ERROR);
    }
 
    /* read through the the file writing to a tmp file as changes are made */
    foundit = 0;
    while ( (stat = read_sample_info(update_file,&sample_entry)) != ENDOFFILE)
    {
	if (stat == ERROR)
	{
           unlockfile(filepath);   /* unlock file */
    	   fclose(update_file);
    	   fclose(tmp_file);
           fprintf(stderr,
	    "update_sample_info: read error on file '%s'.\n",filepath);
           return(ERROR);
	}

        /* Once found and changed we can skip all this */
        if (!foundit)
        {
	  get_sample_info(&sample_entry,match_target,value,MAX_TEXT_LEN,&entryline);
          if (strncmp(value,match_value,MAX_TEXT_LEN) == 0)
          {
	     get_sample_info(&sample_entry,update_target,value,MAX_TEXT_LEN,&entryline);

	     /* If updating STATUS and STATUS: Shimming, then remove this entry */
             if ( (strcmp(infomap.status,update_target) == 0) && 
	          ( (strcmp(update_value,"Complete") == 0) || (strcmp(update_value,"Error") == 0)) &&
		  (strcmp(sample_entry.prompt_entry[entryline].etext,"Shimming") == 0) )
             {
		/* elimenate Shimming Experiment from doneQ */
	        foundit = 1;
		continue;	/* don't update, don't write it out */
             }

	     strncpy(sample_entry.prompt_entry[entryline].etext,update_value,MAX_TEXT_LEN);
	     sample_entry.prompt_entry[entryline].etext[MAX_TEXT_LEN-1] = '\0';
	     foundit = 1;
          }
        }

	if (write_sample_info(tmp_file,&sample_entry) == ERROR)
	{
           unlockfile(filepath);   /* unlock file */
    	   fclose(update_file);
    	   fclose(tmp_file);
           fprintf(stderr,
	    "update_sample_info: write error to temp file '/tmp/update_sample_info.tmp'.\n");
           return(ERROR);
	}
    }

    fclose(update_file);
    fclose(tmp_file);

    /* Changes are complete in the tmp file, now copy the tmp file into the orginal file */
    tmp_file = fopen("/tmp/update_sample_info.tmp","r");
    if (tmp_file == NULL)  /* does file exist? */
    {
        unlockfile(filepath);   /* unlock file */
        fprintf(stderr,
          "update_sample_info: temp file '/tmp/update_sample_info.tmp' could not be opened to be read.\n");
        return(ERROR);
    }

    update_file = fopen(filepath,"w");
    if (update_file == NULL)  /* does file exist? */
    {
        unlockfile(filepath);   /* unlock file */
        fclose(tmp_file);
        fprintf(stderr,"update_sample_info: '%s' file is not present for writing.\n",
			filepath);
        return(ERROR);
    }

    while ( ( stat = read_sample_info(tmp_file,&sample_entry)) != ENDOFFILE)
    {
	if (stat == ERROR)
	{
           unlockfile(filepath);   /* unlock file */
    	   fclose(update_file);
    	   fclose(tmp_file);
           fprintf(stderr,
	    "update_sample_info: read error on file '/tmp/update_sample_info.tmp'.\n");
           return(ERROR);
	}
	if (write_sample_info(update_file,&sample_entry) == ERROR)
	{
           unlockfile(filepath);   /* unlock file */
    	   fclose(update_file);
    	   fclose(tmp_file);
           fprintf(stderr,
	    "update_sample_info: write error to file '%s'.\n",filepath);
           return(ERROR);
	}
    }

    fclose(update_file);
    fclose(tmp_file);

    unlockfile(filepath);   /* unlock file */
    return(OK); 
}
Example #10
0
/* Convert '.files' db to newest db. Returns 1 if a valid file is
 * found and could be converted, 0 in all other cases.
 *
 * '.files' is a text file which contains file records built up in the
 * following way:
 *      '<filename> <nick> <tm> <gots>\n'
 *      '- <comment>\n'
 *      '- <comment>\n'
 *      ...
 */
static int convert_old_files(char *path, char *newfiledb)
{
    FILE *f, *fdb;
    char *s, *fn, *nick, *tm, *s1;
    filedb_entry *fdbe = NULL;
    int in_file = 0, i;
    struct stat st;

    s = nmalloc(strlen(path) + 8);
    sprintf(s, "%s/.files", path);
    f = fopen(s, "r");
    my_free(s);
    if (f == NULL)
        return 0;

    fdb = fopen(newfiledb, "w+b");
    if (!fdb) {
        putlog(LOG_MISC, "(!) Can't create filedb in %s", newfiledb);
        fclose(f);
        return 0;
    }
    lockfile(fdb);
    lockfile(f);
    filedb_initdb(fdb);

    putlog(LOG_FILES, "*", FILES_CONVERT, path);
    /* Scan contents of .files and painstakingly create .filedb entries */
    while (!feof(f)) {
        s = nmalloc(121);
        s1 = s;
        fgets(s, 120, f);
        if (s[strlen(s) - 1] == '\n')
            s[strlen(s) - 1] = 0;
        if (!feof(f)) {
            fn = newsplit(&s1);
            rmspace(fn);
            if ((fn[0]) && (fn[0] != ';') && (fn[0] != '#')) {
                /* Not comment */
                if (fn[0] == '-') {
                    /* Adjust comment for current file */
                    if (in_file && fdbe) {
                        rmspace(s);
                        if (fdbe->desc) {
                            fdbe->desc = nrealloc(fdbe->desc,
                                                  strlen(fdbe->desc) + strlen(s) + 2);
                            strcat(fdbe->desc, "\n");
                        } else
                            fdbe->desc = nmalloc(strlen(s) + 2);
                        strcat(fdbe->desc, s);
                    }
                } else {
                    if (fdbe) {
                        /* File pending. Write to DB */
                        filedb_addfile(fdb, fdbe);
                        free_fdbe(&fdbe);
                    }
                    fdbe = malloc_fdbe();
                    in_file = 1;
                    nick = newsplit(&s1);
                    rmspace(nick);
                    tm = newsplit(&s1);
                    rmspace(tm);
                    rmspace(s1);
                    i = strlen(fn) - 1;
                    if (fn[i] == '/')
                        fn[i] = 0;
                    malloc_strcpy(fdbe->filename, fn);
                    malloc_strcpy(fdbe->uploader, nick);
                    fdbe->gots = atoi(s1);
                    fdbe->uploaded = atoi(tm);
                    sprintf(s, "%s/%s", path, fn);
                    if (stat(s, &st) == 0) {
                        /* File is okay */
                        if (S_ISDIR(st.st_mode)) {
                            fdbe->stat |= FILE_DIR;
                            if (nick[0] == '+') {
                                char x[100];

                                /* Only do global flags, it's an old one */
                                struct flag_record fr = { FR_GLOBAL, 0, 0, 0, 0, 0 };

                                break_down_flags(nick + 1, &fr, NULL);
                                build_flags(x, &fr, NULL);
                                /* We only want valid flags */
                                malloc_strcpy_nocheck(fdbe->flags_req, x);
                            }
                        }
                        fdbe->size = st.st_size;
                    } else
                        in_file = 0;        /* skip */
                }
            }
        }
        my_free(s);
    }
    if (fdbe) {
        /* File pending. Write to DB */
        filedb_addfile(fdb, fdbe);
        free_fdbe(&fdbe);
    }
    fseek(fdb, 0L, SEEK_END);
    unlockfile(f);
    unlockfile(fdb);
    fclose(fdb);
    fclose(f);
    return 1;
}
Example #11
0
int pgp_keymgt(int force)
{
  FILE *f = NULL;
  BUFFER *key, *keybak, *userid, *out, *outkey, *outtxt, *pass, *secout;
  KEYRING *keys;
  int err = 0, res, recreate_pubring = 0, dsa_ok = 0;
#ifdef USE_IDEA
  int rsa_ok = 0;
#endif /* USE_IDEA */
  long expires;
  LOCK *seclock;

  key = buf_new();
  out = buf_new();
  keybak = buf_new();
  secout = buf_new();

  userid = buf_new();
  buf_sets(userid, REMAILERNAME);
  pass = buf_new();
  buf_sets(pass, PASSPHRASE);
  outtxt = buf_new();
  outkey = buf_new();

  /* We only want to build RSA keys if we also can do IDEA
   * This is to not lose any mail should users try our RSA key
   * with IDEA.
   */
#ifdef USE_IDEA
  /* FIXME: pgpdb_getky returns the expiration date from the last key in the keyring
   *        which probably works most of the time if the keys are in the correct order
   *        it doesn't return the latest expiration date (or 0) if the key in question
   *        is before another matching key in the keyring tho
   */
  res = pgpdb_getkey(PK_DECRYPT, PGP_ES_RSA, NULL, NULL, &expires, NULL, NULL,
				  NULL, NULL, NULL, pass);
  if (force == 2 || res < 0 || (expires > 0 && expires - KEYOVERLAPPERIOD < time(NULL))) {
    rsa_ok = -1;
    pgp_keygen(PGP_ES_RSA, 0, userid, pass, PGPKEY, PGPREMSECRING, 0);
  };

  if (force == 0 && (pgpdb_getkey(PK_ENCRYPT, PGP_ES_RSA, NULL, NULL, NULL, NULL, NULL,
				  NULL, NULL, PGPKEY, NULL) < 0) && rsa_ok == 0)
    rsa_ok = 1;
#endif /* USE_IDEA */
  /* FIXME: pgpdb_getky returns the expiration date from the last key in the keyring
   *        which probably works most of the time if the keys are in the correct order
   *        it doesn't return the latest expiration date (or 0) if the key in question
   *        is before another matching key in the keyring tho
   */
  res = pgpdb_getkey(PK_DECRYPT, PGP_E_ELG, NULL, NULL, &expires, NULL, NULL,
				  NULL, NULL, NULL, pass);
  if (force == 2 || res < 0 || (expires > 0 && expires - KEYOVERLAPPERIOD < time(NULL))) {
    dsa_ok = -1;
    pgp_keygen(PGP_E_ELG, 0, userid, pass, PGPKEY, PGPREMSECRING, 0);
  }

  if (force == 0 && (pgpdb_getkey(PK_ENCRYPT, PGP_E_ELG, NULL, NULL, NULL, NULL, NULL,
				  NULL, NULL, PGPKEY, NULL) > 0) && dsa_ok == 0)
    dsa_ok = 1;

  /* No need to rewrite the files - we didn't change a thing */
  if (
#ifdef USE_IDEA
      rsa_ok == 1 &&
#endif /* USE_IDEA */
      dsa_ok == 1)
    goto end;

  /* write keys one key per armor to make hand editing easy and old PGP
   * versions happy */
  err = -1;
  keys = pgpdb_open(PGPKEY, NULL, 0, PGP_TYPE_PUBLIC);
  if (keys == NULL)
    recreate_pubring = 1;
  else {
    while (pgpdb_getnext(keys, key, NULL, userid) != -1) {
      buf_clear(outtxt);
      if (pgp_makekeyheader(PGP_PUBKEY, key, outtxt, NULL, PGP_ANY) == 0) {
	err = 0;
	buf_appends(out, "Type Bits/KeyID     Date       User ID\n");
	buf_cat(out, outtxt);
	buf_nl(out);
	pgp_armor(key, PGP_ARMOR_KEY);
	buf_cat(out, key);
	buf_nl(out);
      }
    }
    pgpdb_close(keys);
  }
  if (err != 0)
    recreate_pubring = 1;
  err = -1;

  keys = pgpdb_open(PGPREMSECRING, NULL, 0, PGP_TYPE_PRIVATE);
  if (keys == NULL)
    goto end;
  while (pgpdb_getnext(keys, key, NULL, userid) != -1) {
    buf_clear(outtxt);
    buf_clear(outkey);
    buf_clear(keybak);
    buf_cat(keybak, key);
    if (pgp_makekeyheader(PGP_SECKEY, key, outtxt, pass, PGP_ANY) == 0) {
      err = 0;
      buf_appends(secout, "Type Bits/KeyID     Date       User ID\n");
      buf_cat(secout, outtxt);
      buf_nl(secout);
      pgp_armor(key, PGP_ARMOR_SECKEY);
      buf_cat(secout, key);
      buf_nl(secout);
    }
    buf_clear(outtxt);
    if (recreate_pubring &&
	pgp_makepubkey(keybak, outtxt, outkey, pass, PGP_ANY) == 0) {
      buf_appends(out, "Type Bits/KeyID     Date       User ID\n");
      buf_cat(out, outtxt);
      buf_nl(out);
      pgp_armor(outkey, PGP_ARMOR_KEY);
      buf_cat(out, outkey);
      buf_nl(out);
    }
  }
  pgpdb_close(keys);

  seclock = lockfile(PGPREMSECRING);
  if (err == 0 && (f = mix_openfile(PGPREMSECRING, "w")) != NULL) {
    buf_write(secout, f);
    fclose(f);
  } else
    err = -1;
  unlockfile(seclock);
  if (err == 0 && (f = mix_openfile(PGPKEY, "w")) != NULL) {
    buf_write(out, f);
    fclose(f);
  } else
    err = -1;
end:
  buf_free(key);
  buf_free(keybak);
  buf_free(out);
  buf_free(userid);
  buf_free(pass);
  buf_free(outtxt);
  buf_free(outkey);
  buf_free(secout);
  return (err);
}