/*
Usage:  delete a name pair from database, send the reply
Return: none
*/
void delete_name(int sockfd, int dbfd, int logfd, struct name_prtl *name_request)
{
    int flag, result;

    lock_file(dbfd);
    write_log(logfd, "[Info] delete_name -- start searching the database");

    flag = is_in_database(dbfd, name_request->name);
    printf("[Info] delete_name -- finish searching database\n");
    if (flag == 0) { /* found */
        if (delete_line(dbfd, name_request->name) != 0) {
            result = pkt_write(sockfd, 8, name_request->name, 
            "fail to operate read or write the database");    
        } else { /* delete name pair */
            result = pkt_write(sockfd, 7, name_request->name, 
            "delete the name successfully");
        }
    } else if (flag == 1) { /* not find such name */
        result = pkt_write(sockfd, 8, name_request->name, 
            "the name is in database");
    } else if (flag == -1) { /* error */
        result = pkt_write(sockfd, 8, name_request->name, 
            "fail to read the datebase, please try it later");
    }

    unlock_file(dbfd);
    if (result < 0) {
        fprintf(stderr, "[Error] delete_name -- send reply fail\n");
        write_log(logfd, "[Error] delete_name -- send reply fail");
    } else {
        fprintf(stdout, "[Info] delete_name -- send reply ok: %s\n", 
            name_request->name);
        write_log(logfd, "[Info] delete_name -- send reply ok");
    }
    return;
}
示例#2
0
/*######################### change_alias_order() ########################*/
void
change_alias_order(char **p_host_names, int new_no_of_hosts)
{
   int                        i,
                              ignore_first_errors,
                              fd,
                              position,
                              pagesize,
                              old_no_of_hosts = no_of_hosts,
                              loop_no_of_hosts,
                              current_fsa_id,
                              new_fsa_fd;
   off_t                      new_fsa_size;
   char                       *ptr,
                              fsa_id_file[MAX_PATH_LENGTH],
                              new_fsa_stat[MAX_PATH_LENGTH];
   struct flock               wlock;
   struct filetransfer_status *new_fsa;

   if (new_no_of_hosts != -1)
   {
      if (no_of_hosts > new_no_of_hosts)
      {
         loop_no_of_hosts = no_of_hosts;
      }
      else
      {
         loop_no_of_hosts = new_no_of_hosts;
      }
      no_of_hosts = new_no_of_hosts;
   }
   else
   {
      loop_no_of_hosts = no_of_hosts;
   }

   (void)strcpy(fsa_id_file, p_work_dir);
   (void)strcat(fsa_id_file, FIFO_DIR);
   (void)strcat(fsa_id_file, FSA_ID_FILE);

   wlock.l_type   = F_WRLCK;
   wlock.l_whence = SEEK_SET;
   wlock.l_start  = 0;
#ifdef HAVE_MMAP
   wlock.l_len    = fsa_size;
#else
   wlock.l_len    = AFD_WORD_OFFSET + (no_of_hosts * sizeof(struct filetransfer_status));
#endif /* HAVE_MMAP */
   if (fcntl(fsa_fd, F_SETLKW, &wlock) < 0)
   {
      /* Is lock already set or are we setting it again? */
      if ((errno != EACCES) && (errno != EAGAIN) && (errno != EBUSY))
      {
         system_log(ERROR_SIGN, __FILE__, __LINE__,
                    _("Could not set write lock for FSA_STAT_FILE : %s"),
                    strerror(errno));
      }
      else
      {
         system_log(DEBUG_SIGN, __FILE__, __LINE__,
                    _("Could not set write lock for FSA_STAT_FILE : %s"),
                    strerror(errno));
      }
   }

   /*
    * When changing the order of the hosts, lock the FSA_ID_FILE so no
    * one gets the idea to do the same thing or change the DIR_CONFIG
    * file.
    */
   if ((fd = lock_file(fsa_id_file, ON)) < 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 _("Failed to lock `%s' [%d]"), fsa_id_file, fd);
      exit(INCORRECT);
   }

   /* Read the fsa_id. */
   if (read(fd, &current_fsa_id, sizeof(int)) < 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 _("Could not read the value of the fsa_id : %s"),
                 strerror(errno));
      (void)close(fd);
      exit(INCORRECT);
   }

   if (current_fsa_id != fsa_id)
   {
      system_log(DEBUG_SIGN, __FILE__, __LINE__,
                 _("AAAaaaarrrrghhhh!!! DON'T CHANGE THE DIR_CONFIG FILE WHILE USING edit_hc!!!!"));
      (void)close(fd);
      exit(INCORRECT);
   }
   current_fsa_id++;

   /* Mark old FSA as stale. */
   *(int *)((char *)fsa - AFD_WORD_OFFSET) = STALE;
   pagesize = *(int *)((char *)fsa - AFD_WORD_OFFSET + SIZEOF_INT + 4);
   ignore_first_errors = *(unsigned char *)((char *)fsa - AFD_WORD_OFFSET + SIZEOF_INT + 1 + 1);

   /*
    * Create a new FSA with the new ordering of the host aliases.
    */
   (void)snprintf(new_fsa_stat, MAX_PATH_LENGTH, "%s%s%s.%d",
                  p_work_dir, FIFO_DIR, FSA_STAT_FILE, current_fsa_id);

   /* Now map the new FSA region to a file. */
   if ((new_fsa_fd = coe_open(new_fsa_stat,
                              (O_RDWR | O_CREAT | O_TRUNC), FILE_MODE)) < 0)
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__,
                 _("Failed to open() `%s' : %s"),
                 new_fsa_stat, strerror(errno));
      exit(INCORRECT);
   }
   new_fsa_size = AFD_WORD_OFFSET +
                  (no_of_hosts * sizeof(struct filetransfer_status));
   if (lseek(new_fsa_fd, new_fsa_size - 1, SEEK_SET) == -1)
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__,
                 _("Failed to lseek() in `%s' : %s"),
                 new_fsa_stat, strerror(errno));
      exit(INCORRECT);
   }
   if (write(new_fsa_fd, "", 1) != 1)
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__,
                 _("write() error : %s"), strerror(errno));
      exit(INCORRECT);
   }
#ifdef HAVE_MMAP
   if ((ptr = mmap(NULL, new_fsa_size, (PROT_READ | PROT_WRITE), MAP_SHARED,
                   new_fsa_fd, 0)) == (caddr_t) -1)
#else
   if ((ptr = mmap_emu(NULL, new_fsa_size, (PROT_READ | PROT_WRITE), MAP_SHARED,
                       new_fsa_stat, 0)) == (caddr_t) -1)
#endif
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__,
                 _("mmap() error : %s"), strerror(errno));
      exit(INCORRECT);
   }

   /* Write number of hosts to new mmap region. */
   *(int *)ptr = no_of_hosts;
   *(ptr + SIZEOF_INT + 1 + 1) = ignore_first_errors;
   *(ptr + SIZEOF_INT + 1 + 1 + 1) = CURRENT_FSA_VERSION; /* FSA version number. */
   *(int *)(ptr + SIZEOF_INT + 4) = pagesize;
   *(ptr + SIZEOF_INT + 4 + SIZEOF_INT) = 0;        /* Not used. */
   *(ptr + SIZEOF_INT + 4 + SIZEOF_INT + 1) = 0;    /* Not used. */
   *(ptr + SIZEOF_INT + 4 + SIZEOF_INT + 2) = 0;    /* Not used. */
   *(ptr + SIZEOF_INT + 4 + SIZEOF_INT + 3) = 0;    /* Not used. */

   /* Copy configuration information from the old FSA. */
   ptr += AFD_WORD_OFFSET;
   *((char *)ptr - AFD_FEATURE_FLAG_OFFSET_END) = *((char *)fsa - AFD_FEATURE_FLAG_OFFSET_END);

   /* Reposition fsa pointer after no_of_host. */
   new_fsa = (struct filetransfer_status *)ptr;

   if (fra_attach() != SUCCESS)
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__, _("Failed to attach to FRA."));
      exit(INCORRECT);
   }

   /*
    * Now copy each entry from the old FSA to the new FSA in
    * the order they are found in the host_list_w.
    */
   for (i = 0; i < loop_no_of_hosts; i++)
   {
      if (p_host_names[i][0] != '\0')
      {
         if ((position = get_host_position(fsa, p_host_names[i],
                                           old_no_of_hosts)) < 0)
         {
            if (hl != NULL)
            {
               int k;

               /*
                * Hmmm. This host is not in the FSA. So lets assume this
                * is a new host.
                */
               (void)memset(&new_fsa[i], 0, sizeof(struct filetransfer_status));
               (void)memcpy(new_fsa[i].host_alias, hl[i].host_alias, MAX_HOSTNAME_LENGTH + 1);
               new_fsa[i].host_id = get_str_checksum(new_fsa[i].host_alias);
               (void)snprintf(new_fsa[i].host_dsp_name, MAX_HOSTNAME_LENGTH + 2,
                              "%-*s", MAX_HOSTNAME_LENGTH, hl[i].host_alias);
               new_fsa[i].toggle_pos = strlen(new_fsa[i].host_alias);
               (void)memcpy(new_fsa[i].real_hostname[0], hl[i].real_hostname[0], MAX_REAL_HOSTNAME_LENGTH);
               (void)memcpy(new_fsa[i].real_hostname[1], hl[i].real_hostname[1], MAX_REAL_HOSTNAME_LENGTH);
               new_fsa[i].host_toggle = HOST_ONE;
               if (hl[i].host_toggle_str[0] != '\0')
               {
                  (void)memcpy(new_fsa[i].host_toggle_str, hl[i].host_toggle_str, MAX_TOGGLE_STR_LENGTH);
                  if (hl[i].host_toggle_str[0] == AUTO_TOGGLE_OPEN)
                  {
                     new_fsa[i].auto_toggle = ON;
                  }
                  else
                  {
                     new_fsa[i].auto_toggle = OFF;
                  }
                  new_fsa[i].original_toggle_pos = DEFAULT_TOGGLE_HOST;
                  new_fsa[i].host_dsp_name[(int)new_fsa[i].toggle_pos] = hl[i].host_toggle_str[(int)new_fsa[i].original_toggle_pos];
               }
               else
               {
                  new_fsa[i].host_toggle_str[0] = '\0';
                  new_fsa[i].original_toggle_pos = NONE;
                  new_fsa[i].auto_toggle = OFF;
               }
               (void)memcpy(new_fsa[i].proxy_name, hl[i].proxy_name, MAX_PROXY_NAME_LENGTH + 1);
               new_fsa[i].transfer_rate_limit = hl[i].transfer_rate_limit;
               new_fsa[i].allowed_transfers = hl[i].allowed_transfers;
               for (k = 0; k < new_fsa[i].allowed_transfers; k++)
               {
                  new_fsa[i].job_status[k].connect_status = DISCONNECT;
                  new_fsa[i].job_status[k].proc_id = -1;
#ifdef _WITH_BURST_2
                  new_fsa[i].job_status[k].job_id = NO_ID;
#endif
               }
               for (k = new_fsa[i].allowed_transfers; k < MAX_NO_PARALLEL_JOBS; k++)
               {
                  new_fsa[i].job_status[k].no_of_files = -1;
                  new_fsa[i].job_status[k].proc_id = -1;
               }
               new_fsa[i].max_errors = hl[i].max_errors;
               new_fsa[i].retry_interval = hl[i].retry_interval;
               new_fsa[i].block_size = hl[i].transfer_blksize;
               new_fsa[i].max_successful_retries = hl[i].successful_retries;
               new_fsa[i].file_size_offset = hl[i].file_size_offset;
               new_fsa[i].transfer_timeout = hl[i].transfer_timeout;
               new_fsa[i].protocol = hl[i].protocol;
               new_fsa[i].protocol_options = hl[i].protocol_options;
               new_fsa[i].ttl = hl[i].ttl;
               new_fsa[i].special_flag = 0;
               if (hl[i].host_status & HOST_CONFIG_HOST_DISABLED)
               {
                  new_fsa[i].special_flag |= HOST_DISABLED;
               }
               new_fsa[i].host_status = 0;
               if (hl[i].host_status & STOP_TRANSFER_STAT)
               {
                  new_fsa[i].host_status |= STOP_TRANSFER_STAT;
               }
               if (hl[i].host_status & PAUSE_QUEUE_STAT)
               {
                  new_fsa[i].host_status |= PAUSE_QUEUE_STAT;
               }
            }
            else
            {
               system_log(DEBUG_SIGN, __FILE__, __LINE__,
                          _("AAAaaaarrrrghhhh!!! Could not find hostname `%s'"),
                          p_host_names[i]);
               (void)close(fd);
               exit(INCORRECT);
            }
         }
         else
         {
            if ((position != INCORRECT) && (position != i))
            {
               int k;

               for (k = 0; k < no_of_dirs; k++)
               {
                  if ((fra[k].host_alias[0] != '\0') &&
                      (CHECK_STRCMP(fra[k].host_alias, fsa[position].host_alias) == 0))
                  {
                     fra[k].fsa_pos = i;
                  }
               }
            }
            (void)memcpy(&new_fsa[i], &fsa[position],
                         sizeof(struct filetransfer_status));
         }
      }
   }
#ifdef HAVE_MMAP
   if (msync(ptr - AFD_WORD_OFFSET, new_fsa_size, MS_SYNC) == -1)
   {
      system_log(WARN_SIGN, __FILE__, __LINE__,
                 "msync() error : %s", strerror(errno));
   }
#endif

   if (fra_detach() < 0)
   {
      system_log(WARN_SIGN, __FILE__, __LINE__,
                 _("Failed to detach from FRA."));
   }

   if (fsa_detach(NO) < 0)
   {
      system_log(WARN_SIGN, __FILE__, __LINE__,
                 _("Failed to detach from old FSA."));
   }

   /* Now "attach" to the new FSA. */
   fsa = new_fsa;
   fsa_fd = new_fsa_fd;
   fsa_id = current_fsa_id;
#ifdef HAVE_MMAP
   fsa_size = new_fsa_size;
#endif

   /* Go to beginning in file. */
   if (lseek(fd, 0, SEEK_SET) < 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 _("Could not seek() to beginning of `%s' : %s"),
                 fsa_id_file, strerror(errno));
   }

   /* Write new value into FSA_ID_FILE file. */
   if (write(fd, &fsa_id, sizeof(int)) != sizeof(int))
   {
      system_log(FATAL_SIGN, __FILE__, __LINE__,
                 _("Could not write value to FSA ID file : %s"),
                 strerror(errno));
      exit(INCORRECT);
   }

   /* Release the lock. */
   if (close(fd) == -1)
   {
      system_log(DEBUG_SIGN, __FILE__, __LINE__,
                 _("close() error : %s"), strerror(errno));
   }

   /* Remove the old FSA file. */
   (void)snprintf(new_fsa_stat, MAX_PATH_LENGTH, "%s%s%s.%d",
                  p_work_dir, FIFO_DIR, FSA_STAT_FILE, current_fsa_id - 1);
   if (unlink(new_fsa_stat) < 0)
   {
      system_log(WARN_SIGN, __FILE__, __LINE__,
                 _("unlink() error : %s"), strerror(errno));
   }

   return;
}
示例#3
0
int lock_file_write(const int fd)
{
	return lock_file(fd, F_WRLCK);
}
示例#4
0
int
main (int argc, char **argv)
{
  int c;
  bool running_suid;
  void *lockstate;
  char *scorefile;
  char *nl;
  const char *prefix, *user_prefix = NULL;
  struct stat buf;
  struct score_entry *scores;
  struct score_entry newscore;
  bool reverse = false;
  ptrdiff_t scorecount, scorealloc;
  ptrdiff_t max_scores = MAX_SCORES;

  srand (time (0));

  while ((c = getopt (argc, argv, "hrm:d:")) != -1)
    switch (c)
      {
      case 'h':
	usage (EXIT_SUCCESS);
	break;
      case 'd':
	user_prefix = optarg;
	break;
      case 'r':
	reverse = 1;
	break;
      case 'm':
	{
	  intmax_t m = strtoimax (optarg, 0, 10);
	  if (m < 0)
	    usage (EXIT_FAILURE);
	  max_scores = min (m, MAX_SCORES);
	}
	break;
      default:
	usage (EXIT_FAILURE);
      }

  if (argc - optind != 3)
    usage (EXIT_FAILURE);

  running_suid = (getuid () != geteuid ());

  prefix = get_prefix (running_suid, user_prefix);

  scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  if (!scorefile)
    lose_syserr ("Couldn't allocate score file");

  strcpy (scorefile, prefix);
  strcat (scorefile, "/");
  strcat (scorefile, argv[optind]);

  newscore.score = strtoimax (argv[optind + 1], 0, 10);

  newscore.data = argv[optind + 2];
  if (strlen (newscore.data) > MAX_DATA_LEN)
    newscore.data[MAX_DATA_LEN] = '\0';
  nl = strchr (newscore.data, '\n');
  if (nl)
    *nl = '\0';

  newscore.username = get_user_id ();
  if (! newscore.username)
    lose_syserr ("Couldn't determine user id");

  if (stat (scorefile, &buf) < 0)
    lose_syserr ("Failed to access scores file");

  if (lock_file (scorefile, &lockstate) < 0)
    lose_syserr ("Failed to lock scores file");

  if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to read scores file");
    }
  if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to add score");
    }
  sort_scores (scores, scorecount, reverse);
  /* Limit the number of scores.  If we're using reverse sorting, then
     also increment the beginning of the array, to skip over the
     *smallest* scores.  Otherwise, just decrementing the number of
     scores suffices, since the smallest is at the end. */
  if (scorecount > max_scores)
    {
      if (reverse)
	scores += scorecount - max_scores;
      scorecount = max_scores;
    }
  if (write_scores (scorefile, scores, scorecount) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to write scores file");
    }
  if (unlock_file (scorefile, lockstate) < 0)
    lose_syserr ("Failed to unlock scores file");
  exit (EXIT_SUCCESS);
}
示例#5
0
文件: potfile.c 项目: lifanov/hashcat
void potfile_write_append (hashcat_ctx_t *hashcat_ctx, const char *out_buf, u8 *plain_ptr, unsigned int plain_len)
{
  const hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  const potfile_ctx_t  *potfile_ctx  = hashcat_ctx->potfile_ctx;
  const user_options_t *user_options = hashcat_ctx->user_options;

  if (potfile_ctx->enabled == false) return;

  u8 *tmp_buf = potfile_ctx->tmp_buf;

  int tmp_len = 0;

  if (1)
  {
    const size_t out_len = strlen (out_buf);

    memcpy (tmp_buf + tmp_len, out_buf, out_len);

    tmp_len += out_len;

    tmp_buf[tmp_len] = hashconfig->separator;

    tmp_len += 1;
  }

  if (1)
  {
    const bool always_ascii = (hashconfig->hash_type & OPTS_TYPE_PT_ALWAYS_ASCII) ? true : false;

    if ((user_options->outfile_autohex == true) && (need_hexify (plain_ptr, plain_len, hashconfig->separator, always_ascii) == true))
    {
      tmp_buf[tmp_len++] = '$';
      tmp_buf[tmp_len++] = 'H';
      tmp_buf[tmp_len++] = 'E';
      tmp_buf[tmp_len++] = 'X';
      tmp_buf[tmp_len++] = '[';

      exec_hexify ((const u8 *) plain_ptr, plain_len, tmp_buf + tmp_len);

      tmp_len += plain_len * 2;

      tmp_buf[tmp_len++] = ']';
    }
    else
    {
      memcpy (tmp_buf + tmp_len, plain_ptr, plain_len);

      tmp_len += plain_len;
    }
  }

  tmp_buf[tmp_len] = 0;

  lock_file (potfile_ctx->fp);

  fprintf (potfile_ctx->fp, "%s" EOL, tmp_buf);

  fflush (potfile_ctx->fp);

  if (unlock_file (potfile_ctx->fp))
  {
    event_log_error (hashcat_ctx, "%s: Failed to unlock file.", potfile_ctx->filename);
  }
}
示例#6
0
bool
FileLock::obtain( LOCK_TYPE t )
{
	int counter = 0; 
#if !defined(WIN32)
	start: 
#endif	
// lock_file uses lseeks in order to lock the first 4 bytes of the file on NT
// It DOES properly reset the lseek version of the file position, but that is
// not the same (in some very inconsistent and weird ways) as the fseek one,
// so if the user has given us a FILE *, we need to make sure we don't ruin
// their current position.  The lesson here is don't use fseeks and lseeks
// interchangeably...
	int		status = -1;
	int saved_errno = -1;

	if ( m_use_kernel_mutex == -1 ) {
		m_use_kernel_mutex = param_boolean_int("FILE_LOCK_VIA_MUTEX", TRUE);
	}

		// If we have the path, we can try to lock via a mutex.  
	if ( m_path && m_use_kernel_mutex ) {
		status = lockViaMutex(t);
	}

		// We cannot lock via a mutex, or we tried and failed.
		// Try via filesystem lock.
	if ( status < 0) {
		long lPosBeforeLock = 0;
		if (m_fp) // if the user has a FILE * as well as an fd
		{
			// save their FILE*-based current position
			lPosBeforeLock = ftell(m_fp); 
		}
		
			// We're seeing sporadic test suite failures where a daemon
			// takes more than 10 seconds to write to the user log.
			// This will help narrow down where the delay is coming from.
		time_t before = time(NULL);
		status = lock_file( m_fd, t, m_blocking );
		saved_errno = errno;
		time_t after = time(NULL);
		if ( (after - before) > 5 ) {
			dprintf( D_FULLDEBUG,
					 "FileLock::obtain(%d): lock_file() took %ld seconds\n",
					 t, (after-before) );
		}
		
		if (m_fp)
		{
			// restore their FILE*-position
			fseek(m_fp, lPosBeforeLock, SEEK_SET); 	
		}

#ifndef WIN32		
			// if we deal with our own fd and are not unlocking
		if (m_delete == 1 && t != UN_LOCK){
			struct stat si; 
			fstat(m_fd, &si);
				// no more hard links ... it was deleted while we were waiting
				// in that case we need to reopen and restart
			if ( si.st_nlink < 1 ){
				release();
				close(m_fd);
				bool initResult;
				if (m_orig_path != NULL && strcmp(m_path, m_orig_path) != 0)
					initResult = initLockFile(false);
				else 
					initResult = initLockFile(true);
				if (!initResult) {
					dprintf(D_FULLDEBUG, "Lock file (%s) cannot be reopened \n", m_path);
					if (m_orig_path) {
						dprintf(D_FULLDEBUG, "Opening and locking the actual log file (%s) since lock file cannot be accessed! \n", m_orig_path);
						m_fd = safe_open_wrapper_follow(m_orig_path, O_CREAT | O_RDWR , 0644);
					} 
				}
				
				if (m_fd < 0) {
					dprintf(D_FULLDEBUG, "Opening the log file %s to lock failed. \n", m_path);
				}
				++counter;
					// let's retry at most 5 times
				if (counter < 6) {
					goto start;
				}
				else 
					status = -1;
			}		
		}
#endif		
	}

	if( status == 0 ) {
		m_state = t;
	}
	if ( status != 0 ) {
		dprintf( D_ALWAYS, "FileLock::obtain(%d) failed - errno %d (%s)\n",
	                t, saved_errno, strerror(saved_errno) );
	}
	else {
		UtcTime	now( true );
		dprintf( D_FULLDEBUG,
				 "FileLock::obtain(%d) - @%.6f lock on %s now %s\n",
				 t, now.combined(), m_path, getStateString(t) );
	}
	return status == 0;
}
示例#7
0
文件: fconc.c 项目: shmmy/OS
void unlock_file(int fd)
{
    lock_file(fd,F_UNLCK); //set lock on file to UNLOCK
}
示例#8
0
/*
 * If the next required delta is now present, let ctm lunch on it and any
 * contiguous deltas.
 */
void
apply_complete()
    {
    int i, dn;
    int lfd;
    FILE *fp, *ctm;
    struct stat sb;
    char class[20];
    char delta[30];
    char junk[2];
    char fname[PATH_MAX];
    char here[PATH_MAX];
    char buf[PATH_MAX*2];

    /*
     * Grab a lock on the ctm mutex file so that we can be sure we are
     * working alone, not fighting another ctm_rmail!
     */
    strcpy(fname, delta_dir);
    strcat(fname, "/.mutex_apply");
    if ((lfd = lock_file(fname)) < 0)
	return;

    /*
     * Find out which delta ctm needs next.
     */
    sprintf(fname, "%s/%s", base_dir, CTM_STATUS);
    if ((fp = fopen(fname, "r")) == NULL)
	{
	close(lfd);
	return;
	}

    i = fscanf(fp, "%19s %d %c", class, &dn, junk);
    fclose(fp);
    if (i != 2)
	{
	close(lfd);
	return;
	}

    /*
     * We might need to convert the delta filename to an absolute pathname.
     */
    here[0] = '\0';
    if (delta_dir[0] != '/')
	{
	getcwd(here, sizeof(here)-1);
	i = strlen(here) - 1;
	if (i >= 0 && here[i] != '/')
	    {
	    here[++i] = '/';
	    here[++i] = '\0';
	    }
	}

    /*
     * Keep applying deltas until we run out or something bad happens.
     */
    for (;;)
	{
	sprintf(delta, "%s.%04d.gz", class, ++dn);
	mk_delta_name(fname, delta);

	if (stat(fname, &sb) < 0)
	    break;

	sprintf(buf, "(cd %s && ctm %s%s%s%s) 2>&1", base_dir,
				set_time ? "-u " : "",
				apply_verbose ? "-v " : "", here, fname);
	if ((ctm = popen(buf, "r")) == NULL)
	    {
	    err("ctm failed to apply %s", delta);
	    break;
	    }

	while (fgets(buf, sizeof(buf), ctm) != NULL)
	    {
	    i = strlen(buf) - 1;
	    if (i >= 0 && buf[i] == '\n')
		buf[i] = '\0';
	    err("ctm: %s", buf);
	    }

	if (pclose(ctm) != 0)
	    {
	    err("ctm failed to apply %s", delta);
	    break;
	    }

	if (delete_after)
	    unlink(fname);

	err("%s applied%s", delta, delete_after ? " and deleted" : "");
	}

    /*
     * Closing the lock file clears the lock.
     */
    close(lfd);
    }
示例#9
0
//-------------------------------------------------------------------------
// Fri Mar  9 15:12:40 EST 2001
// Thu Mar 15 13:40:01 EST 2001
// Mon Mar 26 13:49:08 EST 2001
// Tue Apr  3 16:45:23 EDT 2001
// Mon Apr 30 16:37:43 EDT 2001 -- added support for highway type
// Fri Jul  6 11:37:19 EDT 2001 -- 'tighten-up' search loop
//-------------------------------------------------------------------------
// lookup a CAMAC device (either a serial highway or a module) and
// return o/s specific device number, eg '/dev/sg#'
// puts value into crate.db; leaves unchanged if not found
// NB! called by 'autoconfig()' in cts::verbs
//-------------------------------------------------------------------------
int map_scsi_device( char *highway_name )
{
	char				line[80], *pline, tmp[7];
	char				dsf[3], hwytype;
	int					adapter, i, numOfEntries, scsi_id, sg_number;
	int					status = SUCCESS;		// optimistic
	int					found = FALSE;
	FILE				*fp, *fopen();
	extern struct CRATE	*CRATEdb;				// pointer to in-memory copy of data file

	if( MSGLVL(FUNCTION_NAME) )
		printf( "map_scsi_device('%s')\n", highway_name );

	// open '/proc' filesystem scsi info
	if( (fp = fopen(PROC_FILE, "r")) == NULL ) {
		if( MSGLVL(ALWAYS) )
			fprintf( stderr, "failure to open '%s'\n", PROC_FILE );

		status = FILE_ERROR; 	// serious error !!! no scsi devices to check
		goto MapScsiDevice_Exit;
	}

	// get current db file count
	if( (numOfEntries = get_file_count( CRATE_DB )) <= 0 ) {
		status = FILE_ERROR;
		goto MapScsiDevice_Exit;				// we're done  :<
	}
	if( MSGLVL(DETAILS) )
		printf( "crate.db count= %d\n", numOfEntries );

	// lookup highway name
	if( MSGLVL(DETAILS) )
		printf("msd() looking up '%s'\n", highway_name);
	if( (i = lookup_entry( CRATE_DB, highway_name )) < 0 ) {
		status = NO_DEVICE; 					// no such device in db file
		goto MapScsiDevice_Exit;
	}
	if( MSGLVL(DETAILS) )
		printf( "msd(): lookup index [%d]:%s\n", i, highway_name );

	// point to actual memory
	pline = &line[0];

	// scan all scsi devices
	sg_number = 0;		// start at the beginning
	while( !found && (pline = fgets(line, sizeof(line), fp)) != NULL ) {
		if( strncmp(pline, "Host:", 5) == EQUAL ) {
			sscanf(line, "Host: scsi%d Channel: %*2c Id: %d %*s", &adapter, &scsi_id);

			sprintf(tmp, "GK%c%d", 'A' + adapter, scsi_id);
			if( strncmp(tmp, highway_name, 4) == EQUAL ) {		// found it
				if( QueryHighwayType( tmp ) == SUCCESS )		// determine highway type
					hwytype = tmp[5];

				// we're done, so exit
				found = TRUE;
			}
			else
				sg_number++;
		} // end of if() ....
	} // end of while() ...

	// 'lock' file with semaphore
	if( lock_file() != SUCCESS ) {
		status = FAILURE;		// LOCK_ERROR;		[2001.07.12]
		goto MapScsiDevice_Exit;
	}

	// update memory mapped version
	if( found ) {
		sprintf(dsf, "%03d", sg_number);			// format conversion
		strncpy((CRATEdb+i)->DSFname, dsf, 3);		// real device number
		(CRATEdb+i)->HwyType = hwytype;				// highway type
	}
	else {
		strncpy((CRATEdb+i)->DSFname, "...", 3);	// place-holder device number
		(CRATEdb+i)->HwyType = '.';
	}

	// commit changes to file
	if( commit_entry( CRATE_DB ) != SUCCESS ) {
		status = FAILURE;		// COMMIT_ERROR;	[2001.07.12]
		goto MapScsiDevice_Exit;
	}
	if( MSGLVL(DETAILS) )
		printf( "'%.4s+%.3s+%c'\n", highway_name, (CRATEdb+i)->DSFname, (CRATEdb+i)->HwyType );

	// unlock file
	if( unlock_file() != SUCCESS ) {
		status = FAILURE;		// UNLOCK_ERROR;	[2001.07.12]
		goto MapScsiDevice_Exit;
	}

MapScsiDevice_Exit:
	// cleanup
	if( fp )
		fclose(fp);

	return status;
}
示例#10
0
static int _file_lock_resource(struct cmd_context *cmd, const char *resource,
			       uint32_t flags, struct logical_volume *lv)
{
	char lockfile[PATH_MAX];
	unsigned origin_only = (flags & LCK_ORIGIN_ONLY) ? 1 : 0;
	unsigned revert = (flags & LCK_REVERT) ? 1 : 0;

	switch (flags & LCK_SCOPE_MASK) {
	case LCK_ACTIVATION:
		if (dm_snprintf(lockfile, sizeof(lockfile),
				"%s/A_%s", _lock_dir, resource + 1) < 0) {
			log_error("Too long locking filename %s/A_%s.", _lock_dir, resource + 1);
			return 0;
		}

		if (!lock_file(lockfile, flags))
			return_0;
		break;
	case LCK_VG:
		/* Skip cache refresh for VG_GLOBAL - the caller handles it */
		if (strcmp(resource, VG_GLOBAL))
			lvmcache_drop_metadata(resource, 0);

		if (!strcmp(resource, VG_SYNC_NAMES))
			fs_unlock();

		/* LCK_CACHE does not require a real lock */
		if (flags & LCK_CACHE)
			break;

		if (is_orphan_vg(resource) || is_global_vg(resource)) {
			if (dm_snprintf(lockfile, sizeof(lockfile),
					"%s/P_%s", _lock_dir, resource + 1) < 0) {
				log_error("Too long locking filename %s/P_%s.",
					  _lock_dir, resource + 1);
				return 0;
			}
		} else
			if (dm_snprintf(lockfile, sizeof(lockfile),
					"%s/V_%s", _lock_dir, resource) < 0) {
				log_error("Too long locking filename %s/V_%s.",
					  _lock_dir, resource);
				return 0;
			}

		if (!lock_file(lockfile, flags))
			return_0;
		break;
	case LCK_LV:
		switch (flags & LCK_TYPE_MASK) {
		case LCK_UNLOCK:
			log_very_verbose("Unlocking LV %s%s%s", resource, origin_only ? " without snapshots" : "", revert ? " (reverting)" : "");
			if (!lv_resume_if_active(cmd, resource, origin_only, 0, revert, lv_ondisk(lv)))
				return 0;
			break;
		case LCK_NULL:
			log_very_verbose("Locking LV %s (NL)", resource);
			if (!lv_deactivate(cmd, resource, lv_ondisk(lv)))
				return 0;
			break;
		case LCK_READ:
			log_very_verbose("Locking LV %s (R)", resource);
			if (!lv_activate_with_filter(cmd, resource, 0, lv->status & LV_NOSCAN ? 1 : 0,
						     lv->status & LV_TEMPORARY ? 1 : 0, lv_ondisk(lv)))
				return 0;
			break;
		case LCK_PREAD:
			log_very_verbose("Locking LV %s (PR) - ignored", resource);
			break;
		case LCK_WRITE:
			log_very_verbose("Locking LV %s (W)%s", resource, origin_only ? " without snapshots" : "");
			if (!lv_suspend_if_active(cmd, resource, origin_only, 0, lv_ondisk(lv), lv))
				return 0;
			break;
		case LCK_EXCL:
			log_very_verbose("Locking LV %s (EX)", resource);
			if (!lv_activate_with_filter(cmd, resource, 1, lv->status & LV_NOSCAN ? 1 : 0,
						     lv->status & LV_TEMPORARY ? 1 : 0, lv_ondisk(lv)))
				return 0;
			break;
		default:
			break;
		}
		break;
	default:
		log_error("Unrecognised lock scope: %d",
			  flags & LCK_SCOPE_MASK);
		return 0;
	}

	return 1;
}
示例#11
0
int git_filebuf_open(git_filebuf *file, const char *path, int flags)
{
    int error;
    size_t path_len;

    assert(file && path);

    memset(file, 0x0, sizeof(git_filebuf));

    file->buf_size = WRITE_BUFFER_SIZE;
    file->buf_pos = 0;
    file->fd = -1;

    /* Allocate the main cache buffer */
    file->buffer = git__malloc(file->buf_size);
    if (file->buffer == NULL) {
        error = GIT_ENOMEM;
        goto cleanup;
    }

    /* If we are hashing on-write, allocate a new hash context */
    if (flags & GIT_FILEBUF_HASH_CONTENTS) {
        if ((file->digest = git_hash_new_ctx()) == NULL) {
            error = GIT_ENOMEM;
            goto cleanup;
        }
    }

    /* If we are deflating on-write, */
    if (flags & GIT_FILEBUF_DEFLATE_CONTENTS) {

        /* Initialize the ZLib stream */
        if (deflateInit(&file->zs, Z_BEST_SPEED) != Z_OK) {
            error = git__throw(GIT_EZLIB, "Failed to initialize zlib");
            goto cleanup;
        }

        /* Allocate the Zlib cache buffer */
        file->z_buf = git__malloc(file->buf_size);
        if (file->z_buf == NULL) {
            error = GIT_ENOMEM;
            goto cleanup;
        }

        /* Never flush */
        file->flush_mode = Z_NO_FLUSH;
        file->write = &write_deflate;
    } else {
        file->write = &write_normal;
    }

    /* If we are writing to a temp file */
    if (flags & GIT_FILEBUF_TEMPORARY) {
        char tmp_path[GIT_PATH_MAX];

        /* Open the file as temporary for locking */
        file->fd = gitfo_mktemp(tmp_path, path);
        if (file->fd < 0) {
            error = GIT_EOSERR;
            goto cleanup;
        }

        /* No original path */
        file->path_original = NULL;
        file->path_lock = git__strdup(tmp_path);

        if (file->path_lock == NULL) {
            error = GIT_ENOMEM;
            goto cleanup;
        }
    } else {
        path_len = strlen(path);

        /* Save the original path of the file */
        file->path_original = git__strdup(path);
        if (file->path_original == NULL) {
            error = GIT_ENOMEM;
            goto cleanup;
        }

        /* create the locking path by appending ".lock" to the original */
        file->path_lock = git__malloc(path_len + GIT_FILELOCK_EXTLENGTH);
        if (file->path_lock == NULL) {
            error = GIT_ENOMEM;
            goto cleanup;
        }

        memcpy(file->path_lock, file->path_original, path_len);
        memcpy(file->path_lock + path_len, GIT_FILELOCK_EXTENSION, GIT_FILELOCK_EXTLENGTH);

        /* open the file for locking */
        if ((error = lock_file(file, flags)) < GIT_SUCCESS)
            goto cleanup;
    }

    return GIT_SUCCESS;

cleanup:
    git_filebuf_cleanup(file);
    return git__rethrow(error, "Failed to open file buffer for '%s'", path);
}
示例#12
0
/*############################## read_setup() ###########################*/
void
read_setup(char *file_name,
           char *profile,
           int  *hostname_display_length,
           int  *filename_display_length,
           int  *his_log_set,
           char **hosts,
           int  max_hostname_length)
{
   int         fd;
   uid_t       euid, /* Effective user ID. */
               ruid; /* Real user ID. */
   char        *ptr,
               *buffer = NULL;
   struct stat stat_buf;

   if (setup_file[0] == '\0')
   {
      if ((ptr = getenv("HOME")) != NULL)
      {
         char *wptr;

         (void)strcpy(setup_file, ptr);
         wptr = setup_file + strlen(setup_file);
         *wptr = '/';
         *(wptr + 1) = '.';
         wptr += 2;
         (void)strcpy(wptr, file_name);
         wptr += strlen(file_name);
         *wptr = '.';
         *(wptr + 1) = 's';
         *(wptr + 2) = 'e';
         *(wptr + 3) = 't';
         *(wptr + 4) = 'u';
         *(wptr + 5) = 'p';
         *(wptr + 6) = '.';
         wptr += 7;
         if (profile != NULL)
         {
            (void)strcpy(wptr, profile);
         }
         else
         {
            char hostname[MAX_AFD_NAME_LENGTH];

            ptr = user;
            while ((*ptr != '@') && (*ptr != '\0'))
            {
               *wptr = *ptr;
               wptr++; ptr++;
            }
            if ((*ptr == '@') && (*(ptr + 1) != '\0') && (*(ptr + 1) != ':'))
            {
               *wptr = '@';
               wptr++; ptr++;
               while ((*ptr != ':') && (*ptr != '\0'))
               {
                  *wptr = *ptr;
                  wptr++; ptr++;
               }
            }
            if (get_afd_name(hostname) != INCORRECT)
            {
               *wptr = '.';
               (void)strcpy(wptr + 1, hostname);
            }
         }
      }
      else
      {
         return;
      }
   }

   euid = geteuid();
   ruid = getuid();
   if (euid != ruid)
   {
      if (seteuid(ruid) == -1)
      {
         (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                       ruid, strerror(errno));
      }
   }

   if (stat(setup_file, &stat_buf) == -1)
   {
      if (errno != ENOENT)
      {
         setup_file[0] = '\0';
      }
      if (euid != ruid)
      {
         if (seteuid(euid) == -1)
         {
            (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                          euid, strerror(errno));
         }
      }
      return;
   }

   fd = lock_file(setup_file, ON);
   if (euid != ruid)
   {
      if (seteuid(euid) == -1)
      {
         (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                       euid, strerror(errno));
      }
   }
   if (fd < 0)
   {
      setup_file[0] = '\0';
      return;
   }

   if ((buffer = malloc(stat_buf.st_size + 1)) == NULL)
   {
      (void)close(fd);
      return;
   }
   if (read(fd, buffer, stat_buf.st_size) != stat_buf.st_size)
   {
      free(buffer);
      (void)close(fd);
      return;
   }
   (void)close(fd); /* This will release the lock as well. */
   buffer[stat_buf.st_size] = '\0';

   /* Get the default font. */
   if ((ptr = posi(buffer, FONT_ID)) != NULL)
   {
      int i = 0;

      ptr--;
      while ((*ptr == ' ') || (*ptr == '\t'))
      {
         ptr++;
      }
      while ((*ptr != '\n') && (*ptr != '\0'))
      {
         font_name[i] = *ptr;
         i++; ptr++;
      }
      font_name[i] = '\0';
   }

   /* Get the number of rows. */
   if ((ptr = posi(buffer, ROW_ID)) != NULL)
   {
      int  i = 0;
      char tmp_buffer[MAX_INT_LENGTH + 1];

      ptr--;
      while ((*ptr == ' ') || (*ptr == '\t'))
      {
         ptr++;
      }
      while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
      {
         tmp_buffer[i] = *ptr;
         i++; ptr++;
      }
      tmp_buffer[i] = '\0';
      no_of_rows_set = atoi(tmp_buffer);
   }

   /* Get the line style. */
   if ((ptr = posi(buffer, STYLE_ID)) != NULL)
   {
      int  i = 0;
      char tmp_buffer[MAX_INT_LENGTH + 1];

      ptr--;
      while ((*ptr == ' ') || (*ptr == '\t'))
      {
         ptr++;
      }
      while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
      {
         tmp_buffer[i] = *ptr;
         i++; ptr++;
      }
      tmp_buffer[i] = '\0';
      line_style = atoi(tmp_buffer);
      if (strcmp(file_name, AFD_CTRL) == 0)
      {
         if (line_style <= CHARACTERS_AND_BARS)
         {
            if (line_style == BARS_ONLY)
            {
               line_style = SHOW_LEDS | SHOW_JOBS | SHOW_BARS;
            }
            else if (line_style == CHARACTERS_ONLY)
                 {
                    line_style = SHOW_LEDS | SHOW_JOBS | SHOW_CHARACTERS;
                 }
                 else
                 {
                    line_style = SHOW_LEDS | SHOW_JOBS | SHOW_CHARACTERS | SHOW_BARS;
                 }
         }
         else if (line_style > (SHOW_LEDS | SHOW_JOBS_COMPACT | SHOW_CHARACTERS | SHOW_BARS))
              {
                 line_style = SHOW_LEDS | SHOW_JOBS | SHOW_CHARACTERS | SHOW_BARS;
              }
      }
      else
      {
         if ((line_style != CHARACTERS_AND_BARS) &&
             (line_style != CHARACTERS_ONLY) &&
             (line_style != BARS_ONLY))
         {
            line_style = CHARACTERS_AND_BARS;
         }
      }
   }

   /* Get the other options. */
   if ((ptr = posi(buffer, OTHER_ID)) != NULL)
   {
      int  i = 0;
      char tmp_buffer[MAX_INT_LENGTH + 1];

      ptr--;
      while ((*ptr == ' ') || (*ptr == '\t'))
      {
         ptr++;
      }
      while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
      {
         tmp_buffer[i] = *ptr;
         i++; ptr++;
      }
      tmp_buffer[i] = '\0';
      other_options = atoi(tmp_buffer);
      if (other_options > FORCE_SHIFT_SELECT)
      {
         other_options = DEFAULT_OTHER_OPTIONS;
      }
   }

   /* Get the hostname display length. */
   if (hostname_display_length != NULL)
   {
      if ((ptr = posi(buffer, HOSTNAME_DISPLAY_LENGTH_ID)) != NULL)
      {
         int  i = 0;
         char tmp_buffer[MAX_INT_LENGTH + 1];

         ptr--;
         while ((*ptr == ' ') || (*ptr == '\t'))
         {
            ptr++;
         }
         while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
         {
            tmp_buffer[i] = *ptr;
            i++; ptr++;
         }
         tmp_buffer[i] = '\0';
         *hostname_display_length = atoi(tmp_buffer);
#ifdef WITH_HOSTNAME_LENGTH_CORRECTION
         if (*hostname_display_length > MAX_HOSTNAME_LENGTH)
         {
            *hostname_display_length = MAX_HOSTNAME_LENGTH;
         }
#endif
      }
      else
      {
         *hostname_display_length = DEFAULT_HOSTNAME_DISPLAY_LENGTH;
      }
   }

   /* Get the filename display length. */
   if (filename_display_length != NULL)
   {
      if ((ptr = posi(buffer, FILENAME_DISPLAY_LENGTH_ID)) != NULL)
      {
         int  i = 0;
         char tmp_buffer[MAX_INT_LENGTH + 1];

         ptr--;
         while ((*ptr == ' ') || (*ptr == '\t'))
         {
            ptr++;
         }
         while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
         {
            tmp_buffer[i] = *ptr;
            i++; ptr++;
         }
         tmp_buffer[i] = '\0';
         *filename_display_length = atoi(tmp_buffer);
         if (*filename_display_length > MAX_FILENAME_LENGTH)
         {
            *filename_display_length = MAX_FILENAME_LENGTH;
         }
      }
      else
      {
         *filename_display_length = DEFAULT_FILENAME_DISPLAY_LENGTH;
      }
   }

   /* Get the number of history log entries. */
   if (his_log_set != NULL)
   {
      if ((ptr = posi(buffer, NO_OF_HISTORY_LENGTH_ID)) != NULL)
      {
         int  i = 0;
         char tmp_buffer[MAX_INT_LENGTH + 1];

         ptr--;
         while ((*ptr == ' ') || (*ptr == '\t'))
         {
            ptr++;
         }
         while ((*ptr != '\n') && (*ptr != '\0') && (i < MAX_INT_LENGTH))
         {
            tmp_buffer[i] = *ptr;
            i++; ptr++;
         }
         tmp_buffer[i] = '\0';
         *his_log_set = atoi(tmp_buffer);
         if (*his_log_set > MAX_LOG_HISTORY)
         {
            *his_log_set = MAX_LOG_HISTORY;
         }
      }
      else
      {
         *his_log_set = DEFAULT_NO_OF_HISTORY_LOGS;
      }
   }

   /* Get the list of unimportant host's/AFD's. */
   if (hosts != NULL)
   {
      int i, j, gotcha;

      ptr = buffer;
      while ((ptr = posi(ptr, UNIMPORTANT_ID)) != NULL)
      {
         i = 0;
         gotcha = NO;
         ptr--;
         while ((*ptr == ' ') || (*ptr == '\t'))
         {
            ptr++;
         }
         while ((*ptr != '\n') && (*ptr != '\0') && (i < max_hostname_length))
         {
            hosts[no_of_short_lines][i] = *ptr;
            i++; ptr++;
         }
         hosts[no_of_short_lines][i] = '\0';
         if (i > 0)
         {
            for (j = 0; j < (no_of_short_lines - 1); j++)
            {
               if (strcmp(hosts[no_of_short_lines], hosts[j]) == 0)
               {
                  gotcha = YES;
                  break;
               }
            }
            if (gotcha == NO)
            {
               no_of_short_lines++;
            }
         }
      }
   }
   free(buffer);

   return;
}
示例#13
0
/*############################# write_setup() ###########################*/
void
write_setup(int  hostname_display_length,
            int  filename_display_length,
            int  his_log_set,
            char **hosts,
            int  max_no_hosts,
            int  max_hostname_length)
{
   int         buf_length,
               fd = -1,
               length;
   uid_t       euid, /* Effective user ID. */
               ruid; /* Real user ID. */
   char        *buffer;
   struct stat stat_buf;
   
   if (setup_file[0] == '\0')
   {
      /*
       * Since we have failed to find the users home directory,
       * there is no need to continue.
       */
      return;
   }

   euid = geteuid();
   ruid = getuid();
   if (euid != ruid)
   {
      if (seteuid(ruid) == -1)
      {
         (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                       ruid, strerror(errno));
      }
   }
   if (stat(setup_file, &stat_buf) == -1)
   {
      if (errno == ENOENT)
      {
         fd = open(setup_file, (O_WRONLY | O_CREAT | O_TRUNC),
                   (S_IRUSR | S_IWUSR));
         if (fd < 0)
         {
            (void)xrec(ERROR_DIALOG,
                       "Failed to open() setup file %s : %s (%s %d)",
                       setup_file, strerror(errno), __FILE__, __LINE__);
            if (euid != ruid)
            {
               if (seteuid(euid) == -1)
               {
                  (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                                euid, strerror(errno));
               }
            }
            return;
         }
      }
   }
   if (euid != ruid)
   {
      if (seteuid(euid) == -1)
      {
         (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                       euid, strerror(errno));
      }
   }

   buf_length = strlen(FONT_ID) +  1 + strlen(font_name) + 1 +
                strlen(ROW_ID) + 1 + MAX_INT_LENGTH + 1 +
                strlen(STYLE_ID) + 1 + MAX_INT_LENGTH + 1 +
                strlen(OTHER_ID) + 1 + MAX_INT_LENGTH + 1;
   if (hostname_display_length != -1)
   {
      buf_length += strlen(HOSTNAME_DISPLAY_LENGTH_ID) + 1 + MAX_INT_LENGTH + 1;
   }
   if (filename_display_length != -1)
   {
      buf_length += strlen(FILENAME_DISPLAY_LENGTH_ID) + 1 + MAX_INT_LENGTH + 1;
   }
   if (his_log_set != -1)
   {
      buf_length += strlen(NO_OF_HISTORY_LENGTH_ID) + 1 + MAX_INT_LENGTH + 1;
   }
   if (hosts != NULL)
   {
      buf_length += ((strlen(UNIMPORTANT_ID) + 1 + max_hostname_length + 1) *
                     max_no_hosts);
   }
   if ((buffer = malloc(buf_length)) == NULL)
   {
      (void)xrec(ERROR_DIALOG, "malloc() error : %s (%s %d)",
                 strerror(errno), __FILE__, __LINE__);
      if (fd != -1)
      {
         (void)close(fd);
      }
      return;
   }
   euid = geteuid();
   ruid = getuid();
   if (euid != ruid)
   {
      if (seteuid(ruid) == -1)
      {
         (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                       ruid, strerror(errno));
      }
   }
   if (fd == -1)
   {
      fd = lock_file(setup_file, ON);
      if (euid != ruid)
      {
         if (seteuid(euid) == -1)
         {
            (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                          euid, strerror(errno));
         }
      }
      if (fd < 0)
      {
         free(buffer);
         return;
      }
      if (ftruncate(fd, 0) == -1)
      {
         (void)xrec(ERROR_DIALOG, "Failed to truncate file %s : %s (%s %d)\n",
                    setup_file, strerror(errno), __FILE__, __LINE__);
      }
      length = sprintf(buffer, "%s %s\n%s %d\n%s %d\n%s %d\n",
                       FONT_ID, font_name, ROW_ID, no_of_rows_set,
                       STYLE_ID, line_style, OTHER_ID, other_options);
      if (hostname_display_length != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           HOSTNAME_DISPLAY_LENGTH_ID, hostname_display_length);
      }
      if (filename_display_length != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           FILENAME_DISPLAY_LENGTH_ID, filename_display_length);
      }
      if (his_log_set != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           NO_OF_HISTORY_LENGTH_ID, his_log_set);
      }
      if (hosts != NULL)
      {
         int i;

         for (i = 0; i < max_no_hosts; i++)
         {
            length += sprintf(&buffer[length], "%s %s\n",
                              UNIMPORTANT_ID, hosts[i]);
         }
      }
      if (write(fd, buffer, length) != length)
      {
         (void)xrec(ERROR_DIALOG,
                    "Failed to write to setup file %s : %s (%s %d)",
                    setup_file, strerror(errno), __FILE__, __LINE__);
      }
      (void)close(fd);
   }
   else
   {
      int lock_fd;

      lock_fd = lock_file(setup_file, ON);
      if (euid != ruid)
      {
         if (seteuid(euid) == -1)
         {
            (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                          euid, strerror(errno));
         }
      }
      if (lock_fd < 0)
      {
         (void)close(fd);
         free(buffer);
         return;
      }
      if (ftruncate(fd, 0) == -1)
      {
         (void)xrec(ERROR_DIALOG, "Failed to truncate file %s : %s (%s %d)\n",
                    setup_file, strerror(errno), __FILE__, __LINE__);
      }
      length = sprintf(buffer, "%s %s\n%s %d\n%s %d\n%s %d\n",
                       FONT_ID, font_name, ROW_ID, no_of_rows_set,
                       STYLE_ID, line_style, OTHER_ID, other_options);
      if (hostname_display_length != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           HOSTNAME_DISPLAY_LENGTH_ID, hostname_display_length);
      }
      if (filename_display_length != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           FILENAME_DISPLAY_LENGTH_ID, filename_display_length);
      }
      if (his_log_set != -1)
      {
         length += sprintf(&buffer[length], "%s %d\n",
                           NO_OF_HISTORY_LENGTH_ID, his_log_set);
      }
      if (hosts != NULL)
      {
         int i;

         for (i = 0; i < max_no_hosts; i++)
         {
            length += sprintf(&buffer[length], "%s %s\n",
                              UNIMPORTANT_ID, hosts[i]);
         }
      }
      if (write(fd, buffer, length) != length)
      {
         (void)xrec(ERROR_DIALOG,
                    "Failed to write to setup file %s : %s (%s %d)",
                    setup_file, strerror(errno), __FILE__, __LINE__);
      }
      (void)close(fd);
      (void)close(lock_fd);
   }
   free(buffer);

   return;
}
示例#14
0
static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *options, gboolean ftp, void *handle)
{
  FILE *f;
  int ret;
  gchar *tmpfilename;
  gboolean failure = FALSE;
  CurlDownloadOptions cdo = {0, NULL, NULL};

  /* Check file */
  if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
  {
    if (options == NULL || (!options->check_file_server_time &&
                            !options->use_etag)) {
      /* Nothing to do as file already exists and we don't want to check server */
      return DOWNLOAD_NOT_REQUIRED;
    }

    time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
    /* Get the modified time of this file */
    GStatBuf buf;
    (void)g_stat ( fn, &buf );
    time_t file_time = buf.st_mtime;
    if ( (time(NULL) - file_time) < tile_age ) {
      /* File cache is too recent, so return */
      return DOWNLOAD_NOT_REQUIRED;
    }

    if (options != NULL && options->check_file_server_time) {
      cdo.time_condition = file_time;
    }
    if (options != NULL && options->use_etag) {
      get_etag(fn, &cdo);
    }

  } else {
    gchar *dir = g_path_get_dirname ( fn );
    if ( g_mkdir_with_parents ( dir , 0777 ) != 0)
      g_warning ("%s: Failed to mkdir %s", __FUNCTION__, dir );
    g_free ( dir );
  }

  tmpfilename = g_strdup_printf("%s.tmp", fn);
  if (!lock_file ( tmpfilename ) )
  {
    g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
    g_free ( tmpfilename );
    if (options->use_etag)
      g_free ( cdo.etag );
    return DOWNLOAD_FILE_WRITE_ERROR;
  }
  f = g_fopen ( tmpfilename, "w+b" );  /* truncate file and open it */
  if ( ! f ) {
    g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
    g_free ( tmpfilename );
    if (options->use_etag)
      g_free ( cdo.etag );
    return DOWNLOAD_FILE_WRITE_ERROR;
  }

  /* Call the backend function */
  ret = curl_download_get_url ( hostname, uri, f, options, ftp, &cdo, handle );

  DownloadResult_t result = DOWNLOAD_SUCCESS;

  if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
    g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
    failure = TRUE;
    result = DOWNLOAD_HTTP_ERROR;
  }

  if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
    g_debug("%s: file content checking failed", __FUNCTION__);
    failure = TRUE;
    result = DOWNLOAD_CONTENT_ERROR;
  }

  fclose ( f );
  f = NULL;

  if (failure)
  {
    g_warning(_("Download error: %s"), fn);
    if ( g_remove ( tmpfilename ) != 0 )
      g_warning( ("Failed to remove: %s"), tmpfilename);
    unlock_file ( tmpfilename );
    g_free ( tmpfilename );
    if ( options != NULL && options->use_etag ) {
      g_free ( cdo.etag );
      g_free ( cdo.new_etag );
    }
    return result;
  }

  if (ret == CURL_DOWNLOAD_NO_NEWER_FILE)  {
    (void)g_remove ( tmpfilename );
     // update mtime of local copy
     // Not security critical, thus potential Time of Check Time of Use race condition is not bad
     // coverity[toctou]
     if ( g_utime ( fn, NULL ) != 0 )
       g_warning ( "%s couldn't set time on: %s", __FUNCTION__, fn );
  } else {
    if ( options != NULL && options->convert_file )
      options->convert_file ( tmpfilename );

    if ( options != NULL && options->use_etag ) {
      if ( cdo.new_etag ) {
        /* server returned an etag value */
        set_etag(fn, tmpfilename, &cdo);
      }
    }

     /* move completely-downloaded file to permanent location */
     if ( g_rename ( tmpfilename, fn ) )
        g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
  }
  unlock_file ( tmpfilename );
  g_free ( tmpfilename );

  if ( options != NULL && options->use_etag ) {
    g_free ( cdo.etag );
    g_free ( cdo.new_etag );
  }
  return DOWNLOAD_SUCCESS;
}
示例#15
0
int
main (int argc, char **argv)
{
  int c;
  bool running_suid, running_sgid;
  void *lockstate;
  char *scorefile;
  char *end, *nl, *user, *data;
  const char *prefix, *user_prefix = NULL;
  struct score_entry *scores;
  struct score_entry newscore;
  bool reverse = false;
  ptrdiff_t scorecount, scorealloc;
  ptrdiff_t max_scores = MAX_SCORES;

  srand (time (0));

  while ((c = getopt (argc, argv, "hrm:d:")) != -1)
    switch (c)
      {
      case 'h':
	usage (EXIT_SUCCESS);
	break;
      case 'd':
	user_prefix = optarg;
	break;
      case 'r':
	reverse = 1;
	break;
      case 'm':
	{
	  intmax_t m = strtoimax (optarg, &end, 10);
	  if (optarg == end || *end || m < 0)
	    usage (EXIT_FAILURE);
	  max_scores = min (m, MAX_SCORES);
	}
	break;
      default:
	usage (EXIT_FAILURE);
      }

  if (argc - optind != 3)
    usage (EXIT_FAILURE);

  running_suid = (getuid () != geteuid ());
  running_sgid = (getgid () != getegid ());
  if (running_suid && running_sgid)
    lose ("This program can run either suid or sgid, but not both.");

  prefix = get_prefix (running_suid || running_sgid, user_prefix);

  scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  if (!scorefile)
    lose_syserr ("Couldn't allocate score file");

  char *z = stpcpy (scorefile, prefix);
  *z++ = '/';
  strcpy (z, argv[optind]);

  newscore.score = normalize_integer (argv[optind + 1]);
  if (! newscore.score)
    {
      fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
      return EXIT_FAILURE;
    }

  user = get_user_id ();
  if (! user)
    lose_syserr ("Couldn't determine user id");
  data = argv[optind + 2];
  if (strlen (data) > MAX_DATA_LEN)
    data[MAX_DATA_LEN] = '\0';
  nl = strchr (data, '\n');
  if (nl)
    *nl = '\0';
  newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
  if (! newscore.user_data
      || sprintf (newscore.user_data, "%s %s", user, data) < 0)
    lose_syserr ("Memory exhausted");

  if (lock_file (scorefile, &lockstate) < 0)
    lose_syserr ("Failed to lock scores file");

  if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to read scores file");
    }
  if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to add score");
    }
  sort_scores (scores, scorecount, reverse);
  /* Limit the number of scores.  If we're using reverse sorting, then
     also increment the beginning of the array, to skip over the
     *smallest* scores.  Otherwise, just decrementing the number of
     scores suffices, since the smallest is at the end. */
  if (scorecount > max_scores)
    {
      if (reverse)
	scores += scorecount - max_scores;
      scorecount = max_scores;
    }
  if (write_scores (scorefile, running_sgid ? 0664 : 0644,
		    scores, scorecount) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to write scores file");
    }
  if (unlock_file (scorefile, lockstate) < 0)
    lose_syserr ("Failed to unlock scores file");
  exit (EXIT_SUCCESS);
}
示例#16
0
int pcf_inccount(const char *filename, unsigned long by)
{
  FILE *f;
  int rc;
  unsigned long count;

  /* Should we use a page count file? */
  if (filename == NULL || *filename == '\0') return 0;

  /* Open the file. We need to access the old contents: this excludes the "w",
     "a" and "w+" modes. The operation should create the file if it doesn't
     exist: this excludes the "r" and "r+" modes. Hence the only choice is "a+".
     Note that this procedure makes it unavoidable to accept an empty file as
     being valid. This is, however, anyway necessary because of the fopen() and
     fcntl() calls being not in one transaction.
  */
  if ((f = fopen(filename, "a+")) == NULL) {
    fprintf(stderr, ERRPREFIX "Cannot open page count file `%s': %s.\n",
      filename, strerror(errno));
    return 1;
  }

  /* Lock the file for writing (exclusively) */
  if (lock_file(filename, f, F_WRLCK) != 0) {
    fclose(f);
    return 1;
  }

  /* Reposition on the beginning. fopen() with "a" as above opens the file at
     EOF. */
  if (fseek(f, 0L, SEEK_SET) != 0) {
    fprintf(stderr, ERRPREFIX "fseek() failed on `%s': %s.\n",
      filename, strerror(errno));
    fclose(f);
    return 1;
  }

  /* Read the contents */
  if (read_count(filename, f, &count) != 0) {
    fclose(f);
    return -1;
  }

  /* Rewrite the file */
  rc = 0;
  {
    FILE *f1 = fopen(filename, "w");

    if (f1 == NULL) {
      fprintf(stderr, ERRPREFIX 
	"Error opening page count file `%s' a second time: %s.\n",
	filename, strerror(errno));
      rc = 1;
    }
    else {
      if (fprintf(f1, "%lu\n", count + by) < 0) {
	fprintf(stderr, ERRPREFIX "Error writing to `%s': %s.\n",
	  filename, strerror(errno));
	rc = -1;
      }
      if (fclose(f1) != 0) {
	fprintf(stderr,
	  ERRPREFIX "Error closing `%s' after writing: %s.\n",
	  filename, strerror(errno));
	rc = -1;
      }
    }
  }

  /* Close the file (this releases the lock) */
  if (fclose(f) != 0)
    fprintf(stderr, WARNPREFIX "Error closing `%s': %s.\n",
      filename, strerror(errno));

  return rc;
}
示例#17
0
/** Initialize the SSL context.
 * \return pointer to SSL context object.
 */
SSL_CTX *
ssl_init(char *private_key_file, char *ca_file, int req_client_cert)
{
  const SSL_METHOD *meth;       /* If this const gives you a warning, you're
                                   using an old version of OpenSSL. Walker, this means you! */
  /* uint8_t context[128]; */
  DH *dh;
  unsigned int reps = 1;

  if (!bio_err) {
    if (!SSL_library_init())
      return NULL;
    SSL_load_error_strings();
    /* Error write context */
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
  }

  lock_file(stderr);
  fputs("Seeding OpenSSL random number pool.\n", stderr);
  unlock_file(stderr);
  while (!RAND_status()) {
    /* At this point, a system with /dev/urandom or a EGD file in the usual
       places will have enough entropy. Otherwise, be lazy and use random numbers
       until it's satisfied. */
    uint32_t gibberish[4];
    int n;

    /* sfmt_fill_array32 requires a much larger array. */
    for (n = 0; n < 4; n++)
      gibberish[n] = sfmt_genrand_uint32(&rand_state);

    RAND_seed(gibberish, sizeof gibberish);

    reps += 1;
  }

  lock_file(stderr);
  fprintf(stderr, "Seeded after %u %s.\n", reps, reps > 1 ? "cycles" : "cycle");
  unlock_file(stderr);

  /* Set up SIGPIPE handler here? */

  /* Create context */
  meth = SSLv23_server_method();
  ctx = SSL_CTX_new(meth);

  /* Load keys/certs */
  if (private_key_file && *private_key_file) {
    if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) {
      ssl_errordump
        ("Unable to load server certificate - only anonymous ciphers supported.");
    }
    if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) {
      ssl_errordump
        ("Unable to load private key - only anonymous ciphers supported.");
    }
  }

  /* Load trusted CAs */
  if (ca_file && *ca_file) {
    if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) {
      ssl_errordump("Unable to load CA certificates");
    } else {
      if (req_client_cert)
        SSL_CTX_set_verify(ctx,
                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                           client_verify_callback);
      else
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, client_verify_callback);
#if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
      SSL_CTX_set_verify_depth(ctx, 1);
#endif
    }
  }

  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL);
  SSL_CTX_set_mode(ctx,
                   SSL_MODE_ENABLE_PARTIAL_WRITE |
                   SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

  /* Set up DH callback */
  dh = get_dh1024();
  SSL_CTX_set_tmp_dh(ctx, dh);
  /* The above function makes a private copy of this */
  DH_free(dh);

  /* Set the cipher list to the usual default list, except that
   * we'll allow anonymous diffie-hellman, too.
   */
  SSL_CTX_set_cipher_list(ctx, "ALL:ADH:RC4+RSA:+SSLv2:@STRENGTH");

  /* Set up session cache if we can */
  /*
     strncpy((char *) context, MUDNAME, 128);
     SSL_CTX_set_session_id_context(ctx, context, strlen(context));
   */

  return ctx;
}
示例#18
0
/*
 * Public functions
 */
int cu_rrd_create_file(const char *filename, /* {{{ */
                       const data_set_t *ds, const value_list_t *vl,
                       const rrdcreate_config_t *cfg) {
  char **argv;
  int argc;
  char **rra_def = NULL;
  int rra_num;
  char **ds_def = NULL;
  int ds_num;
  int status = 0;
  time_t last_up;
  unsigned long stepsize;

  if (check_create_dir(filename))
    return -1;

  if ((rra_num = rra_get(&rra_def, vl, cfg)) < 1) {
    P_ERROR("cu_rrd_create_file failed: Could not calculate RRAs");
    return -1;
  }

  if ((ds_num = ds_get(&ds_def, ds, vl, cfg)) < 1) {
    P_ERROR("cu_rrd_create_file failed: Could not calculate DSes");
    rra_free(rra_num, rra_def);
    return -1;
  }

  argc = ds_num + rra_num;

  if ((argv = malloc(sizeof(*argv) * (argc + 1))) == NULL) {
    P_ERROR("cu_rrd_create_file failed: %s", STRERRNO);
    rra_free(rra_num, rra_def);
    ds_free(ds_num, ds_def);
    return -1;
  }

  memcpy(argv, ds_def, ds_num * sizeof(char *));
  memcpy(argv + ds_num, rra_def, rra_num * sizeof(char *));
  argv[ds_num + rra_num] = NULL;

  last_up = CDTIME_T_TO_TIME_T(vl->time);
  if (last_up <= 0)
    last_up = time(NULL);
  last_up -= 1;

  if (cfg->stepsize > 0)
    stepsize = cfg->stepsize;
  else
    stepsize = (unsigned long)CDTIME_T_TO_TIME_T(vl->interval);

  if (cfg->async) {
    status = srrd_create_async(filename, stepsize, last_up, argc,
                               (const char **)argv);
    if (status != 0)
      P_WARNING("cu_rrd_create_file: srrd_create_async (%s) "
                "returned status %i.",
                filename, status);
  } else /* synchronous */
  {
    status = lock_file(filename);
    if (status != 0) {
      if (status == EEXIST)
        P_NOTICE("cu_rrd_create_file: File \"%s\" is already being created.",
                 filename);
      else
        P_ERROR("cu_rrd_create_file: Unable to lock file \"%s\".", filename);
    } else {
      status =
          srrd_create(filename, stepsize, last_up, argc, (const char **)argv);

      if (status != 0) {
        P_WARNING("cu_rrd_create_file: srrd_create (%s) returned status %i.",
                  filename, status);
      } else {
        DEBUG("cu_rrd_create_file: Successfully created RRD file \"%s\".",
              filename);
      }
      unlock_file(filename);
    }
  }

  free(argv);
  ds_free(ds_num, ds_def);
  rra_free(rra_num, rra_def);

  return status;
} /* }}} int cu_rrd_create_file */
示例#19
0
文件: fconc.c 项目: shmmy/OS
int main(int argc, char ** argv)
{
    int OUT;
    int TMP;
    int i;
    const char * output;
    int duplicate = 0;
    int W_FLAGS = O_CREAT | O_WRONLY | O_TRUNC;
    int C_PERMS = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH ;

    if (argc == 1)
    {
        perror("Use at least 1 file name when calling fconc\n");
        exit(EX_USAGE);
    }
    if (argc == 2)
    {
        //No need to chance anything
        exit(0);
    }
    else
    {
        output = argv[argc-1];
    }

    for (i=1; i<(argc-1); i++)
    {
        if (strcmp (argv[i], output) ==0 )
        {
            duplicate = 1;
            break;
        }
    }

    if (duplicate)
    {

        TMP = open("/tmp/fconc.out.tmp",W_FLAGS,C_PERMS);
        if (TMP < 0)
        {
            perror("Error opening tmp file, is another instance running?\n");
            exit(EX_TEMPFAIL);
        }

        lock_file(TMP,F_WRLCK);
        for(i=1; i <(argc-1); i++)
        {
            write_file(TMP,argv[i]);
        }
        unlock_file(TMP);
        if ( close(TMP) < 0)
        {
            perror("Could  not close tmp file");
            exit(EX_IOERR);
        }
        OUT = open(output,W_FLAGS,C_PERMS);
        if (OUT < 0)
        {
            perror("Error handling output file\n");
            exit(EX_IOERR);
        }

        lock_file(OUT,F_WRLCK);
        write_file(OUT,"/tmp/fconc.out.tmp");
        unlock_file(OUT);
        if ( close (OUT) < 0 )
        {
            perror("Could not close output file");
            exit(EX_IOERR);
        }
        if (unlink("/tmp/fconc.out.tmp") != 0)
        {
            perror("Error deleting temporary file, please remove /tmp/fconc.out.tmp\n");
            exit(EX__BASE);
        }
    }

    else
    {
        OUT = open(output,W_FLAGS,C_PERMS);
        if (OUT < 0)
        {
            perror("Error handling output file\n");
            exit(EX_IOERR);
        }
        lock_file(OUT,F_WRLCK);
        for (i=1; i<(argc-1); i++)
        {
            write_file(OUT,argv[i]);
        }
        unlock_file(OUT);
        if ( close(OUT) < 0 )
        {
            perror("Could not close out file");
            exit(EX_IOERR);
        }
    }
    exit(EXIT_SUCCESS);
}
示例#20
0
//-------------------------------------------------------------------------
// add_entry()
// Thu Jan 11 10:41:13 EST 2001
// Tue Apr  3 16:28:20 EDT 2001
//-------------------------------------------------------------------------
// Add a cts or crate entry to the appropriate db. The new entry is inserted 
// 	into the list alphabetically.
//
// input:	db type, 
// 			pointer to a c-string containing a complete entry
// output:	status
//-------------------------------------------------------------------------
int add_entry( int dbType, char *newEntry )
{
	void					*dbptr;						// re-usable pointer for dbs
	int						entrySize, i, numOfEntries;
	int						status = SUCCESS;			// assume the best
	extern struct MODULE	*CTSdb;		// pointer to in-memory copy of data file
	extern struct CRATE		*CRATEdb;	// pointer to in-memory copy of data file

	if( MSGLVL(FUNCTION_NAME) )
		printf( "add_entry()\n" );

//----------------------------
//	adding an entry 
//----------------------------
//-- 'critical section' start
//----------------------------
	// 'lock' with semaphore
	if( lock_file() != SUCCESS ) {
		status = LOCK_ERROR;
		goto AddEntry_Exit;
	}

	// get current number of entries
	if( (numOfEntries = get_file_count(dbType)) < 0 ) {
		status = FILE_ERROR;
		goto AddEntry_Exit;
	}

	// cull db specific info
	switch( dbType ) {
		case CTS_DB:
			dbptr = (void *)CTSdb;
			entrySize = MODULE_ENTRY;
			break;

		case CRATE_DB:
			dbptr = (void *)CRATEdb;
			entrySize = CRATE_ENTRY;
			break;
	}

	// shift current entries by one
	if( numOfEntries )		// ... only if any entries exist
		for( i = numOfEntries - 1; i >= 0; --i )
			memcpy( (char *)dbptr+((i + 1) * entrySize),
					(char *)dbptr+( i      * entrySize),
					entrySize
					);

	// put new entry at head of list
	memcpy( (char *)dbptr, newEntry, entrySize );

	// insertion sort
	if( numOfEntries > 0 ) 		// only insert if more than one entry exists already
		if( issort(dbptr, numOfEntries + 1, entrySize, compare_str) != 0 ) {
			status = ERROR;
			goto AddEntry_Exit;
		}

	// commit change to file
	if( commit_entry(dbType) != SUCCESS ) {
		status = COMMIT_ERROR;
		goto AddEntry_Exit;
	}

	// release semaphore
	if( unlock_file() != SUCCESS )
		status = UNLOCK_ERROR;

//----------------------------
//-- 'critical section' finish
//----------------------------

AddEntry_Exit:
	if( MSGLVL(DETAILS) ) {
		printf( "add_entry(): " ); ShowStatus( status );
	}

	return status;
}
示例#21
0
文件: module_udp.c 项目: kdzm/zmap
int udp_global_initialize(struct state_conf *conf) {
	char *args, *c;
	int i;
	unsigned int n;

	FILE *inp;

	num_ports = conf->source_port_last - conf->source_port_first + 1;

	udp_send_msg = strdup(udp_send_msg_default);
	udp_send_msg_len = strlen(udp_send_msg);

	if (!(conf->probe_args && strlen(conf->probe_args) > 0))
		return(0);

	args = strdup(conf->probe_args);
	if (! args) exit(1);

	if (strcmp(args, "template-fields") == 0) {
		lock_file(stderr);
		fprintf(stderr, "%s",
			"List of allowed UDP template fields (name: description)\n\n");
		for (uint32_t i = 0; i < udp_num_template_field_types; ++i) {
			fprintf(stderr, "%s: %s\n",
				udp_payload_template_fields[i].name,
				udp_payload_template_fields[i].desc);
		}
		fprintf(stderr, "%s\n" ,"");
		unlock_file(stderr);
		exit(0);
	}

	c = strchr(args, ':');
	if (! c) {
		free(args);
		free(udp_send_msg);
		log_fatal("udp", udp_usage_error);
		exit(1);
	}

	*c++ = 0;

	if (strcmp(args, "text") == 0) {
		free(udp_send_msg);
		udp_send_msg = strdup(c);
		udp_send_msg_len = strlen(udp_send_msg);

	} else if (strcmp(args, "file") == 0 || strcmp(args, "template") == 0) {
		inp = fopen(c, "rb");
		if (!inp) {
			free(args);
			free(udp_send_msg);
			log_fatal("udp", "could not open UDP data file '%s'\n", c);
			exit(1);
		}
		free(udp_send_msg);
		udp_send_msg = xmalloc(MAX_UDP_PAYLOAD_LEN);
		udp_send_msg_len = fread(udp_send_msg, 1, MAX_UDP_PAYLOAD_LEN, inp);
		fclose(inp);

		if (strcmp(args, "template") == 0) {
			udp_send_substitutions = 1;
			udp_template = udp_template_load(udp_send_msg, udp_send_msg_len);
		}

	} else if (strcmp(args, "hex") == 0) {
		udp_send_msg_len = strlen(c) / 2;
		free(udp_send_msg);
		udp_send_msg = xmalloc(udp_send_msg_len);

		for (i=0; i < udp_send_msg_len; i++) {
			if (sscanf(c + (i*2), "%2x", &n) != 1) {
				free(args);
				free(udp_send_msg);
				log_fatal("udp", "non-hex character: '%c'", c[i*2]);
				exit(1);
			}
			udp_send_msg[i] = (n & 0xff);
		}
	} else {
		log_fatal("udp", udp_usage_error);
		free(udp_send_msg);
		free(args);
		exit(1);
	}

	if (udp_send_msg_len > MAX_UDP_PAYLOAD_LEN) {
		log_warn("udp", "warning: reducing UDP payload to %d "
				"bytes (from %d) to fit on the wire\n",
				MAX_UDP_PAYLOAD_LEN, udp_send_msg_len);
		udp_send_msg_len = MAX_UDP_PAYLOAD_LEN;
	}
	free(args);
	return EXIT_SUCCESS;
}
示例#22
0
文件: hashes.c 项目: sm-350/hashcat
int save_hash (hashcat_ctx_t *hashcat_ctx)
{
  hashes_t        *hashes       = hashcat_ctx->hashes;
  hashconfig_t    *hashconfig   = hashcat_ctx->hashconfig;
  user_options_t  *user_options = hashcat_ctx->user_options;

  const char *hashfile = hashes->hashfile;

  char *new_hashfile;
  char *old_hashfile;

  hc_asprintf (&new_hashfile, "%s.new", hashfile);
  hc_asprintf (&old_hashfile, "%s.old", hashfile);

  unlink (new_hashfile);

  char separator = hashconfig->separator;

  FILE *fp = fopen (new_hashfile, "wb");

  if (fp == NULL)
  {
    event_log_error (hashcat_ctx, "%s: %s", new_hashfile, strerror (errno));

    free (new_hashfile);
    free (old_hashfile);

    return -1;
  }

  if (lock_file (fp) == -1)
  {
    fclose (fp);

    event_log_error (hashcat_ctx, "%s: %s", new_hashfile, strerror (errno));

    free (new_hashfile);
    free (old_hashfile);

    return -1;
  }

  u8 *out_buf = (u8 *) hcmalloc (HCBUFSIZ_LARGE);

  for (u32 salt_pos = 0; salt_pos < hashes->salts_cnt; salt_pos++)
  {
    if (hashes->salts_shown[salt_pos] == 1) continue;

    salt_t *salt_buf = &hashes->salts_buf[salt_pos];

    for (u32 digest_pos = 0; digest_pos < salt_buf->digests_cnt; digest_pos++)
    {
      u32 idx = salt_buf->digests_offset + digest_pos;

      if (hashes->digests_shown[idx] == 1) continue;

      if (hashconfig->opts_type & OPTS_TYPE_BINARY_HASHFILE)
      {
        if ((hashconfig->hash_mode == 2500) || (hashconfig->hash_mode == 2501))
        {
          hccapx_t hccapx;

          to_hccapx_t (hashcat_ctx, &hccapx, salt_pos, digest_pos);

          hc_fwrite (&hccapx, sizeof (hccapx_t), 1, fp);
        }
        else
        {
          // TODO
        }
      }
      else
      {
        if (user_options->username == true)
        {
          user_t *user = hashes->hash_info[idx]->user;

          u32 i;

          for (i = 0; i < user->user_len; i++) fputc (user->user_name[i], fp);

          fputc (separator, fp);
        }

        out_buf[0] = 0;

        ascii_digest (hashcat_ctx, (char *) out_buf, HCBUFSIZ_LARGE, salt_pos, digest_pos);

        fprintf (fp, "%s" EOL, out_buf);
      }
    }
  }

  hcfree (out_buf);

  fflush (fp);

  fclose (fp);

  unlink (old_hashfile);

  if (rename (hashfile, old_hashfile) != 0)
  {
    event_log_error (hashcat_ctx, "Rename file '%s' to '%s': %s", hashfile, old_hashfile, strerror (errno));

    free (new_hashfile);
    free (old_hashfile);

    return -1;
  }

  unlink (hashfile);

  if (rename (new_hashfile, hashfile) != 0)
  {
    event_log_error (hashcat_ctx, "Rename file '%s' to '%s': %s", new_hashfile, hashfile, strerror (errno));

    free (new_hashfile);
    free (old_hashfile);

    return -1;
  }

  unlink (old_hashfile);

  free (new_hashfile);
  free (old_hashfile);

  return 0;
}
示例#23
0
文件: send.c 项目: 340211173/zmap
// one sender thread
int send_run(sock_t st, shard_t *s)
{
	log_trace("send", "send thread started");
	pthread_mutex_lock(&send_mutex);
	// Allocate a buffer to hold the outgoing packet
	char buf[MAX_PACKET_SIZE];
	memset(buf, 0, MAX_PACKET_SIZE);

	// OS specific per-thread init
	if (send_run_init(st)) {
		return -1;
	}

	// MAC address length in characters
	char mac_buf[(ETHER_ADDR_LEN * 2) + (ETHER_ADDR_LEN - 1) + 1];
	char *p = mac_buf;
	for(int i=0; i < ETHER_ADDR_LEN; i++) {
		if (i == ETHER_ADDR_LEN-1) {
			snprintf(p, 3, "%.2x", zconf.hw_mac[i]);
			p += 2;
		} else {
			snprintf(p, 4, "%.2x:", zconf.hw_mac[i]);
			p += 3;
		}
	}
	log_debug("send", "source MAC address %s",
			mac_buf);
	void *probe_data;
	if (zconf.probe_module->thread_initialize) {
		zconf.probe_module->thread_initialize(buf, zconf.hw_mac, zconf.gw_mac,
					      zconf.target_port, &probe_data);
	}
	pthread_mutex_unlock(&send_mutex);

	// adaptive timing to hit target rate
	uint32_t count = 0;
	uint32_t last_count = count;
	double last_time = now();
	uint32_t delay = 0;
	int interval = 0;
	uint32_t max_targets = s->state.max_targets;
	volatile int vi;
	if (zconf.rate > 0) {
		// estimate initial rate
		delay = 10000;
		for (vi = delay; vi--; )
			;
		delay *= 1 / (now() - last_time) / (zconf.rate / zconf.senders);
		interval = (zconf.rate / zconf.senders) / 20;
		last_time = now();
	}
	uint32_t curr = shard_get_cur_ip(s);
	int attempts = zconf.num_retries + 1;
	uint32_t idx = 0;
	while (1) {
		// adaptive timing delay
		if (delay > 0) {
			count++;
			for (vi = delay; vi--; )
				;
			if (!interval || (count % interval == 0)) {
				double t = now();
				delay *= (double)(count - last_count)
					/ (t - last_time) / (zconf.rate / zconf.senders);
				if (delay < 1)
					delay = 1;
				last_count = count;
				last_time = t;
			}
		}
		if (zrecv.complete) {
			s->cb(s->id, s->arg);
			break;
		}
		if (s->state.sent >= max_targets) {
			s->cb(s->id, s->arg);
			break;
		}
		if (zconf.max_runtime && zconf.max_runtime <= now() - zsend.start) {
			s->cb(s->id, s->arg);
			break;
		}
		if (curr == 0) {
			s->cb(s->id, s->arg);
			break;
		}
		s->state.sent++;
		for (int i=0; i < zconf.packet_streams; i++) {
			uint32_t src_ip = get_src_ip(curr, i);

		  	uint32_t validation[VALIDATE_BYTES/sizeof(uint32_t)];
			validate_gen(src_ip, curr, (uint8_t *)validation);
			zconf.probe_module->make_packet(buf, src_ip, curr, validation, i, probe_data);

			if (zconf.dryrun) {
				lock_file(stdout);
				zconf.probe_module->print_packet(stdout, buf);
				unlock_file(stdout);
			} else {
				int length = zconf.probe_module->packet_length;
				void *contents = buf + zconf.send_ip_pkts*sizeof(struct ether_header);
				for (int i = 0; i < attempts; ++i) {
					int rc = send_packet(st, contents, length, idx);
					if (rc < 0) {
						struct in_addr addr;
						addr.s_addr = curr;
						log_debug("send", "send_packet failed for %s. %s",
								  inet_ntoa(addr), strerror(errno));
						s->state.failures++;
					} else {
						break;
					}
				}
				idx++;
				idx &= 0xFF;
			}
		}

		curr = shard_get_next_ip(s);
	}
	if (zconf.dryrun) {
		pthread_mutex_lock(&send_mutex);
		fflush(stdout);
		pthread_mutex_unlock(&send_mutex);
	}
	log_debug("send", "thread %hu finished", s->id);
	return EXIT_SUCCESS;
}
int git_filebuf_open(git_filebuf *file, const char *path, int flags)
{
	int compression;
	size_t path_len;

	/* opening an already open buffer is a programming error;
	 * assert that this never happens instead of returning
	 * an error code */
	assert(file && path && file->buffer == NULL);

	memset(file, 0x0, sizeof(git_filebuf));

	if (flags & GIT_FILEBUF_DO_NOT_BUFFER)
		file->do_not_buffer = true;

	file->buf_size = WRITE_BUFFER_SIZE;
	file->buf_pos = 0;
	file->fd = -1;
	file->last_error = BUFERR_OK;

	/* Allocate the main cache buffer */
	if (!file->do_not_buffer) {
		file->buffer = git__malloc(file->buf_size);
		GITERR_CHECK_ALLOC(file->buffer);
	}

	/* If we are hashing on-write, allocate a new hash context */
	if (flags & GIT_FILEBUF_HASH_CONTENTS) {
		file->digest = git_hash_new_ctx();
		GITERR_CHECK_ALLOC(file->digest);
	}

	compression = flags >> GIT_FILEBUF_DEFLATE_SHIFT;

	/* If we are deflating on-write, */
	if (compression != 0) {
		/* Initialize the ZLib stream */
		if (deflateInit(&file->zs, compression) != Z_OK) {
			giterr_set(GITERR_ZLIB, "Failed to initialize zlib");
			goto cleanup;
		}

		/* Allocate the Zlib cache buffer */
		file->z_buf = git__malloc(file->buf_size);
		GITERR_CHECK_ALLOC(file->z_buf);

		/* Never flush */
		file->flush_mode = Z_NO_FLUSH;
		file->write = &write_deflate;
	} else {
		file->write = &write_normal;
	}

	/* If we are writing to a temp file */
	if (flags & GIT_FILEBUF_TEMPORARY) {
		git_buf tmp_path = GIT_BUF_INIT;

		/* Open the file as temporary for locking */
		file->fd = git_futils_mktmp(&tmp_path, path);

		if (file->fd < 0) {
			git_buf_free(&tmp_path);
			goto cleanup;
		}
		file->fd_is_open = true;

		/* No original path */
		file->path_original = NULL;
		file->path_lock = git_buf_detach(&tmp_path);
		GITERR_CHECK_ALLOC(file->path_lock);
	} else {
		path_len = strlen(path);

		/* Save the original path of the file */
		file->path_original = git__strdup(path);
		GITERR_CHECK_ALLOC(file->path_original);

		/* create the locking path by appending ".lock" to the original */
		file->path_lock = git__malloc(path_len + GIT_FILELOCK_EXTLENGTH);
		GITERR_CHECK_ALLOC(file->path_lock);

		memcpy(file->path_lock, file->path_original, path_len);
		memcpy(file->path_lock + path_len, GIT_FILELOCK_EXTENSION, GIT_FILELOCK_EXTLENGTH);

		/* open the file for locking */
		if (lock_file(file, flags) < 0)
			goto cleanup;
	}

	return 0;

cleanup:
	git_filebuf_cleanup(file);
	return -1;
}
示例#25
0
int main(void)
{
	int fd, ret;
	pid_t pid;

	fd = open("passwd", O_RDWR);
	if (fd == -1) {
		perror("open");
		exit(1);
	}

	pid = fork();
	if (pid == -1) {
		perror("fork");
		close(fd);
		exit(1);
	} else if (pid == 0) {
		struct flock lock;
		lock.l_type = F_WRLCK;
		lock.l_whence = SEEK_SET;
		lock.l_start = 0;
		lock.l_len = 5;

		ret = fcntl(fd, F_GETLK, &lock);
		if (ret == -1) {
			perror("fcntl");
			exit(1);
		}

		if (lock.l_type == F_UNLCK) {
			ret = lock_file(fd, F_SETLK, F_WRLCK, 0, SEEK_SET, 5);
			if (ret == -1) {
				printf("pid=%d ""lock file failed!", getpid());
				exit(1);
			}
		} else {
			if (lock.l_type == F_RDLCK) {
				printf("old readlock!\n");
			} else if (lock.l_type == F_WRLCK) {
				printf("old writelock!\n");
			}
			exit(0);
		}
		printf("child lock sucess!\n");
		lseek(fd, 0, SEEK_SET);
		write(fd, "hello", 5);
		close(fd);
		exit(0);
	}

	if (pid > 0) {
#if 1
		ret = lock_file(fd, F_SETLK, F_RDLCK, 0, SEEK_SET, 5);
		if (ret == -1) {
			printf("pid=%d lock file failed", getpid());
			exit(1);
		}
#endif
		char buf[5];
		lseek(fd, 0, SEEK_SET);
		
		int cnt = read(fd, buf, 5);
		if (cnt == -1) {
			perror("read");
			exit(1);
		}
#if 1 
		ret = lock_file(fd, F_SETLK, F_UNLCK, 0, SEEK_SET, 5);
		if (ret == -1) {
			printf("unlock failed!\n");
			exit(1);
		}
#endif
		write(1, buf, cnt);
		write(1, "\n", 1);
		sleep(5);
		close(fd);
		exit(0);
	}
}
示例#26
0
文件: myssl.c 项目: captdeaf/pennmush
/** Initialize the SSL context.
 * \return pointer to SSL context object.
 */
SSL_CTX *
ssl_init(char *private_key_file, char *ca_file, char *ca_dir,
         int req_client_cert)
{
  const SSL_METHOD
    *meth; /* If this const gives you a warning, you're
              using an old version of OpenSSL. Walker, this means you! */
  /* uint8_t context[128]; */
  unsigned int reps = 1;
  pcg32_random_t rand_state;
  uint64_t seeds[2];
  bool seeded = false;

  if (!bio_err) {
    if (!SSL_library_init())
      return NULL;
    SSL_load_error_strings();
    /* Error write context */
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
  }

  lock_file(stderr);
  fputs("Seeding OpenSSL random number pool.\n", stderr);
  unlock_file(stderr);
  while (!RAND_status()) {
    /* At this point, a system with /dev/urandom or a EGD file in the usual
       places will have enough entropy. Otherwise, be lazy and use random
       numbers until it's satisfied. */
    uint32_t gibberish[8];
    int n;

    if (!seeded) {
      generate_seed(seeds);
      pcg32_srandom_r(&rand_state, seeds[0], seeds[1]);
      seeded = 1;
    }

    for (n = 0; n < 8; n++)
      gibberish[n] = pcg32_random_r(&rand_state);

    RAND_seed(gibberish, sizeof gibberish);

    reps += 1;
  }

  lock_file(stderr);
  fprintf(stderr, "Seeded after %u %s.\n", reps, reps > 1 ? "cycles" : "cycle");
  unlock_file(stderr);

  /* Set up SIGPIPE handler here? */

  /* Create context */
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  meth = TLS_server_method();
#else
  meth = SSLv23_server_method();
#endif
  ctx = SSL_CTX_new(meth);
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

  /* Load keys/certs */
  if (private_key_file && *private_key_file) {
    if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) {
      ssl_errordump("Unable to load server certificate - only anonymous "
                    "ciphers supported.");
    }
    if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) {
      ssl_errordump(
        "Unable to load private key - only anonymous ciphers supported.");
    }
  }

  /* Load trusted CAs */
  if ((ca_file && *ca_file) || (ca_dir && *ca_dir)) {
    if (!SSL_CTX_load_verify_locations(ctx,
                                       (ca_file && *ca_file) ? ca_file : NULL,
                                       (ca_dir && *ca_dir) ? ca_dir : NULL)) {
      ssl_errordump("Unable to load CA certificates");
    }
    {
      STACK_OF(X509_NAME) *certs = NULL;
      if (ca_file && *ca_file)
        certs = SSL_load_client_CA_file(ca_file);
      if (certs)
        SSL_CTX_set_client_CA_list(ctx, certs);

      if (req_client_cert)
        SSL_CTX_set_verify(ctx,
                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                           client_verify_callback);
      else
        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, client_verify_callback);
#if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
      SSL_CTX_set_verify_depth(ctx, 1);
#endif
    }
  }

  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL);
  SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
                          SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

  /* Set up DH key */
  {
    DH *dh;
    dh = get_dh2048();
    SSL_CTX_set_tmp_dh(ctx, dh);
    DH_free(dh);
  }

#ifdef NID_X9_62_prime256v1
  /* Set up ECDH key */
  {
    EC_KEY *ecdh = NULL;
    ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    SSL_CTX_set_tmp_ecdh(ctx, ecdh);
    EC_KEY_free(ecdh);
  }
#endif

  /* Set the cipher list to the usual default list, except that
   * we'll allow anonymous diffie-hellman, too.
   */
  SSL_CTX_set_cipher_list(ctx, "ALL:ECDH:ADH:!LOW:!MEDIUM:@STRENGTH");

  /* Set up session cache if we can */
  /*
     strncpy((char *) context, MUDNAME, 128);
     SSL_CTX_set_session_id_context(ctx, context, strlen(context));
   */

  return ctx;
}
示例#27
0
int lock_file_read(const int fd)
{
	return lock_file(fd, F_RDLCK);
}
示例#28
0
文件: myssl.c 项目: captdeaf/pennmush
static DH *
get_dh2048(void)
{
  static const uint8_t dh2048_p[] = {
    0x8C, 0x9A, 0x5A, 0x28, 0xBF, 0x13, 0x24, 0xC0, 0xD3, 0x7A, 0x73, 0xC3,
    0x87, 0x5B, 0x80, 0x81, 0xE8, 0xF3, 0x7B, 0xF6, 0xF7, 0x18, 0x71, 0xF9,
    0xBB, 0x5B, 0x88, 0x21, 0xAB, 0x63, 0xF6, 0x82, 0xA6, 0xEC, 0xD7, 0x04,
    0x25, 0xDC, 0x64, 0x75, 0x00, 0x49, 0x2C, 0x13, 0x04, 0x4F, 0xCF, 0xF9,
    0x06, 0xE0, 0x4D, 0x23, 0xB8, 0x7C, 0xD8, 0x29, 0x59, 0x6F, 0x69, 0xCC,
    0x41, 0x1F, 0x45, 0xF8, 0x25, 0xC8, 0x72, 0xF4, 0xC8, 0x37, 0x3C, 0x30,
    0xC2, 0x5A, 0xF3, 0x14, 0x43, 0x98, 0x4F, 0x99, 0x12, 0xBC, 0x68, 0x7E,
    0x20, 0x24, 0xAA, 0x8B, 0xBA, 0x87, 0x32, 0xBC, 0x4B, 0xF3, 0x16, 0x25,
    0xEE, 0xE5, 0xEB, 0x47, 0xED, 0xB2, 0x7D, 0x8F, 0x4F, 0xC8, 0xFB, 0x58,
    0x3D, 0x2E, 0xF6, 0x54, 0xF4, 0xDA, 0xD1, 0x88, 0x6A, 0xD8, 0xBC, 0x32,
    0xEC, 0xDA, 0xF1, 0xBC, 0xAF, 0x16, 0x90, 0xCD, 0xEE, 0x5F, 0x92, 0x0B,
    0xCE, 0xB9, 0x26, 0xCF, 0x18, 0xAE, 0x8C, 0x9B, 0x06, 0x0B, 0x83, 0x4D,
    0x99, 0x31, 0x98, 0x3B, 0x29, 0xE1, 0x16, 0x6A, 0xA4, 0x5E, 0xE8, 0x10,
    0x5F, 0x5B, 0x72, 0x3A, 0xA1, 0xD9, 0x89, 0x70, 0x61, 0xD9, 0xC2, 0x25,
    0x53, 0x5C, 0x44, 0x10, 0x27, 0xD7, 0xF2, 0x68, 0x75, 0x3F, 0xA3, 0xA7,
    0xCF, 0x02, 0x03, 0x49, 0xB4, 0xE4, 0xAF, 0x08, 0xEA, 0xAE, 0x97, 0x07,
    0x36, 0xC8, 0xD5, 0x24, 0xC6, 0x51, 0x8B, 0x91, 0x9A, 0x14, 0x91, 0x67,
    0x6A, 0xC0, 0xC3, 0x0E, 0x7C, 0xD8, 0x1F, 0xD2, 0x31, 0x07, 0x59, 0x5D,
    0x1D, 0xBD, 0x8E, 0xAE, 0xD7, 0x01, 0xBA, 0xDE, 0x0B, 0xDA, 0xA6, 0xBC,
    0x9A, 0xD1, 0x39, 0x59, 0x8F, 0xE5, 0x72, 0x65, 0x0F, 0x2A, 0x2D, 0x90,
    0x56, 0xE9, 0xDA, 0xF5, 0x4A, 0x26, 0xD3, 0xB3, 0x56, 0x19, 0x84, 0x00,
    0x3A, 0x11, 0x78, 0x83,
  };
  static const uint8_t dh2048_g[] = {
    0x02,
  };
  DH *dh;

  if ((dh = DH_new()) == NULL)
    return NULL;

#ifdef HAVE_DH_SET0_PQG
  BIGNUM *p, *g;
  p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
  if (!p) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 1!\n", stderr);
    unlock_file(stderr);
    DH_free(dh);
    return NULL;
  }

  g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
  if (!g) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 2!\n", stderr);
    unlock_file(stderr);
    BN_free(p);
    DH_free(dh);
    return NULL;
  }

  DH_set0_pqg(dh, p, NULL, g);
#else
  dh->p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
  if (!dh->p) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 1!\n", stderr);
    unlock_file(stderr);
    DH_free(dh);
    return NULL;
  }

  dh->g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
  if (!dh->g) {
    lock_file(stderr);
    fputs("Error in BN_bin2bn 2!\n", stderr);
    unlock_file(stderr);
    DH_free(dh);
    return NULL;
  }
#endif

  return dh;
}
 template <typename IdentifierT> static bool Remove(const IdentifierT id)
 {
     OSRMLockFile lock_file;
     boost::interprocess::xsi_key key(lock_file().string().c_str(), id);
     return Remove(key);
 }
示例#30
0
int
open_file(const char *file, int *can_write, const char *header)
{
	int fd;
	struct stat s;

	if (ensure_directories_exist(file, 0700))
		return -1;
	*can_write = 1;
	fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
	if (fd < 0) {
		if (errno == EROFS) {
			*can_write = 0;
			condlog(3, "Cannot open file [%s] read/write. "
				" trying readonly", file);
			fd = open(file, O_RDONLY);
			if (fd < 0) {
				condlog(0, "Cannot open file [%s] "
					"readonly : %s", file, strerror(errno));
				return -1;
			}
		}
		else {
			condlog(0, "Cannot open file [%s] : %s", file,
				strerror(errno));
			return -1;
		}
	}
	if (*can_write && lock_file(fd, file) < 0)
		goto fail;

	memset(&s, 0, sizeof(s));
	if (fstat(fd, &s) < 0){
		condlog(0, "Cannot stat file %s : %s", file, strerror(errno));
		goto fail;
	}
	if (s.st_size == 0) {
		if (*can_write == 0)
			goto fail;
		/* If file is empty, write the header */
		size_t len = strlen(header);
		if (write(fd, header, len) != len) {
			condlog(0,
				"Cannot write header to file %s : %s", file,
				strerror(errno));
			/* cleanup partially written header */
			if (ftruncate(fd, 0))
				condlog(0, "Cannot truncate header : %s",
					strerror(errno));
			goto fail;
		}
		fsync(fd);
		condlog(3, "Initialized new file [%s]", file);
	}

	return fd;

fail:
	close(fd);
	return -1;
}