Ejemplo n.º 1
0
/*
 * Set an error in a status-code option (from set_status_code).
 */
static int
set_error(struct lq6_state *lq, u_int16_t code, const char *message) {
	struct data_string d;
	int ret_val;

	memset(&d, 0, sizeof(d));
	d.len = sizeof(code) + strlen(message);
	if (!buffer_allocate(&d.buffer, d.len, MDL)) {
		log_fatal("set_error: no memory for status code.");
	}
	d.data = d.buffer->data;
	putUShort(d.buffer->data, code);
	memcpy(d.buffer->data + sizeof(code), message, d.len - sizeof(code));
	if (!save_option_buffer(&dhcpv6_universe, lq->reply_opts,
				d.buffer, (unsigned char *)d.data, d.len, 
				D6O_STATUS_CODE, 0)) {
		log_error("set_error: error saving status code.");
		ret_val = 0;
	} else {
		ret_val = 1;
	}
	data_string_forget(&d, MDL);
	return ret_val;
}
Ejemplo n.º 2
0
static int build_global_dns_packet(const char* domain) 
{	 
	qname_len = domain_to_qname(&qname, domain);
	dns_packet_len = sizeof(dns_header) + qname_len + sizeof(dns_question_tail);

	if (dns_packet_len > DNS_SEND_LEN) {
			log_fatal("dns", "DNS packet bigger (%d) than our limit (%d)", 
					dns_packet_len, DNS_SEND_LEN);
			return EXIT_FAILURE;
	}
	
	dns_packet = xmalloc(dns_packet_len);

	dns_header* dns_header_p = (dns_header*)dns_packet;
	char* qname_p = dns_packet + sizeof(dns_header);
	dns_question_tail* tail_p = (dns_question_tail*)(dns_packet + 
			sizeof(dns_header) + qname_len);

	// All other header fields should be 0. Except id, which we set per thread.
	
	// Please recurse as needed.
	dns_header_p->rd = 1; // Is one bit. Don't need htons
	
	// We have 1 question
	dns_header_p->qdcount = htons(1);

	memcpy(qname_p, qname, qname_len);

	// Set the qtype to what we passed from args
	tail_p->qtype = htons(qtype);

	// Set the qclass to The Internet (TM) (R) (I hope you're happy now Zakir)
	tail_p->qclass = htons(0x01); // MAGIC NUMBER. Let's be honest. This is only ever 1

	return EXIT_SUCCESS;
}
Ejemplo n.º 3
0
/****************
 * Flush the cache.  This cannot be used while in a transaction.
 */
int
tdbio_sync()
{
    CACHE_CTRL r;
    int did_lock = 0;

    if( db_fd == -1 )
        open_db();
    if( in_transaction )
        log_bug("tdbio: syncing while in transaction\n");

    if( !cache_is_dirty )
        return 0;

    if( !is_locked ) {
        if( make_dotlock( lockhandle, -1 ) )
            log_fatal("can't acquire lock - giving up\n");
        else
            is_locked = 1;
        did_lock = 1;
    }
    for( r = cache_list; r; r = r->next ) {
        if( r->flags.used && r->flags.dirty ) {
            int rc = write_cache_item( r );
            if( rc )
                return rc;
        }
    }
    cache_is_dirty = 0;
    if( did_lock && !opt.lock_once ) {
        if( !release_dotlock( lockhandle ) )
            is_locked = 0;
    }

    return 0;
}
Ejemplo n.º 4
0
int
tdbio_db_matches_options()
{
  static int yes_no = -1;

  if( yes_no == -1 )
    {
      TRUSTREC vr;
      int rc;

      rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
      if( rc )
	log_fatal( _("%s: error reading version record: %s\n"),
		   db_name, g10_errstr(rc) );

      yes_no = vr.r.ver.marginals == opt.marginals_needed
	&& vr.r.ver.completes == opt.completes_needed
	&& vr.r.ver.cert_depth == opt.max_cert_depth
	&& vr.r.ver.trust_model == opt.trust_model
	&& vr.r.ver.min_cert_level == opt.min_cert_level;
    }

  return yes_no;
}
Ejemplo n.º 5
0
int
_gcry_rndw32_gather_random (void (*add)(const void*, size_t,
                                        enum random_origins),
                            enum random_origins origin,
                            size_t length, int level )
{
  static int is_initialized;

  if (!level)
    return 0;

  /* We don't differentiate between level 1 and 2 here because there
     is no internal entropy pool as a scary resource.  It may all work
     slower, but because our entropy source will never block but
     deliver some not easy to measure entropy, we assume level 2.  */

  if (!is_initialized)
    {
      OSVERSIONINFO osvi = { sizeof( osvi ) };

      GetVersionEx( &osvi );
      if (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)
        log_fatal ("can only run on a Windows NT platform\n" );
      system_is_w2000 = (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0);
      init_system_rng ();
      is_initialized = 1;
    }

  if (debug_me)
    log_debug ("rndw32#gather_random: ori=%d len=%u lvl=%d\n",
               origin, (unsigned int)length, level );

  slow_gatherer (add, origin);

  return 0;
}
Ejemplo n.º 6
0
/* Basic initialization which is required to initialize mutexes and
   such.  It does not run a full initialization so that the filling of
   the random pool can be delayed until it is actually needed.  We
   assume that this function is used before any concurrent access
   happens. */
static void
initialize_basics(void)
{
  static int initialized = 0;

  if (!initialized)
    {
      initialized = 1;

#ifdef USE_RANDOM_DAEMON
      _gcry_daemon_initialize_basics ();
#endif /*USE_RANDOM_DAEMON*/

      /* Make sure that we are still using the values we have
         traditionally used for the random levels.  */
      gcry_assert (GCRY_WEAK_RANDOM == 0
                   && GCRY_STRONG_RANDOM == 1
                   && GCRY_VERY_STRONG_RANDOM == 2);

      int err =  gpgrt_lock_init(&pool_lock);
      if (err)
        log_fatal ("failed to initialize the pool lock: %s\n", gpg_strerror (err));
    }
}
Ejemplo n.º 7
0
/* Compute the fingerprint of the certificate CERT and put it into
   the 20 bytes large buffer DIGEST.  Return address of this buffer.  */
unsigned char *
cert_compute_fpr (ksba_cert_t cert, unsigned char *digest)
{
  gpg_error_t err;
  gcry_md_hd_t md;

  err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
  if (err)
    log_fatal ("gcry_md_open failed: %s\n", gpg_strerror (err));

  err = ksba_cert_hash (cert, 0, HASH_FNC, md);
  if (err)
    {
      log_error ("oops: ksba_cert_hash failed: %s\n", gpg_strerror (err));
      memset (digest, 0xff, 20); /* Use a dummy value. */
    }
  else
    {
      gcry_md_final (md);
      memcpy (digest, gcry_md_read (md, GCRY_MD_SHA1), 20);
    }
  gcry_md_close (md);
  return digest;
}
static int
do_compress(compress_filter_context_t *zfx, bz_stream *bzs, int flush, IOBUF a)
{
  int zrc;
  unsigned n;

  do
    {
      bzs->next_out = zfx->outbuf;
      bzs->avail_out = zfx->outbufsize;
      if( DBG_FILTER )
	log_debug("enter bzCompress: avail_in=%u, avail_out=%u, flush=%d\n",
		  (unsigned)bzs->avail_in, (unsigned)bzs->avail_out, flush );
      zrc = BZ2_bzCompress( bzs, flush );
      if( zrc == BZ_STREAM_END && flush == BZ_FINISH )
	;
      else if( zrc != BZ_RUN_OK && zrc != BZ_FINISH_OK )
	log_fatal("bz2lib deflate problem: rc=%d\n", zrc );

      n = zfx->outbufsize - bzs->avail_out;
      if( DBG_FILTER )
	log_debug("leave bzCompress:"
		  " avail_in=%u, avail_out=%u, n=%u, zrc=%d\n",
		  (unsigned)bzs->avail_in, (unsigned)bzs->avail_out,
		  (unsigned)n, zrc );

      if( iobuf_write( a, zfx->outbuf, n ) )
	{
	  log_debug("bzCompress: iobuf_write failed\n");
	  return G10ERR_WRITE_FILE;
	}
    }
  while( bzs->avail_in || (flush == BZ_FINISH && zrc != BZ_STREAM_END) );

  return 0;
}
Ejemplo n.º 9
0
void
register_eventhandler(struct eventqueue **queue, void (*handler)(void *))
{
	struct eventqueue *t, *q;

	/* traverse to end of list */
	t = NULL;
	for (q = *queue ; q ; q = q->next) {
		if (q->handler == handler)
			return; /* handler already registered */
		t = q;
	}
		
	q = ((struct eventqueue *)dmalloc(sizeof(struct eventqueue), MDL));
	if (!q)
		log_fatal("register_eventhandler: no memory!");
	memset(q, 0, sizeof *q);
	if (t)
		t->next = q;
	else 
		*queue	= q;
	q->handler = handler;
	return;
}
Ejemplo n.º 10
0
int move_range(const std::string &min_key, const std::string &max_key, int limit, std::string *moved_max_key){
	// get key range
	std::vector<std::string> keys;
	ssdb::Status s;
	s = src->keys(min_key, max_key, limit, &keys);
	if(!s.ok()){
		log_error("response error: %s", s.code().c_str());
		return -1;
	}
	if(keys.empty()){
		return 0;
	}
	if(moved_max_key){
		*moved_max_key = keys[keys.size() - 1];

		// lock key range
		log_info("lock range %s", KeyRange(min_key, *moved_max_key).str().c_str());
		const std::vector<std::string>* resp;
		resp = src->request("set_kv_range", *moved_max_key, max_key);
		if(!resp || resp->empty() || resp->at(0) != "ok"){
			log_error("src server set_kv_range error!");
			return -1;
		}
	}

	// move key range
	for(int i=0; i<(int)keys.size(); i++){
		const std::string &key = keys[i];
		if(move_key(key) == -1){
			log_fatal("move key %s error! %s", key.c_str(), s.code().c_str());
			exit(1);   
		}
	}
	
	return (int)keys.size();
}
Ejemplo n.º 11
0
/*!
 *
 * \brief Find a lease in the lease chain and then remove it
 * If we can't find the lease on the given lease chain it's a fatal error.
 *
 * \param lc The lease chain to update
 * \param lp The lease to remove
 */
void
lc_unlink_lease(struct leasechain *lc, struct lease *lp) {
#if defined (DEBUG_BINARY_LEASES)
	log_debug("LC unlink lease %s:%d", MDL);

	INSIST(lc != NULL);
	INSIST(lc->list != NULL);
	INSIST(lp != NULL );
	INSIST(lp->lc != NULL );
	INSIST(lp->lc == lc );
#endif

	size_t pos = lc_binary_search_lease(lc, lp, 0, lc->nelem-1);
	if (pos == SIZE_MAX) {
		/* fatal, lease not found in leasechain */
		log_fatal("Lease with binding state %s not on its queue.",
			  (lp->binding_state < 1 ||
			   lp->binding_state > FTS_LAST)
			  ? "unknown"
			  : binding_state_names[lp->binding_state - 1]);
	}

	lc_unlink_lease_pos(lc, pos);
}
Ejemplo n.º 12
0
void gdmaps_test_lookup_check(const unsigned tnum, const gdmaps_t* gdmaps, const char* map_name, const char* addr_txt, const char* dclist_cmp, const unsigned scope_cmp) {
    dmn_assert(gdmaps);
    dmn_assert(map_name);
    dmn_assert(addr_txt);
    dmn_assert(dclist_cmp);

    log_info("Subtest %u starting", tnum);

    int map_idx = gdmaps_name2idx(gdmaps, map_name);
    if(map_idx < 0)
        log_fatal("Subtest %u failed: Map name '%s' not found in configuration", tnum, map_name);

    client_info_t cinfo;
    cinfo.edns_client_mask = 150U;
    unsigned scope = 175U;

    const int addr_err = gdnsd_anysin_getaddrinfo(addr_txt, NULL, &cinfo.edns_client);
    if(addr_err)
        log_fatal("Subtest %u failed: Cannot parse address '%s': %s", tnum, addr_txt, gai_strerror(addr_err));

    // To void gdmaps fallback pitfalls
    memcpy(&cinfo.dns_source, &cinfo.edns_client, sizeof(anysin_t));
    const uint8_t* dclist = gdmaps_lookup(gdmaps, map_idx, &cinfo, &scope);

    // w/ edns_client_mask set, scope_mask should *always* be set by gdmaps_lookup();
    // (and regardless, dclist should also always be set and contain something)
    if(!dclist)
        log_fatal("Subtest %u failed: gdmaps_lookup(%s, %s) returned NULL", tnum, map_name, addr_txt);
    if(scope == 175U)
        log_fatal("Subtest %u failed: gdmaps_lookup(%s, %s) failed to set the scope mask", tnum, map_name, addr_txt);

    if(strcmp((const char*)dclist, dclist_cmp))
        log_fatal("Subtest %u failed: Wanted dclist %s, got dclist %s", tnum,
            gdmaps_logf_dclist(gdmaps, map_idx, (const uint8_t*)dclist_cmp),
            gdmaps_logf_dclist(gdmaps, map_idx, dclist));

    if(scope != scope_cmp)
        log_fatal("Subtest %u failed: Wanted scope mask %u, got %u", tnum, scope_cmp, scope);
}
Ejemplo n.º 13
0
/****************
 * Decrypt the data, specified by ED with the key DEK.
 */
int
decrypt_data( void *procctx, PKT_encrypted *ed, DEK *dek )
{
  decode_filter_ctx_t dfx;
  byte *p;
  int rc=0, c, i;
  byte temp[32];
  unsigned blocksize;
  unsigned nprefix;
  
  dfx = xtrycalloc (1, sizeof *dfx);
  if (!dfx)
    return gpg_error_from_syserror ();
  dfx->refcount = 1;

  if ( opt.verbose && !dek->algo_info_printed )
    {
      if (!openpgp_cipher_test_algo (dek->algo))
        log_info (_("%s encrypted data\n"), 
                  openpgp_cipher_algo_name (dek->algo));
      else
        log_info (_("encrypted with unknown algorithm %d\n"), dek->algo );
      dek->algo_info_printed = 1;
    }
  rc = openpgp_cipher_test_algo (dek->algo);
  if (rc)
    goto leave;
  blocksize = openpgp_cipher_get_algo_blklen (dek->algo);
  if ( !blocksize || blocksize > 16 )
    log_fatal ("unsupported blocksize %u\n", blocksize );
  nprefix = blocksize;
  if ( ed->len && ed->len < (nprefix+2) )
    BUG();

  if ( ed->mdc_method ) 
    {
      if (gcry_md_open (&dfx->mdc_hash, ed->mdc_method, 0 ))
        BUG ();
      if ( DBG_HASHING )
        gcry_md_start_debug (dfx->mdc_hash, "checkmdc");
    }

  rc = openpgp_cipher_open (&dfx->cipher_hd, dek->algo,
			    GCRY_CIPHER_MODE_CFB,
			    (GCRY_CIPHER_SECURE
			     | ((ed->mdc_method || dek->algo >= 100)?
				0 : GCRY_CIPHER_ENABLE_SYNC)));
  if (rc)
    {
      /* We should never get an error here cause we already checked
       * that the algorithm is available.  */
      BUG();
    }


  /* log_hexdump( "thekey", dek->key, dek->keylen );*/
  rc = gcry_cipher_setkey (dfx->cipher_hd, dek->key, dek->keylen);
  if ( gpg_err_code (rc) == GPG_ERR_WEAK_KEY )
    {
      log_info(_("WARNING: message was encrypted with"
                 " a weak key in the symmetric cipher.\n"));
      rc=0;
    }
  else if( rc )
    {
      log_error("key setup failed: %s\n", g10_errstr(rc) );
      goto leave;
    }

  if (!ed->buf) 
    {
      log_error(_("problem handling encrypted packet\n"));
      goto leave;
    }

  gcry_cipher_setiv (dfx->cipher_hd, NULL, 0);

  if ( ed->len )
    {
      for (i=0; i < (nprefix+2) && ed->len; i++, ed->len-- ) 
        {
          if ( (c=iobuf_get(ed->buf)) == -1 )
            break;
          else
            temp[i] = c;
        }
    }
  else 
    {
      for (i=0; i < (nprefix+2); i++ )
        if ( (c=iobuf_get(ed->buf)) == -1 )
          break;
        else
          temp[i] = c;
    }
  
  gcry_cipher_decrypt (dfx->cipher_hd, temp, nprefix+2, NULL, 0);
  gcry_cipher_sync (dfx->cipher_hd);
  p = temp;
  /* log_hexdump( "prefix", temp, nprefix+2 ); */
  if (dek->symmetric
      && (p[nprefix-2] != p[nprefix] || p[nprefix-1] != p[nprefix+1]) )
    {
      rc = gpg_error (GPG_ERR_BAD_KEY);
      goto leave;
    }
  
  if ( dfx->mdc_hash )
    gcry_md_write (dfx->mdc_hash, temp, nprefix+2);

  dfx->refcount++;
  if ( ed->mdc_method )
    iobuf_push_filter ( ed->buf, mdc_decode_filter, dfx );
  else
    iobuf_push_filter ( ed->buf, decode_filter, dfx );

  proc_packets ( procctx, ed->buf );
  ed->buf = NULL;
  if ( ed->mdc_method && dfx->eof_seen == 2 )
    rc = gpg_error (GPG_ERR_INV_PACKET);
  else if ( ed->mdc_method )
    { 
      /* We used to let parse-packet.c handle the MDC packet but this
         turned out to be a problem with compressed packets: With old
         style packets there is no length information available and
         the decompressor uses an implicit end.  However we can't know
         this implicit end beforehand (:-) and thus may feed the
         decompressor with more bytes than actually needed.  It would
         be possible to unread the extra bytes but due to our weird
         iobuf system any unread is non reliable due to filters
         already popped off.  The easy and sane solution is to care
         about the MDC packet only here and never pass it to the
         packet parser.  Fortunatley the OpenPGP spec requires a
         strict format for the MDC packet so that we know that 22
         bytes are appended.  */
      int datalen = gcry_md_get_algo_dlen (ed->mdc_method);

      assert (dfx->cipher_hd);
      assert (dfx->mdc_hash);
      gcry_cipher_decrypt (dfx->cipher_hd, dfx->defer, 22, NULL, 0);
      gcry_md_write (dfx->mdc_hash, dfx->defer, 2);
      gcry_md_final (dfx->mdc_hash);

      if (dfx->defer[0] != '\xd3' || dfx->defer[1] != '\x14' )
        {
          log_error("mdc_packet with invalid encoding\n");
          rc = gpg_error (GPG_ERR_INV_PACKET);
        }
      else if (datalen != 20
               || memcmp (gcry_md_read (dfx->mdc_hash, 0),
                          dfx->defer+2,datalen ))
        rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
      /* log_printhex("MDC message:", dfx->defer, 22); */
      /* log_printhex("MDC calc:", gcry_md_read (dfx->mdc_hash,0), datalen); */
    }
  
  
 leave:
  release_dfx_context (dfx);
  return rc;
}
Ejemplo n.º 14
0
// Grab these bytes, and close the connection.
// Even if we don't need to read any bytes,
// we have to have this so that libevent thinks we have
// a read event, so that it can timeout TCP connects
// (as a read timeout)
void read_cb(struct bufferevent *bev, void *arg)
{
	struct evbuffer *in = bufferevent_get_input(bev);
	struct state *st = arg;
	size_t len = evbuffer_get_length(in);
	struct in_addr addr;
	addr.s_addr = st->src_ip;

	log_debug("forge-socket", "read_cb for %s", inet_ntoa(addr));

	if (len > MAX_BANNER_LEN) {
		len = MAX_BANNER_LEN;
	}

	if (len > 0) {
		// Grab the banner	
		unsigned int i;
		unsigned char *buf = malloc(len+1);

		st->state = RECEIVED;

		if (!buf) {
			log_fatal("forge-socket", "cannot alloc %d byte buf", len+1);
			return;
		}
		evbuffer_remove(in, buf, len);
		
		printf("%s ", inet_ntoa(addr));

		if (st->conf->format == FORMAT_ASCII) {
			// Ascii
			buf[len] = '\0';
			printf("%s\n", buf);
		} else if (st->conf->format == FORMAT_HEX) {
			// Hex output
			for (i=0; i<len; i++) {
				printf("%02x", buf[i]);
			}
			printf("\n");
		} else if (st->conf->format == FORMAT_BASE64) {
			// Base64
			int i=0;
			char out[4] = {0,0,0,0};
			while (i < len) {
				uint32_t value = 0;
				value += (i < len) ? buf[i++] << 16 : 0; 	
				value += (i < len) ? buf[i++] <<  8 : 0;
				value += (i < len) ? buf[i++]       : 0;
				out[0] = BASE64_ALPHABET[(value >> 18) & 0x3F];
				out[1] = BASE64_ALPHABET[(value >> 12) & 0x3F];                                                                           
				out[2] = BASE64_ALPHABET[(value >>  6) & 0x3F];
				out[3] = BASE64_ALPHABET[(value      ) & 0x3F];
				if (i < len) {
					printf("%c%c%c%c", out[0], out[1], out[2], out[3]);
				}
			}
			if (len > 0) {
				switch (len % 3) {
				case 1:
					out[2] = '=';
				case 2:
					out[3] = '=';
				default:
					break;
				}
				printf("%c%c%c%c\n", out[0], out[1], out[2], out[3]);
			}
		}
Ejemplo n.º 15
0
static gcry_mpi_t
gen_prime (unsigned int nbits, int secret, int randomlevel, 
           int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg)
{
  gcry_mpi_t prime, ptest, pminus1, val_2, val_3, result;
  int i;
  unsigned int x, step;
  unsigned int count1, count2;
  int *mods;
  
/*   if (  DBG_CIPHER ) */
/*     log_debug ("generate a prime of %u bits ", nbits ); */

  if (nbits < 16)
    log_fatal ("can't generate a prime with less than %d bits\n", 16);

  mods = gcry_xmalloc( no_of_small_prime_numbers * sizeof *mods );
  /* Make nbits fit into gcry_mpi_t implementation. */
  val_2  = mpi_alloc_set_ui( 2 );
  val_3 = mpi_alloc_set_ui( 3);
  prime  = secret? gcry_mpi_snew ( nbits ): gcry_mpi_new ( nbits );
  result = mpi_alloc_like( prime );
  pminus1= mpi_alloc_like( prime );
  ptest  = mpi_alloc_like( prime );
  count1 = count2 = 0;
  for (;;)
    {  /* try forvever */
      int dotcount=0;
      
      /* generate a random number */
      gcry_mpi_randomize( prime, nbits, randomlevel );
      
      /* Set high order bit to 1, set low order bit to 1.  If we are
         generating a secret prime we are most probably doing that
         for RSA, to make sure that the modulus does have the
         requested key size we set the 2 high order bits. */
      mpi_set_highbit (prime, nbits-1);
      if (secret)
        mpi_set_bit (prime, nbits-2);
      mpi_set_bit(prime, 0);
      
      /* Calculate all remainders. */
      for (i=0; (x = small_prime_numbers[i]); i++ )
        mods[i] = mpi_fdiv_r_ui(NULL, prime, x);
      
      /* Now try some primes starting with prime. */
      for(step=0; step < 20000; step += 2 ) 
        {
          /* Check against all the small primes we have in mods. */
          count1++;
          for (i=0; (x = small_prime_numbers[i]); i++ ) 
            {
              while ( mods[i] + step >= x )
                mods[i] -= x;
              if ( !(mods[i] + step) )
                break;
	    }
          if ( x )
            continue;   /* Found a multiple of an already known prime. */
          
          mpi_add_ui( ptest, prime, step );

          /* Do a fast Fermat test now. */
          count2++;
          mpi_sub_ui( pminus1, ptest, 1);
          gcry_mpi_powm( result, val_2, pminus1, ptest );
          if ( !mpi_cmp_ui( result, 1 ) )
            { 
              /* Not composite, perform stronger tests */
              if (is_prime(ptest, 5, &count2 ))
                {
                  if (!mpi_test_bit( ptest, nbits-1-secret ))
                    {
                      progress('\n');
                      log_debug ("overflow in prime generation\n");
                      break; /* Stop loop, continue with a new prime. */
                    }

                  if (extra_check && extra_check (extra_check_arg, ptest))
                    { 
                      /* The extra check told us that this prime is
                         not of the caller's taste. */
                      progress ('/');
                    }
                  else
                    { 
                      /* Got it. */
                      mpi_free(val_2);
                      mpi_free(val_3);
                      mpi_free(result);
                      mpi_free(pminus1);
                      mpi_free(prime);
                      gcry_free(mods);
                      return ptest; 
                    }
                }
	    }
          if (++dotcount == 10 )
            {
              progress('.');
              dotcount = 0;
	    }
	}
      progress(':'); /* restart with a new random value */
    }
}
Ejemplo n.º 16
0
void initialize_common_option_spaces()
{
	unsigned code;
	int i;

	/* The 'universes' table is dynamically grown to contain
	 * universe as they're configured - except during startup.
	 * Since we know how many we put down in .c files, we can
	 * allocate a more-than-right-sized buffer now, leaving some
	 * space for user-configured option spaces.
	 *
	 * 1: dhcp_universe (dhcpv4 options)
	 * 2: nwip_universe (dhcpv4 NWIP option)
	 * 3: fqdn_universe (dhcpv4 fqdn option - reusable for v6)
	 * 4: vendor_class_universe (VIVCO)
	 * 5: vendor_universe (VIVSO)
	 * 6: isc_universe (dhcpv4 isc config space)
	 * 7: dhcpv6_universe (dhcpv6 options)
	 * 8: vsio_universe (DHCPv6 Vendor-Identified space)
	 * 9: isc6_universe (ISC's Vendor universe in DHCPv6 VSIO)
	 * 10: fqdn6_universe (dhcpv6 fqdn option shill to v4)
	 * 11: agent_universe (dhcpv4 relay agent - see server/stables.c)
	 * 12: server_universe (server's config, see server/stables.c)
	 * 13: user-config
	 * 14: more user-config
	 * 15: more user-config
	 * 16: more user-config
	 */
	universe_max = 16;
	i = universe_max * sizeof(struct universe *);
	if (i <= 0)
		log_fatal("Ludicrous initial size option space table.");
	universes = dmalloc(i, MDL);
	if (universes == NULL)
		log_fatal("Can't allocate option space table.");
	memset(universes, 0, i);

	/* Set up the DHCP option universe... */
	dhcp_universe.name = "dhcp";
	dhcp_universe.concat_duplicates = 1;
	dhcp_universe.lookup_func = lookup_hashed_option;
	dhcp_universe.option_state_dereference =
		hashed_option_state_dereference;
	dhcp_universe.save_func = save_hashed_option;
	dhcp_universe.delete_func = delete_hashed_option;
	dhcp_universe.encapsulate = hashed_option_space_encapsulate;
	dhcp_universe.foreach = hashed_option_space_foreach;
	dhcp_universe.decode = parse_option_buffer;
	dhcp_universe.length_size = 1;
	dhcp_universe.tag_size = 1;
	dhcp_universe.get_tag = getUChar;
	dhcp_universe.store_tag = putUChar;
	dhcp_universe.get_length = getUChar;
	dhcp_universe.store_length = putUChar;
	dhcp_universe.site_code_min = 0;
	dhcp_universe.end = DHO_END;
	dhcp_universe.index = universe_count++;
	universes [dhcp_universe.index] = &dhcp_universe;
	if (!option_name_new_hash(&dhcp_universe.name_hash,
				  BYTE_NAME_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&dhcp_universe.code_hash,
				  BYTE_CODE_HASH_SIZE, MDL))
		log_fatal ("Can't allocate dhcp option hash table.");
	for (i = 0 ; dhcp_options[i].name ; i++) {
		option_code_hash_add(dhcp_universe.code_hash,
				     &dhcp_options[i].code, 0,
				     &dhcp_options[i], MDL);
		option_name_hash_add(dhcp_universe.name_hash,
				     dhcp_options [i].name, 0,
				     &dhcp_options [i], MDL);
	}
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("DHCP name hash: %s",
		 option_name_hash_report(dhcp_universe.name_hash));
	log_info("DHCP code hash: %s",
		 option_code_hash_report(dhcp_universe.code_hash));
#endif

	/* Set up the Novell option universe (for option 63)... */
	nwip_universe.name = "nwip";
	nwip_universe.concat_duplicates = 0; /* XXX: reference? */
	nwip_universe.lookup_func = lookup_linked_option;
	nwip_universe.option_state_dereference =
		linked_option_state_dereference;
	nwip_universe.save_func = save_linked_option;
	nwip_universe.delete_func = delete_linked_option;
	nwip_universe.encapsulate = nwip_option_space_encapsulate;
	nwip_universe.foreach = linked_option_space_foreach;
	nwip_universe.decode = parse_option_buffer;
	nwip_universe.length_size = 1;
	nwip_universe.tag_size = 1;
	nwip_universe.get_tag = getUChar;
	nwip_universe.store_tag = putUChar;
	nwip_universe.get_length = getUChar;
	nwip_universe.store_length = putUChar;
	nwip_universe.site_code_min = 0;
	nwip_universe.end = 0;
	code = DHO_NWIP_SUBOPTIONS;
	nwip_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&nwip_universe.enc_opt,
				     dhcp_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find NWIP parent option (%s:%d).", MDL);
	nwip_universe.index = universe_count++;
	universes [nwip_universe.index] = &nwip_universe;
	if (!option_name_new_hash(&nwip_universe.name_hash,
				  NWIP_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&nwip_universe.code_hash,
				  NWIP_HASH_SIZE, MDL))
		log_fatal ("Can't allocate nwip option hash table.");
	for (i = 0 ; nwip_options[i].name ; i++) {
		option_code_hash_add(nwip_universe.code_hash,
				     &nwip_options[i].code, 0,
				     &nwip_options[i], MDL);
		option_name_hash_add(nwip_universe.name_hash,
				     nwip_options[i].name, 0,
				     &nwip_options[i], MDL);
	}
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("NWIP name hash: %s",
		 option_name_hash_report(nwip_universe.name_hash));
	log_info("NWIP code hash: %s",
		 option_code_hash_report(nwip_universe.code_hash));
#endif

	/* Set up the FQDN option universe... */
	fqdn_universe.name = "fqdn";
	fqdn_universe.concat_duplicates = 0;
	fqdn_universe.lookup_func = lookup_linked_option;
	fqdn_universe.option_state_dereference =
		linked_option_state_dereference;
	fqdn_universe.save_func = save_linked_option;
	fqdn_universe.delete_func = delete_linked_option;
	fqdn_universe.encapsulate = fqdn_option_space_encapsulate;
	fqdn_universe.foreach = linked_option_space_foreach;
	fqdn_universe.decode = fqdn_universe_decode;
	fqdn_universe.length_size = 1;
	fqdn_universe.tag_size = 1;
	fqdn_universe.get_tag = getUChar;
	fqdn_universe.store_tag = putUChar;
	fqdn_universe.get_length = getUChar;
	fqdn_universe.store_length = putUChar;
	fqdn_universe.site_code_min = 0;
	fqdn_universe.end = 0;
	fqdn_universe.index = universe_count++;
	code = DHO_FQDN;
	fqdn_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&fqdn_universe.enc_opt,
				     dhcp_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find FQDN parent option (%s:%d).", MDL);
	universes [fqdn_universe.index] = &fqdn_universe;
	if (!option_name_new_hash(&fqdn_universe.name_hash,
				  FQDN_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&fqdn_universe.code_hash,
				  FQDN_HASH_SIZE, MDL))
		log_fatal ("Can't allocate fqdn option hash table.");
	for (i = 0 ; fqdn_options[i].name ; i++) {
		option_code_hash_add(fqdn_universe.code_hash,
				     &fqdn_options[i].code, 0,
				     &fqdn_options[i], MDL);
		option_name_hash_add(fqdn_universe.name_hash,
				     fqdn_options[i].name, 0,
				     &fqdn_options[i], MDL);
	}
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("FQDN name hash: %s",
		 option_name_hash_report(fqdn_universe.name_hash));
	log_info("FQDN code hash: %s",
		 option_code_hash_report(fqdn_universe.code_hash));
#endif

        /* Set up the Vendor Identified Vendor Class options (for option
	 * 125)...
	 */
        vendor_class_universe.name = "vendor-class";
	vendor_class_universe.concat_duplicates = 0; /* XXX: reference? */
        vendor_class_universe.lookup_func = lookup_hashed_option;
        vendor_class_universe.option_state_dereference =
                hashed_option_state_dereference;
        vendor_class_universe.save_func = save_hashed_option;
        vendor_class_universe.delete_func = delete_hashed_option;
        vendor_class_universe.encapsulate = hashed_option_space_encapsulate;
        vendor_class_universe.foreach = hashed_option_space_foreach;
        vendor_class_universe.decode = parse_option_buffer;
        vendor_class_universe.length_size = 1;
        vendor_class_universe.tag_size = 4;
	vendor_class_universe.get_tag = getULong;
        vendor_class_universe.store_tag = putULong;
	vendor_class_universe.get_length = getUChar;
        vendor_class_universe.store_length = putUChar;
	vendor_class_universe.site_code_min = 0;
	vendor_class_universe.end = 0;
	code = DHO_VIVCO_SUBOPTIONS;
	vendor_class_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&vendor_class_universe.enc_opt,
				     dhcp_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find VIVCO parent option (%s:%d).", MDL);
        vendor_class_universe.index = universe_count++;
        universes[vendor_class_universe.index] = &vendor_class_universe;
        if (!option_name_new_hash(&vendor_class_universe.name_hash,
				  VIVCO_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&vendor_class_universe.code_hash,
				  VIVCO_HASH_SIZE, MDL))
                log_fatal("Can't allocate Vendor Identified Vendor Class "
			  "option hash table.");
        for (i = 0 ; vendor_class_options[i].name ; i++) {
		option_code_hash_add(vendor_class_universe.code_hash,
				     &vendor_class_options[i].code, 0,
				     &vendor_class_options[i], MDL);
                option_name_hash_add(vendor_class_universe.name_hash,
                                     vendor_class_options[i].name, 0,
                                     &vendor_class_options[i], MDL);
        }
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("VIVCO name hash: %s",
		 option_name_hash_report(vendor_class_universe.name_hash));
	log_info("VIVCO code hash: %s",
		 option_code_hash_report(vendor_class_universe.code_hash));
#endif

        /* Set up the Vendor Identified Vendor Sub-options (option 126)... */
        vendor_universe.name = "vendor";
	vendor_universe.concat_duplicates = 0; /* XXX: reference? */
        vendor_universe.lookup_func = lookup_hashed_option;
        vendor_universe.option_state_dereference =
                hashed_option_state_dereference;
        vendor_universe.save_func = save_hashed_option;
        vendor_universe.delete_func = delete_hashed_option;
        vendor_universe.encapsulate = hashed_option_space_encapsulate;
        vendor_universe.foreach = hashed_option_space_foreach;
        vendor_universe.decode = parse_option_buffer;
        vendor_universe.length_size = 1;
        vendor_universe.tag_size = 4;
	vendor_universe.get_tag = getULong;
        vendor_universe.store_tag = putULong;
	vendor_universe.get_length = getUChar;
        vendor_universe.store_length = putUChar;
	vendor_universe.site_code_min = 0;
	vendor_universe.end = 0;
	code = DHO_VIVSO_SUBOPTIONS;
	vendor_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&vendor_universe.enc_opt,
				     dhcp_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find VIVSO parent option (%s:%d).", MDL);
        vendor_universe.index = universe_count++;
        universes[vendor_universe.index] = &vendor_universe;
        if (!option_name_new_hash(&vendor_universe.name_hash,
				  VIVSO_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&vendor_universe.code_hash,
				  VIVSO_HASH_SIZE, MDL))
                log_fatal("Can't allocate Vendor Identified Vendor Sub-"
			  "options hash table.");
        for (i = 0 ; vendor_options[i].name ; i++) {
                option_code_hash_add(vendor_universe.code_hash,
				     &vendor_options[i].code, 0,
				     &vendor_options[i], MDL);
                option_name_hash_add(vendor_universe.name_hash,
				     vendor_options[i].name, 0,
				     &vendor_options[i], MDL);
        }
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("VIVSO name hash: %s",
		 option_name_hash_report(vendor_universe.name_hash));
	log_info("VIVSO code hash: %s",
		 option_code_hash_report(vendor_universe.code_hash));
#endif

        /* Set up the ISC Vendor-option universe (for option 125.2495)... */
        isc_universe.name = "isc";
	isc_universe.concat_duplicates = 0; /* XXX: check VIVSO ref */
        isc_universe.lookup_func = lookup_linked_option;
        isc_universe.option_state_dereference =
                linked_option_state_dereference;
        isc_universe.save_func = save_linked_option;
        isc_universe.delete_func = delete_linked_option;
        isc_universe.encapsulate = linked_option_space_encapsulate;
        isc_universe.foreach = linked_option_space_foreach;
        isc_universe.decode = parse_option_buffer;
        isc_universe.length_size = 2;
        isc_universe.tag_size = 2;
	isc_universe.get_tag = getUShort;
        isc_universe.store_tag = putUShort;
	isc_universe.get_length = getUShort;
        isc_universe.store_length = putUShort;
	isc_universe.site_code_min = 0;
	isc_universe.end = 0;
	code = VENDOR_ISC_SUBOPTIONS;
	isc_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&isc_universe.enc_opt,
				     vendor_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find ISC parent option (%s:%d).", MDL);
        isc_universe.index = universe_count++;
        universes[isc_universe.index] = &isc_universe;
        if (!option_name_new_hash(&isc_universe.name_hash,
				  VIV_ISC_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&isc_universe.code_hash,
				  VIV_ISC_HASH_SIZE, MDL))
                log_fatal("Can't allocate ISC Vendor options hash table.");
        for (i = 0 ; isc_options[i].name ; i++) {
		option_code_hash_add(isc_universe.code_hash,
				     &isc_options[i].code, 0,
				     &isc_options[i], MDL);
                option_name_hash_add(isc_universe.name_hash,
                                     isc_options[i].name, 0,
                                     &isc_options[i], MDL);
        }
#if defined(REPORT_HASH_PERFORMANCE)
	log_info("ISC name hash: %s",
		 option_name_hash_report(isc_universe.name_hash));
	log_info("ISC code hash: %s",
		 option_code_hash_report(isc_universe.code_hash));
#endif

	/* Set up the DHCPv6 root universe. */
	dhcpv6_universe.name = "dhcp6";
	dhcpv6_universe.concat_duplicates = 0;
	dhcpv6_universe.lookup_func = lookup_hashed_option;
	dhcpv6_universe.option_state_dereference =
		hashed_option_state_dereference;
	dhcpv6_universe.save_func = save_hashed_option;
	dhcpv6_universe.delete_func = delete_hashed_option;
	dhcpv6_universe.encapsulate = hashed_option_space_encapsulate;
	dhcpv6_universe.foreach = hashed_option_space_foreach;
	dhcpv6_universe.decode = parse_option_buffer;
	dhcpv6_universe.length_size = 2;
	dhcpv6_universe.tag_size = 2;
	dhcpv6_universe.get_tag = getUShort;
	dhcpv6_universe.store_tag = putUShort;
	dhcpv6_universe.get_length = getUShort;
	dhcpv6_universe.store_length = putUShort;
	dhcpv6_universe.site_code_min = 0;
	/* DHCPv6 has no END option. */
	dhcpv6_universe.end = 0x00;
	dhcpv6_universe.index = universe_count++;
	universes[dhcpv6_universe.index] = &dhcpv6_universe;
	if (!option_name_new_hash(&dhcpv6_universe.name_hash,
				  WORD_NAME_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&dhcpv6_universe.code_hash,
				  WORD_CODE_HASH_SIZE, MDL))
		log_fatal("Can't allocate dhcpv6 option hash tables.");
	for (i = 0 ; dhcpv6_options[i].name ; i++) {
		option_code_hash_add(dhcpv6_universe.code_hash,
				     &dhcpv6_options[i].code, 0,
				     &dhcpv6_options[i], MDL);
		option_name_hash_add(dhcpv6_universe.name_hash,
				     dhcpv6_options[i].name, 0,
				     &dhcpv6_options[i], MDL);
	}

	/* Add DHCPv6 protocol enumeration sets. */
	add_enumeration(&dhcpv6_duid_types);
	add_enumeration(&dhcpv6_status_codes);
	add_enumeration(&dhcpv6_messages);

	/* Set up DHCPv6 VSIO universe. */
	vsio_universe.name = "vsio";
	vsio_universe.concat_duplicates = 0;
	vsio_universe.lookup_func = lookup_hashed_option;
	vsio_universe.option_state_dereference =
		hashed_option_state_dereference;
	vsio_universe.save_func = save_hashed_option;
	vsio_universe.delete_func = delete_hashed_option;
	vsio_universe.encapsulate = hashed_option_space_encapsulate;
	vsio_universe.foreach = hashed_option_space_foreach;
	vsio_universe.decode = parse_option_buffer;
	vsio_universe.length_size = 0;
	vsio_universe.tag_size = 4;
	vsio_universe.get_tag = getULong;
	vsio_universe.store_tag = putULong;
	vsio_universe.get_length = NULL;
	vsio_universe.store_length = NULL;
	vsio_universe.site_code_min = 0;
	/* No END option. */
	vsio_universe.end = 0x00;
	code = D6O_VENDOR_OPTS;
	if (!option_code_hash_lookup(&vsio_universe.enc_opt,
				     dhcpv6_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find VSIO parent option (%s:%d).", MDL);
	vsio_universe.index = universe_count++;
	universes[vsio_universe.index] = &vsio_universe;
	if (!option_name_new_hash(&vsio_universe.name_hash,
				  VSIO_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&vsio_universe.code_hash,
				  VSIO_HASH_SIZE, MDL))
		log_fatal("Can't allocate Vendor Specific Information "
			  "Options space.");
	for (i = 0 ; vsio_options[i].name != NULL ; i++) {
		option_code_hash_add(vsio_universe.code_hash,
				     &vsio_options[i].code, 0,
				     &vsio_options[i], MDL);
		option_name_hash_add(vsio_universe.name_hash,
				     vsio_options[i].name, 0,
				     &vsio_options[i], MDL);
	}

	/* Add ISC VSIO sub-sub-option space. */
	isc6_universe.name = "isc6";
	isc6_universe.concat_duplicates = 0;
	isc6_universe.lookup_func = lookup_hashed_option;
	isc6_universe.option_state_dereference =
		hashed_option_state_dereference;
	isc6_universe.save_func = save_hashed_option;
	isc6_universe.delete_func = delete_hashed_option;
	isc6_universe.encapsulate = hashed_option_space_encapsulate;
	isc6_universe.foreach = hashed_option_space_foreach;
	isc6_universe.decode = parse_option_buffer;
	isc6_universe.length_size = 0;
	isc6_universe.tag_size = 4;
	isc6_universe.get_tag = getULong;
	isc6_universe.store_tag = putULong;
	isc6_universe.get_length = NULL;
	isc6_universe.store_length = NULL;
	isc6_universe.site_code_min = 0;
	/* No END option. */
	isc6_universe.end = 0x00;
	code = 2495;
	if (!option_code_hash_lookup(&isc6_universe.enc_opt,
				     vsio_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find ISC parent option (%s:%d).", MDL);
	isc6_universe.index = universe_count++;
	universes[isc6_universe.index] = &isc6_universe;
	if (!option_name_new_hash(&isc6_universe.name_hash,
				  VIV_ISC_HASH_SIZE, MDL) ||
	    !option_code_new_hash(&isc6_universe.code_hash,
				  VIV_ISC_HASH_SIZE, MDL))
		log_fatal("Can't allocate Vendor Specific Information "
			  "Options space.");
	for (i = 0 ; isc6_options[i].name != NULL ; i++) {
		option_code_hash_add(isc6_universe.code_hash,
				     &isc6_options[i].code, 0,
				     &isc6_options[i], MDL);
		option_name_hash_add(isc6_universe.name_hash,
				     isc6_options[i].name, 0,
				     &isc6_options[i], MDL);
	}

	/* The fqdn6 option space is a protocol-wrapper shill for the
	 * old DHCPv4 space.
	 */
	fqdn6_universe.name = "fqdn6-if-you-see-me-its-a-bug-bug-bug";
	fqdn6_universe.lookup_func = lookup_fqdn6_option;
	fqdn6_universe.option_state_dereference = NULL; /* Covered by v4. */
	fqdn6_universe.save_func = save_fqdn6_option;
	fqdn6_universe.delete_func = delete_fqdn6_option;
	fqdn6_universe.encapsulate = fqdn6_option_space_encapsulate;
	fqdn6_universe.foreach = fqdn6_option_space_foreach;
	fqdn6_universe.decode = fqdn6_universe_decode;
	/* This is not a 'normal' encapsulated space, so these values are
	 * meaningless.
	 */
	fqdn6_universe.length_size = 0;
	fqdn6_universe.tag_size = 0;
	fqdn6_universe.get_tag = NULL;
	fqdn6_universe.store_tag = NULL;
	fqdn6_universe.get_length = NULL;
	fqdn6_universe.store_length = NULL;
	fqdn6_universe.site_code_min = 0;
	fqdn6_universe.end = 0;
	fqdn6_universe.index = universe_count++;
	code = D6O_CLIENT_FQDN;
	fqdn6_universe.enc_opt = NULL;
	if (!option_code_hash_lookup(&fqdn6_universe.enc_opt,
				     dhcpv6_universe.code_hash, &code, 0, MDL))
		log_fatal("Unable to find FQDN v6 parent option. (%s:%d).",
			  MDL);
	universes[fqdn6_universe.index] = &fqdn6_universe;
	/* The fqdn6 space shares the same option space as the v4 space.
	 * So there are no name or code hashes on the v6 side.
	 */
	fqdn6_universe.name_hash = NULL;
	fqdn6_universe.code_hash = NULL;


	/* Set up the hash of DHCPv4 universes. */
	universe_new_hash(&universe_hash, UNIVERSE_HASH_SIZE, MDL);
	universe_hash_add(universe_hash, dhcp_universe.name, 0,
			  &dhcp_universe, MDL);
	universe_hash_add(universe_hash, nwip_universe.name, 0,
			  &nwip_universe, MDL);
	universe_hash_add(universe_hash, fqdn_universe.name, 0,
			  &fqdn_universe, MDL);
	universe_hash_add(universe_hash, vendor_class_universe.name, 0,
			  &vendor_class_universe, MDL);
	universe_hash_add(universe_hash, vendor_universe.name, 0,
			  &vendor_universe, MDL);
	universe_hash_add(universe_hash, isc_universe.name, 0,
			  &isc_universe, MDL);

	/* Set up hashes for DHCPv6 universes. */
	universe_hash_add(universe_hash, dhcpv6_universe.name, 0,
			  &dhcpv6_universe, MDL);
	universe_hash_add(universe_hash, vsio_universe.name, 0,
			  &vsio_universe, MDL);
	universe_hash_add(universe_hash, isc6_universe.name, 0,
			  &isc6_universe, MDL);
/* This should not be necessary.  Listing here just for consistency.
 *	universe_hash_add(universe_hash, fqdn6_universe.name, 0,
 *			  &fqdn6_universe, MDL);
 */
}
Ejemplo n.º 17
0
void dhcp_common_objects_setup ()
{
	isc_result_t status;

	status = omapi_object_type_register (&dhcp_type_control,
					     "control",
					     dhcp_control_set_value,
					     dhcp_control_get_value,
					     dhcp_control_destroy,
					     dhcp_control_signal_handler,
					     dhcp_control_stuff_values,
					     dhcp_control_lookup, 
					     dhcp_control_create,
					     dhcp_control_remove, 0, 0, 0,
					     sizeof (dhcp_control_object_t),
					     0, RC_MISC);
	if (status != ISC_R_SUCCESS)
		log_fatal ("Can't register control object type: %s",
			   isc_result_totext (status));
	status = dhcp_control_allocate (&dhcp_control_object, MDL);
	if (status != ISC_R_SUCCESS)
		log_fatal ("Can't make initial control object: %s",
			   isc_result_totext (status));
	dhcp_control_object -> state = server_startup;

	status = omapi_object_type_register (&dhcp_type_group,
					     "group",
					     dhcp_group_set_value,
					     dhcp_group_get_value,
					     dhcp_group_destroy,
					     dhcp_group_signal_handler,
					     dhcp_group_stuff_values,
					     dhcp_group_lookup, 
					     dhcp_group_create,
					     dhcp_group_remove, 0, 0, 0,
					     sizeof (struct group_object), 0,
					     RC_MISC);
	if (status != ISC_R_SUCCESS)
		log_fatal ("Can't register group object type: %s",
			   isc_result_totext (status));

	status = omapi_object_type_register (&dhcp_type_subnet,
					     "subnet",
					     dhcp_subnet_set_value,
					     dhcp_subnet_get_value,
					     dhcp_subnet_destroy,
					     dhcp_subnet_signal_handler,
					     dhcp_subnet_stuff_values,
					     dhcp_subnet_lookup, 
					     dhcp_subnet_create,
					     dhcp_subnet_remove, 0, 0, 0,
					     sizeof (struct subnet), 0,
					     RC_MISC);
	if (status != ISC_R_SUCCESS)
		log_fatal ("Can't register subnet object type: %s",
			   isc_result_totext (status));

	status = omapi_object_type_register
		(&dhcp_type_shared_network,
		 "shared-network",
		 dhcp_shared_network_set_value,
		 dhcp_shared_network_get_value,
		 dhcp_shared_network_destroy,
		 dhcp_shared_network_signal_handler,
		 dhcp_shared_network_stuff_values,
		 dhcp_shared_network_lookup, 
		 dhcp_shared_network_create,
		 dhcp_shared_network_remove, 0, 0, 0,
		 sizeof (struct shared_network), 0, RC_MISC);
	if (status != ISC_R_SUCCESS)
		log_fatal ("Can't register shared network object type: %s",
			   isc_result_totext (status));

	interface_setup ();
}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
    int ret = 0;
    int rc;
    char *str = NULL;
    int ti = (argc > 1 ? atoi(argv[1]) : 0);

    srand(time(NULL));
    str = getenv("VERBOSE");
    _verbose = (str ? atoi(str) : _verbose);
    str = getenv("LEGACY");
    _legacy = (str ? atoi(str) : _legacy);

    spawned = random_value(10, 20);
    size = random_value(10, 20);
    rank = random_value(10, 20);
    appnum = random_value(10, 20);
    if (PMI2_SUCCESS != (rc = PMI2_Init(&spawned, &size, &rank, &appnum))) {
        log_fatal("PMI2_Init failed: %d\n", rc);
        return rc;
    }

    if (!ti || 1 == ti) {
        rc = test_item1();
        ret += (rc ? 1 : 0);
        log_info("TI1  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 2 == ti) {
        rc = test_item2();
        ret += (rc ? 1 : 0);
        log_info("TI2  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 3 == ti) {
        rc = test_item3();
        ret += (rc ? 1 : 0);
        log_info("TI3  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 4 == ti) {
        rc = test_item4();
        ret += (rc ? 1 : 0);
        log_info("TI4  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 5 == ti) {
        rc = test_item5();
        ret += (rc ? 1 : 0);
        log_info("TI5  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 6 == ti) {
        rc = test_item6();
        ret += (rc ? 1 : 0);
        log_info("TI6  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 7 == ti) {
        rc = test_item7();
        ret += (rc ? 1 : 0);
        log_info("TI7  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 8 == ti) {
        rc = test_item8();
        ret += (rc ? 1 : 0);
        log_info("TI8  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (!ti || 9 == ti) {
        rc = test_item9();
        ret += (rc ? 1 : 0);
        log_info("TI9  : %s\n", (rc ? "FAIL" : "PASS"));
    }

    if (PMI2_SUCCESS != (rc = PMI2_Finalize())) {
        log_fatal("PMI2_Finalize failed: %d\n", rc);
        return rc;
    }

    return ret;
}
Ejemplo n.º 19
0
int parity_chsize(struct snapraid_parity_handle* parity, data_off_t size, data_off_t* out_size, int skip_fallocate)
{
	int ret;

	if (parity->st.st_size < size) {
		int f_ret;
		int f_errno;
		const char* call;

#if HAVE_FALLOCATE
		call = "fallocate";
		if (!skip_fallocate) {
			/* allocate real space using the specific Linux fallocate() operation. */
			/* If the underline filesystem doesn't support it, this operation fails, */
			/* instead posix_fallocate() fallbacks to write the whole file. */
			ret = fallocate(parity->f, 0, 0, size);

			/* fallocate() returns the error number as positive integer, */
			/* and in this case it doesn't set errno, just like posix_fallocate() */
			/* Checking the glibc code (2.11.1 and 2.14.1) it seems that ENOSYS */
			/* may be returned in errno, so we support both the return way */
			if (ret > 0) { /* if a positive error is returned, convert it to errno */
				/* LCOV_EXCL_START */
				errno = ret;
				ret = -1;
				/* LCOV_EXCL_STOP */
			}
		} else {
			errno = EOPNOTSUPP;
			ret = -1;
		}

		/* we get EOPNOTSUPP if the operation is not supported, like in ext3/ext2 */
		/* or ENOSYS with kernel before 2.6.23 */
		if (errno == EOPNOTSUPP || errno == ENOSYS) {
			/* fallback using ftruncate() */
			call = "ftruncate";
			ret = ftruncate(parity->f, size);
		}
#else
		(void)skip_fallocate; /* avoid the warning */

		/* allocate using a sparse file */
		call = "ftruncate";
		ret = ftruncate(parity->f, size);
#endif
		/* save the state of the grow operation */
		f_ret = ret;
		f_errno = errno;

		/* get the stat info */
		ret = fstat(parity->f, &parity->st);
		if (ret != 0) {
			/* LCOV_EXCL_START */
			log_fatal("Error accessing parity file '%s'. %s.\n", parity->path, strerror(errno));
			goto bail;
			/* LCOV_EXCL_STOP */
		}

		/* return the new size */
		*out_size = parity->st.st_size;

		/* now check the error */
		if (f_ret != 0) {
			/* LCOV_EXCL_START */
			if (f_errno == ENOSPC) {
				log_fatal("Failed to grow parity file '%s' to size %" PRIu64 " using %s due lack of space.\n", parity->path, size, call);
			} else {
				log_fatal("Error growing parity file '%s' to size %" PRIu64 " using %s. Do you have enough space? %s.\n", parity->path, size, call, strerror(f_errno));
			}
			goto bail;
			/* LCOV_EXCL_STOP */
		}
	} else if (parity->st.st_size > size) {
		int f_ret;
		int f_errno;

		/* truncate the parity file */
		ret = ftruncate(parity->f, size);

		/* save the state of the shrink operation */
		f_ret = ret;
		f_errno = errno;

		/* get the stat info */
		ret = fstat(parity->f, &parity->st);
		if (ret != 0) {
			/* LCOV_EXCL_START */
			log_fatal("Error accessing parity file '%s'. %s.\n", parity->path, strerror(errno));
			goto bail;
			/* LCOV_EXCL_STOP */
		}

		/* return the new size */
		*out_size = parity->st.st_size;

		/* now check the error */
		if (f_ret != 0) {
			/* LCOV_EXCL_START */
			log_fatal("Error truncating parity file '%s' to size %" PRIu64 ". %s.\n", parity->path, size, strerror(f_errno));
			goto bail;
			/* LCOV_EXCL_STOP */
		}

		/* adjust the valid to the new size */
		parity->valid_size = size;
	}

	return 0;

bail:
	/* LCOV_EXCL_START */
	parity->valid_size = 0;
	return -1;
	/* LCOV_EXCL_STOP */
}
Ejemplo n.º 20
0
NetworkServer* NetworkServer::init(const Config &conf, int num_readers, int num_writers){
	static bool inited = false;
	if(inited){
		return NULL;
	}
	inited = true;
	
	NetworkServer *serv = new NetworkServer();
	if(num_readers >= 0){
		serv->num_readers = num_readers;
	}
	if(num_writers >= 0){
		serv->num_writers = num_writers;
	}
	
	{ // server
		const char *ip = conf.get_str("server.ip");
		int port = conf.get_num("server.port");
		if(ip == NULL || ip[0] == '\0'){
			ip = "127.0.0.1";
		}
		
		serv->serv_link = Link::listen(ip, port);
		if(serv->serv_link == NULL){
			log_fatal("error opening server socket! %s", strerror(errno));
			fprintf(stderr, "error opening server socket! %s\n", strerror(errno));
			exit(1);
		}
		// see UNP
		// if client send RST between server's calls of select() and accept(),
		// accept() will block until next connection.
		// so, set server socket nonblock.
		serv->serv_link->noblock();
		log_info("server listen on %s:%d", ip, port);

		std::string password;
		password = conf.get_str("server.auth");
		if(password.size() && (password.size() < 32 || password == "very-strong-password")){
			log_fatal("weak password is not allowed!");
			fprintf(stderr, "WARNING! Weak password is not allowed!\n");
			exit(1);
		}
		if(password.empty()){
			log_info("    auth    : off");
		}else{
			log_info("    auth    : on");
		}
		serv->need_auth = false;		
		if(!password.empty()){
			serv->need_auth = true;
			serv->password = password;
		}
	}

	// init ip_filter
	{
		Config *cc = (Config *)conf.get("server");
		if(cc != NULL){
			std::vector<Config *> *children = &cc->children;
			std::vector<Config *>::iterator it;
			for(it = children->begin(); it != children->end(); it++){
				if((*it)->key == "allow"){
					const char *ip = (*it)->str();
					log_info("    allow   : %s", ip);
					serv->ip_filter->add_allow(ip);
				}
				if((*it)->key == "deny"){
					const char *ip = (*it)->str();
					log_info("    deny   : %s", ip);
					serv->ip_filter->add_deny(ip);
				}
			}
		}
	}
	
	std::string readonly = conf.get_str("server.readonly");
	strtolower(&readonly);
	if(readonly == "yes"){
		serv->readonly = true;
	}else{
		readonly = "no";
		serv->readonly = false;
	}
	log_info("    readonly: %s", readonly.c_str());
	

	return serv;
}
Ejemplo n.º 21
0
static void
init_pool( size_t n)
{
    long int pgsize_val;
    size_t pgsize;

    poolsize = n;

    if( disable_secmem )
	log_bug("secure memory is disabled");

#if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
    pgsize_val = sysconf (_SC_PAGESIZE);
#elif defined(HAVE_GETPAGESIZE)
    pgsize_val = getpagesize ();
#else
    pgsize_val = -1;
#endif
    pgsize = (pgsize_val != -1 && pgsize_val > 0)? pgsize_val : 4096;


#ifdef HAVE_MMAP
    poolsize = (poolsize + pgsize -1 ) & ~(pgsize-1);
#ifdef MAP_ANONYMOUS
       pool = mmap( 0, poolsize, PROT_READ|PROT_WRITE,
				 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#else /* map /dev/zero instead */
    {	int fd;

	fd = open("/dev/zero", O_RDWR);
	if( fd == -1 ) {
	    log_error("can't open /dev/zero: %s\n", strerror(errno) );
	    pool = (void*)-1;
	}
	else {
	    pool = mmap( 0, poolsize, PROT_READ|PROT_WRITE,
				      MAP_PRIVATE, fd, 0);
	    close (fd);
	}
    }
#endif
    if( pool == (void*)-1 )
	log_info("can't mmap pool of %u bytes: %s - using malloc\n",
			    (unsigned)poolsize, strerror(errno));
    else {
	pool_is_mmapped = 1;
	pool_okay = 1;
    }

#endif
    if( !pool_okay ) {
	pool = malloc( poolsize );
	if( !pool )
	    log_fatal("can't allocate memory pool of %u bytes\n",
						       (unsigned)poolsize);
	else
	    pool_okay = 1;
    }
    lock_pool( pool, poolsize );
    poollen = 0;
}
Ejemplo n.º 22
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  gpg_error_t err;
  int rc;
  parsed_uri_t uri;
  uri_tuple_t r;
  http_t hd;
  int c;
  unsigned int my_http_flags = 0;
  int no_out = 0;
  int tls_dbg = 0;
  const char *cafile = NULL;
  http_session_t session = NULL;

  gpgrt_init ();
  log_set_prefix (PGM, 1 | 4);
  if (argc)
    { argc--; argv++; }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: " PGM " URL\n"
                 "Options:\n"
                 "  --verbose         print timings etc.\n"
                 "  --debug           flyswatter\n"
                 "  --gnutls-debug N  use GNUTLS debug level N\n"
                 "  --cacert FNAME    expect CA certificate in file FNAME\n"
                 "  --no-verify       do not verify the certificate\n"
                 "  --force-tls       use HTTP_FLAG_FORCE_TLS\n"
                 "  --no-out          do not print the content\n",
                 stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose += 2;
          debug++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--gnutls-debug"))
        {
          argc--; argv++;
          if (argc)
            {
              tls_dbg = atoi (*argv);
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--cacert"))
        {
          argc--; argv++;
          if (argc)
            {
              cafile = *argv;
              argc--; argv++;
            }
        }
      else if (!strcmp (*argv, "--no-verify"))
        {
          no_verify = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force-tls"))
        {
          my_http_flags |= HTTP_FLAG_FORCE_TLS;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--no-out"))
        {
          no_out = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        {
          fprintf (stderr, PGM ": unknown option '%s'\n", *argv);
          exit (1);
        }
    }
  if (argc != 1)
    {
      fprintf (stderr, PGM ": no or too many URLS given\n");
      exit (1);
    }

  if (!cafile)
    cafile = prepend_srcdir ("tls-ca.pem");

#if HTTP_USE_NTBTLS

  (void)err;

  ntbtls_set_debug (tls_dbg, NULL, NULL);

#elif HTTP_USE_GNUTLS

  rc = gnutls_global_init ();
  if (rc)
    log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));

  http_register_tls_callback (verify_callback);
  http_register_tls_ca (cafile);

  err = http_session_new (&session, NULL);
  if (err)
    log_error ("http_session_new failed: %s\n", gpg_strerror (err));

  /* rc = gnutls_dh_params_init(&dh_params); */
  /* if (rc) */
  /*   log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */
  /* read_dh_params ("dh_param.pem"); */

  /* rc = gnutls_certificate_set_x509_trust_file */
  /*   (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */
  /* if (rc) */
  /*   log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */
  /*              gnutls_strerror (rc)); */

  /* gnutls_certificate_set_dh_params (certcred, dh_params); */

  gnutls_global_set_log_function (my_gnutls_log);
  if (tls_dbg)
    gnutls_global_set_log_level (tls_dbg);

#endif /*HTTP_USE_GNUTLS*/

  rc = http_parse_uri (&uri, *argv, 1);
  if (rc)
    {
      log_error ("'%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }

  printf ("Scheme: %s\n", uri->scheme);
  if (uri->opaque)
    printf ("Value : %s\n", uri->path);
  else
    {
      printf ("Auth  : %s\n", uri->auth? uri->auth:"[none]");
      printf ("Host  : %s\n", uri->host);
      printf ("Port  : %u\n", uri->port);
      printf ("Path  : %s\n", uri->path);
      for (r = uri->params; r; r = r->next)
        {
          printf ("Params: %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      for (r = uri->query; r; r = r->next)
        {
          printf ("Query : %s", r->name);
          if (!r->no_value)
            {
              printf ("=%s", r->value);
              if (strlen (r->value) != r->valuelen)
                printf (" [real length=%d]", (int) r->valuelen);
            }
          putchar ('\n');
        }
      printf ("TLS   : %s\n",
              uri->use_tls? "yes":
              (my_http_flags&HTTP_FLAG_FORCE_TLS)? "forced" : "no");

    }
  fflush (stdout);
  http_release_parsed_uri (uri);
  uri = NULL;

  rc = http_open_document (&hd, *argv, NULL, my_http_flags,
                           NULL, session, NULL, NULL);
  if (rc)
    {
      log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc));
      return 1;
    }
  log_info ("open_http_document succeeded; status=%u\n",
            http_get_status_code (hd));

  {
    const char **names;
    int i;

    names = http_get_header_names (hd);
    if (!names)
      log_fatal ("http_get_header_names failed: %s\n",
                 gpg_strerror (gpg_error_from_syserror ()));
    for (i = 0; names[i]; i++)
      printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i]));
    xfree (names);
  }
  fflush (stdout);

  switch (http_get_status_code (hd))
    {
    case 200:
    case 400:
    case 401:
    case 403:
    case 404:
      {
        unsigned long count = 0;
        while ((c = es_getc (http_get_read_ptr (hd))) != EOF)
          {
            count++;
            if (!no_out)
              putchar (c);
          }
        log_info ("Received bytes: %lu\n", count);
      }
      break;
    case 301:
    case 302:
    case 307:
      log_info ("Redirected to: %s\n", http_get_header (hd, "Location"));
      break;
    }
  http_close (hd, 0);

  http_session_release (session);
#ifdef HTTP_USE_GNUTLS
  gnutls_global_deinit ();
#endif /*HTTP_USE_GNUTLS*/

  return 0;
}
Ejemplo n.º 23
0
void gdnsd_prcu_destroy_lock(void) {
    int pthread_err;
    if((pthread_err = pthread_rwlock_destroy(&gdnsd_prcu_rwlock)))
        log_fatal("pthread_rwlock_destroy() failed: %s", dmn_logf_strerror(pthread_err));
}
Ejemplo n.º 24
0
F_NONNULL F_NORETURN
static void syserr_for_ev(const char* msg) { dmn_assert(msg); log_fatal("%s: %s", msg, dmn_logf_errno()); }
Ejemplo n.º 25
0
static void
lock_pool( void *p, size_t n )
{
#if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK)
    int err;

    cap_set_proc( cap_from_text("cap_ipc_lock+ep") );
    err = mlock( p, n );
    if( err && errno )
	err = errno;
    cap_set_proc( cap_from_text("cap_ipc_lock+p") );

    if( err ) {
	if( errno != EPERM
#ifdef EAGAIN  /* OpenBSD returns this */
	    && errno != EAGAIN
#endif
#ifdef ENOSYS  /* Some SCOs return this (function not implemented) */
	    && errno != ENOSYS
#endif
#ifdef ENOMEM  /* Linux can return this */
            && errno != ENOMEM
#endif
	  )
	    log_error("can't lock memory: %s\n", strerror(err));
	show_warning = 1;
    }

#elif defined(HAVE_MLOCK)
    uid_t uid;
    int err;

    uid = getuid();

#ifdef HAVE_BROKEN_MLOCK
    /* ick. but at least we get secured memory. about to lock
       entire data segment. */
#ifdef HAVE_PLOCK
# ifdef _AIX
    /* The configure for AIX returns broken mlock but the plock has
       the strange requirement to somehow set the stack limit first.
       The problem might turn out in indeterministic program behaviour
       and hanging processes which can somehow be solved when enough
       processes are clogging up the memory.  To get this problem out
       of the way we simply don't try to lock the memory at all.
       */    
    errno = EPERM;
    err = errno;
# else /* !_AIX */
    err = plock( DATLOCK );
    if( err && errno )
        err = errno;
# endif /*_AIX*/
#else /*!HAVE_PLOCK*/
    if( uid ) {
	errno = EPERM;
	err = errno;
    }
    else {
	err = mlock( p, n );
	if( err && errno )
	    err = errno;
    }
#endif /*!HAVE_PLOCK*/
#else
    err = mlock( p, n );
    if( err && errno )
	err = errno;
#endif

    if( uid && !geteuid() ) {
	/* check that we really dropped the privs.
	 * Note: setuid(0) should always fail */
	if( setuid( uid ) || getuid() != geteuid() || !setuid(0) )
	    log_fatal("failed to reset uid: %s\n", strerror(errno));
    }

    if( err ) {
	if( errno != EPERM
#ifdef EAGAIN  /* OpenBSD returns this */
	    && errno != EAGAIN
#endif
#ifdef ENOSYS  /* Some SCOs return this (function not implemented) */
	    && errno != ENOSYS
#endif
#ifdef ENOMEM  /* Linux can return this */
            && errno != ENOMEM
#endif
	  )
#ifdef __VMS
	    log_warning ("can't lock memory: %s\n", strerror(err));
#else
	    log_error ("can't lock memory: %s\n", strerror(err));
#endif
	show_warning = 1;
    }

#elif defined ( __QNX__ )
    /* QNX does not page at all, so the whole secure memory stuff does
     * not make much sense.  However it is still of use because it
     * wipes out the memory on a free().
     * Therefore it is sufficient to suppress the warning
     */
#elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__)
    /* It does not make sense to print such a warning, given the fact that 
     * this whole Windows !@#$% and their user base are inherently insecure
     */
#elif defined (__riscos__)
    /* no virtual memory on RISC OS, so no pages are swapped to disc,
     * besides we don't have mmap, so we don't use it! ;-)
     * But don't complain, as explained above.
     */
#else
    log_info("Please note that you don't have secure memory on this system\n");
#endif
}
Ejemplo n.º 26
0
/**
 * @brief Initialize the NSSI RPC mechanism.
 *
 * This implementation of \b nssi_rpc_init initializes the
 * Portals library and interface so that we can use Portals
 * as the underlying communication protocol.
 *
 * @param pid  @input The ID to use for this process.
 */
int nssi_rpc_init(
    const nssi_rpc_transport rpc_transport,
    const nssi_rpc_encode    rpc_encode,
    const char              *url)
{
    int rc;

    NNTI_transport_id_t transport_id;

    log_debug(rpc_debug_level, "************************************************************ entered");

    if (rpc_initialized) return NSSI_OK;

    /* check to see if logging is enabled */
    if (logger_not_initialized()) {
        logger_set_file(stderr);
    }

    /* make sure the timer works properly */
//    rc = nssi_timer_test();
//    if (rc != NSSI_OK) {
//        log_fatal(rpc_debug_level, "nssi_timer_test() failed");
//        return rc;
//    }

    /* stash the transport and encoding types so we know how to cleanup on exit */
//    transport = rpc_transport;
    encoding  = rpc_encode;

    /* initialize the transport mechanism */
    switch (rpc_transport) {
        case NSSI_RPC_PTL:
            transport_id=NNTI_TRANSPORT_PORTALS;
            break;
        case NSSI_RPC_IB:
            transport_id=NNTI_TRANSPORT_IB;
            break;
        case NSSI_RPC_LUC:
            transport_id=NNTI_TRANSPORT_LUC;
            break;
        case NSSI_RPC_GEMINI:
            transport_id=NNTI_TRANSPORT_GEMINI;
            break;
        case NSSI_RPC_MPI:
            transport_id=NNTI_TRANSPORT_MPI;
            break;
        default:
            rc = NSSI_ENOENT;
            log_error(rpc_debug_level, "the transport scheme %d does not exist", rpc_transport);
            return rc;
    }

    rc = NNTI_init(
            transport_id,
            url,
            &transports[rpc_transport]);
    if (rc != NNTI_OK) {
        log_fatal(rpc_debug_level,"failed");
        return rc;
    }

    /* initialize the xdr-encoding mechanism */
    switch (rpc_encode) {
        case NSSI_RPC_XDR:
            rc = nssi_xdr_init();
            if (rc != NSSI_OK) {
                log_fatal(rpc_debug_level,"failed, %d", rc);
                return rc;
            }
            break;

        default:
            rc = NSSI_ENOENT;
            log_error(rpc_debug_level, "the transport scheme "
            "does not exist");
            return rc;
    }

    config_init(&nssi_config);
    config_get_from_env(&nssi_config);
    if (nssi_config.use_buffer_queue) {
        trios_buffer_queue_init(
                &send_bq,
                nssi_config.buffer_queue_initial_size,
                nssi_config.buffer_queue_max_size,
                nssi_config.buffer_queue_create_if_empty,
                &transports[rpc_transport],
                NNTI_SEND_SRC,
                NSSI_SHORT_REQUEST_SIZE);
        trios_buffer_queue_init(
                &recv_bq,
                nssi_config.buffer_queue_initial_size,
                nssi_config.buffer_queue_max_size,
                nssi_config.buffer_queue_create_if_empty,
                &transports[rpc_transport],
                NNTI_RECV_DST,
                NSSI_SHORT_RESULT_SIZE);
        trios_buffer_queue_init(
                &rdma_target_bq,
                nssi_config.rdma_buffer_queue_initial_size,
                nssi_config.rdma_buffer_queue_max_size,
                nssi_config.rdma_buffer_queue_create_if_empty,
                &transports[rpc_transport],
                (NNTI_buf_ops_t)(NNTI_GET_SRC|NNTI_PUT_DST),
                nssi_config.rdma_buffer_queue_buffer_size);
        trios_buffer_queue_init(
                &rdma_get_bq,
                nssi_config.rdma_buffer_queue_initial_size,
                nssi_config.rdma_buffer_queue_max_size,
                nssi_config.rdma_buffer_queue_create_if_empty,
                &transports[rpc_transport],
                NNTI_GET_DST,
                nssi_config.rdma_buffer_queue_buffer_size);
        trios_buffer_queue_init(
                &rdma_put_bq,
                nssi_config.rdma_buffer_queue_initial_size,
                nssi_config.rdma_buffer_queue_max_size,
                nssi_config.rdma_buffer_queue_create_if_empty,
                &transports[rpc_transport],
                NNTI_PUT_SRC,
                nssi_config.rdma_buffer_queue_buffer_size);
    }

    rpc_initialized = true;

    if (logging_debug(rpc_debug_level)) {
        fprint_NNTI_peer(logger_get_file(), "transports[rpc_transport].me",
                "end of nssi_rpc_init", &transports[rpc_transport].me);
    }

    log_debug(rpc_debug_level, "************************************************************  exit");

    return NSSI_OK;
}
Ejemplo n.º 27
0
/****************
 * Decrypt INBUF to OUTBUF with the mode selected at open.
 * inbuf and outbuf may overlap or be the same.
 * Depending on the mode some some contraints apply to INBUFLEN.
 */
static gcry_err_code_t
cipher_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen,
                const byte *inbuf, size_t inbuflen)
{
  gcry_err_code_t rc;

  switch (c->mode)
    {
    case GCRY_CIPHER_MODE_ECB:
      rc = do_ecb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_CBC:
      rc = _gcry_cipher_cbc_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_CFB:
      rc = _gcry_cipher_cfb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_OFB:
      rc = _gcry_cipher_ofb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_CTR:
      rc = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_AESWRAP:
      rc = _gcry_cipher_aeswrap_decrypt (c, outbuf, outbuflen,
                                         inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_CCM:
      rc = _gcry_cipher_ccm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_CMAC:
      rc = GPG_ERR_INV_CIPHER_MODE;
      break;

    case GCRY_CIPHER_MODE_GCM:
      rc = _gcry_cipher_gcm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_POLY1305:
      rc = _gcry_cipher_poly1305_decrypt (c, outbuf, outbuflen,
					  inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_OCB:
      rc = _gcry_cipher_ocb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen);
      break;

    case GCRY_CIPHER_MODE_STREAM:
      c->spec->stdecrypt (&c->context.c,
                          outbuf, (byte*)/*arggg*/inbuf, inbuflen);
      rc = 0;
      break;

    case GCRY_CIPHER_MODE_NONE:
      if (fips_mode () || !_gcry_get_debug_flag (0))
        {
          fips_signal_error ("cipher mode NONE used");
          rc = GPG_ERR_INV_CIPHER_MODE;
        }
      else
        {
          if (inbuf != outbuf)
            memmove (outbuf, inbuf, inbuflen);
          rc = 0;
        }
      break;

    default:
      log_fatal ("cipher_decrypt: invalid mode %d\n", c->mode );
      rc = GPG_ERR_INV_CIPHER_MODE;
      break;
    }

  return rc;
}
Ejemplo n.º 28
0
static Projectile* _create_projectile(ProjArgs *args) {
	if(IN_DRAW_CODE) {
		log_fatal("Tried to spawn a projectile while in drawing code");
	}

	Projectile *p = (Projectile*)objpool_acquire(stage_object_pools.projectiles);

	p->birthtime = global.frames;
	p->pos = p->pos0 = p->prevpos = args->pos;
	p->angle = args->angle;
	p->rule = args->rule;
	p->draw_rule = args->draw_rule;
	p->shader = args->shader_ptr;
	p->blend = args->blend;
	p->sprite = args->sprite_ptr;
	p->type = args->type;
	p->color = *args->color;
	p->max_viewport_dist = args->max_viewport_dist;
	p->size = args->size;
	p->collision_size = args->collision_size;
	p->flags = args->flags;
	p->timeout = args->timeout;
	p->damage = args->damage;
	p->damage_type = args->damage_type;
	p->clear_flags = 0;

	if(args->shader_params != NULL) {
		p->shader_params = *args->shader_params;
	}

	memcpy(p->args, args->args, sizeof(p->args));

	p->ent.draw_layer = args->layer;
	p->ent.draw_func = ent_draw_projectile;

	projectile_set_prototype(p, args->proto);

	// p->collision_size *= 10;
	// p->size *= 5;

	if((p->type == PROJ_ENEMY || p->type == PROJ_PLAYER) && (creal(p->size) <= 0 || cimag(p->size) <= 0)) {
		log_fatal("Tried to spawn a projectile with invalid size %f x %f", creal(p->size), cimag(p->size));
	}

	if(!(p->ent.draw_layer & LAYER_LOW_MASK)) {
		drawlayer_low_t sublayer;

		switch(p->type) {
			case PROJ_ENEMY:
				// 1. Large projectiles go below smaller ones.
				sublayer = LAYER_LOW_MASK - (drawlayer_low_t)projectile_rect_area(p);
				sublayer = (sublayer << 4) & LAYER_LOW_MASK;
				// 2. Group by shader (hardcoded precedence).
				sublayer |= ht_get(&shader_sublayer_map, p->shader, 0) & 0xf;
				// If specific blending order is required, then you should set up the sublayer manually.
				p->ent.draw_layer |= sublayer;
				break;

			case PROJ_PARTICLE:
				// 1. Group by shader (hardcoded precedence).
				sublayer = ht_get(&shader_sublayer_map, p->shader, 0) & 0xf;
				sublayer <<= 4;
				sublayer |= 0x100;
				// If specific blending order is required, then you should set up the sublayer manually.
				p->ent.draw_layer |= sublayer;
				break;

			default:
				break;
		}
	}

	ent_register(&p->ent, ENT_PROJECTILE);

	// TODO: Maybe allow ACTION_DESTROY here?
	// But in that case, code that uses this function's return value must be careful to not dereference a NULL pointer.
	proj_call_rule(p, EVENT_BIRTH);
	alist_append(args->dest, p);

	return p;
}
Ejemplo n.º 29
0
void NetworkServer::serve(){
	writer = new ProcWorkerPool("writer");
	writer->start(num_writers);
	reader = new ProcWorkerPool("reader");
	reader->start(num_readers);

	ready_list_t ready_list;
	ready_list_t ready_list_2;
	ready_list_t::iterator it;
	const Fdevents::events_t *events;

	fdes->set(serv_link->fd(), FDEVENT_IN, 0, serv_link);
	fdes->set(this->reader->fd(), FDEVENT_IN, 0, this->reader);
	fdes->set(this->writer->fd(), FDEVENT_IN, 0, this->writer);
	
	uint32_t last_ticks = g_ticks;
	
	while(!quit){
		double loop_stime = millitime();

		// status report
		if((uint32_t)(g_ticks - last_ticks) >= STATUS_REPORT_TICKS){
			last_ticks = g_ticks;
			log_info("server running, links: %d", this->link_count);
		}
		
		ready_list.swap(ready_list_2);
		ready_list_2.clear();
		
		if(!ready_list.empty()){
			// ready_list not empty, so we should return immediately
			events = fdes->wait(0);
		}else{
			events = fdes->wait(50);
		}
		if(events == NULL){
			log_fatal("events.wait error: %s", strerror(errno));
			break;
		}
		
		for(int i=0; i<(int)events->size(); i++){
			const Fdevent *fde = events->at(i);
			if(fde->data.ptr == serv_link){
				Link *link = accept_link();
				if(link){
					this->link_count ++;				
					log_debug("new link from %s:%d, fd: %d, links: %d",
						link->remote_ip, link->remote_port, link->fd(), this->link_count);
					fdes->set(link->fd(), FDEVENT_IN, 1, link);
				}else{
					log_debug("accept return NULL");
				}
			}else if(fde->data.ptr == this->reader || fde->data.ptr == this->writer){
				ProcWorkerPool *worker = (ProcWorkerPool *)fde->data.ptr;
				ProcJob *job = NULL;
				if(worker->pop(&job) == 0){
					log_fatal("reading result from workers error!");
					exit(0);
				}
				proc_result(job, &ready_list);
			}else{
				proc_client_event(fde, &ready_list);
			}
		}

		for(it = ready_list.begin(); it != ready_list.end(); it ++){
			Link *link = *it;
			fdes->del(link->fd());

			if(link->error()){
				this->link_count --;
				delete link;
				continue;
			}

			const Request *req = link->recv();
			if(req == NULL){
				log_warn("fd: %d, link parse error, delete link", link->fd());
				link->mark_error();
				ready_list_2.push_back(link);
				continue;
			}
			if(req->empty()){
				fdes->set(link->fd(), FDEVENT_IN, 1, link);
				continue;
			}
			
			link->active_time = millitime();

			ProcJob *job = new ProcJob();
			job->link = link;
			job->req = link->last_recv();
			int result = this->proc(job);
			if(result == PROC_THREAD){
				//
			}else if(result == PROC_BACKEND){
				// link_count does not include backend links
				this->link_count --;
			}else{
				proc_result(job, &ready_list_2);
			}
		} // end foreach ready link

		double loop_time = millitime() - loop_stime;
		if(loop_time > 0.5){
			log_warn("long loop time: %.3f", loop_time);
		}
	}
}
Ejemplo n.º 30
0
static int test_item9(void)
{
    int rc = 0;
    int i, j, r;
    char symb, symb_start = 'a';
    int fence_cnt;
    int fence_num = random_value(2, 10);
    int keys_per_fence = random_value(10, 100);
    int val_size = random_value(10, PMI2_MAX_VALLEN / 10);
    int keys_total = 0;

    fence_cnt = 0;
    while (fence_cnt < fence_num) {
        log_info("fence_cnt=%d of fence_num=%d keys_per_fence=%d keys_total=%d val_size=%d\n",
                fence_cnt, fence_num, keys_per_fence, keys_total, val_size);
        symb = symb_start;
        for (i = 0; i < keys_per_fence; i++) {
            char key[PMI2_MAX_KEYLEN];
            char val[PMI2_MAX_VALLEN] = "";
            sprintf(key, "RANK%d-key-%d", rank, i + keys_total);
            for (j = 0; j < val_size; j++) {
                val[j] = symb;
            }
            symb++;
            if (symb > 'z') {
                symb = 'a';
            }
            if (PMI2_SUCCESS != (rc = PMI2_KVS_Put(key, val))) {
                log_fatal("PMI2_KVS_Put [%s=%s] %d\n", key, val, rc);
                return rc;
            }
            log_info("PMI2_KVS_Put [rank=%d %s] %d\n", rank, key, rc);
        }
        symb_start = symb;
        keys_total += keys_per_fence;

        if (PMI2_SUCCESS != (rc = PMI2_KVS_Fence())) {
            log_fatal("PMI2_KVS_Fence %d\n", rc);
            return rc;
        }

        for (r = 0; r < size; r++) {
            int len;
            symb = 'a';
            for (i = 0; i < keys_total; i++) {
                char key[PMI2_MAX_KEYLEN];
                char val[PMI2_MAX_VALLEN] = "";
                sprintf(key, "RANK%d-key-%d", r, i);

                if (PMI2_SUCCESS != (rc = PMI2_KVS_Get(jobid, r, key, val, sizeof(val), &len))) {
                    log_fatal("PMI2_KVS_Get [%s=?] %d\n", key, rc);
                    return rc;
                }

                log_info("PMI2_KVS_Get [rank=%d %s] %d\n", rank, key, rc);

                if (len != val_size) {
                    log_fatal("%d: failure on rank %d, key #%d: len mismatch:"
                            " %d instead of %d\n", rank, r, i, len, val_size);
                }

                for (j = 0; j < val_size; j++) {
                    if (val[j] != symb) {
                        log_fatal("%d: failure on rank %d, key #%d: value mismatch"
                                " at symb %d: \'%c\' instead of \'%c\'\n", rank,
                                r, i, j, val[j], symb);
                    }
                }
                symb++;
                if (symb > 'z') {
                    symb = 'a';
                }
            }
        }
        fence_cnt++;
    }

    return rc;
}