Ejemplo n.º 1
0
/*
 * init() is called when the plugin is loaded, before any other functions
 *	are called.  Put global initialization here.
 */
extern int init(void)
{
	verbose("%s loaded", plugin_name);
	return SLURM_SUCCESS;
}
Ejemplo n.º 2
0
/** check file descriptor count */
static void
checkrlimits(struct config_file* cfg)
{
#ifndef S_SPLINT_S
#ifdef HAVE_GETRLIMIT
	/* list has number of ports to listen to, ifs number addresses */
	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 + 
			(int)cfg->incoming_num_tcp:0));
	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
		((cfg->do_ip4 && !cfg->if_automatic?1:0) + 
		 (cfg->do_ip6?1:0)):cfg->num_ifs);
	size_t listen_num = list*listen_ifs;
	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
	size_t outtcpnum = cfg->outgoing_num_tcp;
	size_t misc = 4; /* logfile, pidfile, stdout... */
	size_t perthread_noudp = listen_num + outtcpnum + 
		2/*cmdpipe*/ + 2/*libevent*/ + misc; 
	size_t perthread = perthread_noudp + outudpnum;

#if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
	int numthread = 1; /* it forks */
#else
	int numthread = (cfg->num_threads?cfg->num_threads:1);
#endif
	size_t total = numthread * perthread + misc;
	size_t avail;
	struct rlimit rlim;

	if(total > 1024 && 
		strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
		log_warn("too many file descriptors requested. The builtin"
			"mini-event cannot handle more than 1024. Config "
			"for less fds or compile with libevent");
		if(numthread*perthread_noudp+15 > 1024)
			fatal_exit("too much tcp. not enough fds.");
		cfg->outgoing_num_ports = (int)((1024 
			- numthread*perthread_noudp 
			- 10 /* safety margin */) /numthread);
		log_warn("continuing with less udp ports: %u",
			cfg->outgoing_num_ports);
		total = 1024;
	}
	if(perthread > 64 && 
		strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
		log_err("too many file descriptors requested. The winsock"
			" event handler cannot handle more than 64 per "
			" thread. Config for less fds");
		if(perthread_noudp+2 > 64)
			fatal_exit("too much tcp. not enough fds.");
		cfg->outgoing_num_ports = (int)((64 
			- perthread_noudp 
			- 2/* safety margin */));
		log_warn("continuing with less udp ports: %u",
			cfg->outgoing_num_ports);
		total = numthread*(perthread_noudp+
			(size_t)cfg->outgoing_num_ports)+misc;
	}
	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
		log_warn("getrlimit: %s", strerror(errno));
		return;
	}
	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
		return;
	if((size_t)rlim.rlim_cur < total) {
		avail = (size_t)rlim.rlim_cur;
		rlim.rlim_cur = (rlim_t)(total + 10);
		rlim.rlim_max = (rlim_t)(total + 10);
#ifdef HAVE_SETRLIMIT
		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
			log_warn("setrlimit: %s", strerror(errno));
#endif
			log_warn("cannot increase max open fds from %u to %u",
				(unsigned)avail, (unsigned)total+10);
			/* check that calculation below does not underflow,
			 * with 15 as margin */
			if(numthread*perthread_noudp+15 > avail)
				fatal_exit("too much tcp. not enough fds.");
			cfg->outgoing_num_ports = (int)((avail 
				- numthread*perthread_noudp 
				- 10 /* safety margin */) /numthread);
			log_warn("continuing with less udp ports: %u",
				cfg->outgoing_num_ports);
			log_warn("increase ulimit or decrease threads, "
				"ports in config to remove this warning");
			return;
#ifdef HAVE_SETRLIMIT
		}
#endif
		verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
			(unsigned)avail, (unsigned)total+10);
	}
#else	
	(void)cfg;
#endif /* HAVE_GETRLIMIT */
#endif /* S_SPLINT_S */
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	job_desc_msg_t desc;
	resource_allocation_response_msg_t *alloc;
	time_t before, after;
	allocation_msg_thread_t *msg_thr;
	char **env = NULL, *cluster_name;
	int status = 0;
	int retries = 0;
	pid_t pid  = getpid();
	pid_t tpgid = 0;
	pid_t rc_pid = 0;
	int i, rc = 0;
	static char *msg = "Slurm job queue full, sleeping and retrying.";
	slurm_allocation_callbacks_t callbacks;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), logopt, 0, NULL);
	_set_exit_code();

	if (spank_init_allocator() < 0) {
		error("Failed to initialize plugin stack");
		exit(error_exit);
	}

	/* Be sure to call spank_fini when salloc exits
	 */
	if (atexit((void (*) (void)) spank_fini) < 0)
		error("Failed to register atexit handler for plugins: %m");


	if (initialize_and_process_args(argc, argv) < 0) {
		error("salloc parameter parsing");
		exit(error_exit);
	}
	/* reinit log with new verbosity (if changed by command line) */
	if (opt.verbose || opt.quiet) {
		logopt.stderr_level += opt.verbose;
		logopt.stderr_level -= opt.quiet;
		logopt.prefix_level = 1;
		log_alter(logopt, 0, NULL);
	}

	if (spank_init_post_opt() < 0) {
		error("Plugin stack post-option processing failed");
		exit(error_exit);
	}

	_set_spank_env();
	_set_submit_dir_env();
	if (opt.cwd && chdir(opt.cwd)) {
		error("chdir(%s): %m", opt.cwd);
		exit(error_exit);
	}

	if (opt.get_user_env_time >= 0) {
		bool no_env_cache = false;
		char *sched_params;
		char *user = uid_to_string(opt.uid);

		if (xstrcmp(user, "nobody") == 0) {
			error("Invalid user id %u: %m", (uint32_t)opt.uid);
			exit(error_exit);
		}

		sched_params = slurm_get_sched_params();
		no_env_cache = (sched_params &&
				strstr(sched_params, "no_env_cache"));
		xfree(sched_params);

		env = env_array_user_default(user,
					     opt.get_user_env_time,
					     opt.get_user_env_mode,
					     no_env_cache);
		xfree(user);
		if (env == NULL)
			exit(error_exit);    /* error already logged */
		_set_rlimits(env);
	}

	/*
	 * Job control for interactive salloc sessions: only if ...
	 *
	 * a) input is from a terminal (stdin has valid termios attributes),
	 * b) controlling terminal exists (non-negative tpgid),
	 * c) salloc is not run in allocation-only (--no-shell) mode,
	 * NOTE: d and e below are configuration dependent
	 * d) salloc runs in its own process group (true in interactive
	 *    shells that support job control),
	 * e) salloc has been configured at compile-time to support background
	 *    execution and is not currently in the background process group.
	 */
	if (tcgetattr(STDIN_FILENO, &saved_tty_attributes) < 0) {
		/*
		 * Test existence of controlling terminal (tpgid > 0)
		 * after first making sure stdin is not redirected.
		 */
	} else if ((tpgid = tcgetpgrp(STDIN_FILENO)) < 0) {
#ifdef HAVE_ALPS_CRAY
		verbose("no controlling terminal");
#else
		if (!opt.no_shell) {
			error("no controlling terminal: please set --no-shell");
			exit(error_exit);
		}
#endif
#ifdef SALLOC_RUN_FOREGROUND
	} else if ((!opt.no_shell) && (pid == getpgrp())) {
		if (tpgid == pid)
			is_interactive = true;
		while (tcgetpgrp(STDIN_FILENO) != pid) {
			if (!is_interactive) {
				error("Waiting for program to be placed in "
				      "the foreground");
				is_interactive = true;
			}
			killpg(pid, SIGTTIN);
		}
	}
#else
	} else if ((!opt.no_shell) && (getpgrp() == tcgetpgrp(STDIN_FILENO))) {
Ejemplo n.º 4
0
/*
 * read packets, try to authenticate the user and
 * return only if authentication is successful
 */
static void
do_authloop(Authctxt *authctxt)
{
	int authenticated = 0;
	u_int bits;
	Key *client_host_key;
	BIGNUM *n;
	char *client_user, *password;
	char info[1024];
	u_int dlen;
	u_int ulen;
	int prev, type = 0;
	struct passwd *pw = authctxt->pw;

	debug("Attempting authentication for %s%.100s.",
	    authctxt->valid ? "" : "illegal user ", authctxt->user);

	/* If the user has no password, accept authentication immediately. */
	if (options.password_authentication &&
#ifdef KRB5
	    (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
#endif
	    PRIVSEP(auth_password(authctxt, ""))) {
		auth_log(authctxt, 1, "without authentication", "");
		return;
	}

	/* Indicate that authentication is needed. */
	packet_start(SSH_SMSG_FAILURE);
	packet_send();
	packet_write_wait();

	client_user = NULL;

	for (;;) {
		/* default to fail */
		authenticated = 0;

		info[0] = '\0';

		/* Get a packet from the client. */
		prev = type;
		type = packet_read();

		/*
		 * If we started challenge-response authentication but the
		 * next packet is not a response to our challenge, release
		 * the resources allocated by get_challenge() (which would
		 * normally have been released by verify_response() had we
		 * received such a response)
		 */
		if (prev == SSH_CMSG_AUTH_TIS &&
		    type != SSH_CMSG_AUTH_TIS_RESPONSE)
			abandon_challenge_response(authctxt);

		/* Process the packet. */
		switch (type) {
		case SSH_CMSG_AUTH_RHOSTS_RSA:
			if (!options.rhosts_rsa_authentication) {
				verbose("Rhosts with RSA authentication disabled.");
				break;
			}
			/*
			 * Get client user name.  Note that we just have to
			 * trust the client; root on the client machine can
			 * claim to be any user.
			 */
			client_user = packet_get_string(&ulen);

			/* Get the client host key. */
			client_host_key = key_new(KEY_RSA1);
			bits = packet_get_int();
			packet_get_bignum(client_host_key->rsa->e);
			packet_get_bignum(client_host_key->rsa->n);

			if (bits != BN_num_bits(client_host_key->rsa->n))
				verbose("Warning: keysize mismatch for client_host_key: "
				    "actual %d, announced %d",
				    BN_num_bits(client_host_key->rsa->n), bits);
			packet_check_eom();

			authenticated = auth_rhosts_rsa(pw, client_user,
			    client_host_key);
			key_free(client_host_key);

			snprintf(info, sizeof info, " ruser %.100s", client_user);
			break;

		case SSH_CMSG_AUTH_RSA:
			if (!options.rsa_authentication) {
				verbose("RSA authentication disabled.");
				break;
			}
			/* RSA authentication requested. */
			if ((n = BN_new()) == NULL)
				fatal("do_authloop: BN_new failed");
			packet_get_bignum(n);
			packet_check_eom();
			authenticated = auth_rsa(pw, n);
			BN_clear_free(n);
			break;

		case SSH_CMSG_AUTH_PASSWORD:
			if (!options.password_authentication) {
				verbose("Password authentication disabled.");
				break;
			}
			/*
			 * Read user password.  It is in plain text, but was
			 * transmitted over the encrypted channel so it is
			 * not visible to an outside observer.
			 */
			password = packet_get_string(&dlen);
			packet_check_eom();

			/* Try authentication with the password. */
			authenticated = PRIVSEP(auth_password(authctxt, password));

			memset(password, 0, strlen(password));
			xfree(password);
			break;

		case SSH_CMSG_AUTH_TIS:
			debug("rcvd SSH_CMSG_AUTH_TIS");
			if (options.challenge_response_authentication == 1) {
				char *challenge = get_challenge(authctxt);
				if (challenge != NULL) {
					debug("sending challenge '%s'", challenge);
					packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
					packet_put_cstring(challenge);
					xfree(challenge);
					packet_send();
					packet_write_wait();
					continue;
				}
			}
			break;
		case SSH_CMSG_AUTH_TIS_RESPONSE:
			debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
			if (options.challenge_response_authentication == 1) {
				char *response = packet_get_string(&dlen);
				packet_check_eom();
				authenticated = verify_response(authctxt, response);
				memset(response, 'r', dlen);
				xfree(response);
			}
			break;

		default:
			/*
			 * Any unknown messages will be ignored (and failure
			 * returned) during authentication.
			 */
			logit("Unknown message during authentication: type %d", type);
			break;
		}
#ifdef BSD_AUTH
		if (authctxt->as) {
			auth_close(authctxt->as);
			authctxt->as = NULL;
		}
#endif
		if (!authctxt->valid && authenticated)
			fatal("INTERNAL ERROR: authenticated invalid user %s",
			    authctxt->user);

#ifdef _UNICOS
		if (authenticated && cray_access_denied(authctxt->user)) {
			authenticated = 0;
			fatal("Access denied for user %s.",authctxt->user);
		}
#endif /* _UNICOS */

#ifdef HAVE_CYGWIN
		if (authenticated &&
		    !check_nt_auth(type == SSH_CMSG_AUTH_PASSWORD, pw)) {
			packet_disconnect("Authentication rejected for uid %d.",
			pw == NULL ? -1 : pw->pw_uid);
			authenticated = 0;
		}
#else
		/* Special handling for root */
		if (authenticated && authctxt->pw->pw_uid == 0 &&
		    !auth_root_allowed(get_authname(type)))
			authenticated = 0;
#endif

#ifdef USE_PAM
		if (options.use_pam && authenticated && 
		    !PRIVSEP(do_pam_account()))
			authenticated = 0;
#endif

#ifdef SECURITY_COUNTS
	access__attempted(!authenticated, authctxt->user);
#endif

		/* Log before sending the reply */
		auth_log(authctxt, authenticated, get_authname(type), info);

		if (client_user != NULL) {
			xfree(client_user);
			client_user = NULL;
		}

		if (authenticated)
			return;

		if (authctxt->failures++ > AUTH_FAIL_MAX)
			packet_disconnect(AUTH_FAIL_MSG, authctxt->user);

		packet_start(SSH_SMSG_FAILURE);
		packet_send();
		packet_write_wait();
	}
}
Ejemplo n.º 5
0
/** answer query from the cache */
static int
answer_from_cache(struct worker* worker, struct query_info* qinfo,
	struct reply_info* rep, uint16_t id, uint16_t flags, 
	struct comm_reply* repinfo, struct edns_data* edns)
{
	uint32_t timenow = *worker->env.now;
	uint16_t udpsize = edns->udp_size;
	int secure;
	int must_validate = !(flags&BIT_CD) && worker->env.need_to_validate;
	/* see if it is possible */
	if(rep->ttl < timenow) {
		/* the rrsets may have been updated in the meantime.
		 * we will refetch the message format from the
		 * authoritative server 
		 */
		return 0;
	}
	if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
		return 0;
	/* locked and ids and ttls are OK. */
	/* check CNAME chain (if any) */
	if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type == 
		htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type == 
		htons(LDNS_RR_TYPE_DNAME))) {
		if(!reply_check_cname_chain(rep)) {
			/* cname chain invalid, redo iterator steps */
			verbose(VERB_ALGO, "Cache reply: cname chain broken");
		bail_out:
			rrset_array_unlock_touch(worker->env.rrset_cache, 
				worker->scratchpad, rep->ref, rep->rrset_count);
			regional_free_all(worker->scratchpad);
			return 0;
		}
	}
	/* check security status of the cached answer */
	if( rep->security == sec_status_bogus && must_validate) {
		/* BAD cached */
		edns->edns_version = EDNS_ADVERTISED_VERSION;
		edns->udp_size = EDNS_ADVERTISED_SIZE;
		edns->ext_rcode = 0;
		edns->bits &= EDNS_DO;
		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 
			qinfo, id, flags, edns);
		rrset_array_unlock_touch(worker->env.rrset_cache, 
			worker->scratchpad, rep->ref, rep->rrset_count);
		regional_free_all(worker->scratchpad);
		if(worker->stats.extended) {
			worker->stats.ans_bogus ++;
			worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
		}
		return 1;
	} else if( rep->security == sec_status_unchecked && must_validate) {
		verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
			"validation");
		goto bail_out; /* need to validate cache entry first */
	} else if(rep->security == sec_status_secure) {
		if(reply_all_rrsets_secure(rep))
			secure = 1;
		else	{
			if(must_validate) {
				verbose(VERB_ALGO, "Cache reply: secure entry"
					" changed status");
				goto bail_out; /* rrset changed, re-verify */
			}
			secure = 0;
		}
	} else	secure = 0;

	edns->edns_version = EDNS_ADVERTISED_VERSION;
	edns->udp_size = EDNS_ADVERTISED_SIZE;
	edns->ext_rcode = 0;
	edns->bits &= EDNS_DO;
	if(!reply_info_answer_encode(qinfo, rep, id, flags, 
		repinfo->c->buffer, timenow, 1, worker->scratchpad,
		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 
			qinfo, id, flags, edns);
	}
	/* cannot send the reply right now, because blocking network syscall
	 * is bad while holding locks. */
	rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
		rep->ref, rep->rrset_count);
	regional_free_all(worker->scratchpad);
	if(worker->stats.extended) {
		if(secure) worker->stats.ans_secure++;
		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
	}
	/* go and return this buffer to the client */
	return 1;
}
Ejemplo n.º 6
0
enum sec_status 
dnskey_verify_rrset_sig(struct regional* region, ldns_buffer* buf, 
	struct val_env* ve, uint32_t now,
        struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
        size_t dnskey_idx, size_t sig_idx,
	struct rbtree_t** sortree, int* buf_canon, char** reason)
{
	enum sec_status sec;
	uint8_t* sig;		/* RRSIG rdata */
	size_t siglen;
	size_t rrnum = rrset_get_count(rrset);
	uint8_t* signer;	/* rrsig signer name */
	size_t signer_len;
	unsigned char* sigblock; /* signature rdata field */
	unsigned int sigblock_len;
	uint16_t ktag;		/* DNSKEY key tag */
	unsigned char* key;	/* public key rdata field */
	unsigned int keylen;
	rrset_get_rdata(rrset, rrnum + sig_idx, &sig, &siglen);
	/* min length of rdatalen, fixed rrsig, root signer, 1 byte sig */
	if(siglen < 2+20) {
		verbose(VERB_QUERY, "verify: signature too short");
		*reason = "signature too short";
		return sec_status_bogus;
	}

	if(!(dnskey_get_flags(dnskey, dnskey_idx) & DNSKEY_BIT_ZSK)) {
		verbose(VERB_QUERY, "verify: dnskey without ZSK flag");
		*reason = "dnskey without ZSK flag";
		return sec_status_bogus; 
	}

	if(dnskey_get_protocol(dnskey, dnskey_idx) != LDNS_DNSSEC_KEYPROTO) { 
		/* RFC 4034 says DNSKEY PROTOCOL MUST be 3 */
		verbose(VERB_QUERY, "verify: dnskey has wrong key protocol");
		*reason = "dnskey has wrong protocolnumber";
		return sec_status_bogus;
	}

	/* verify as many fields in rrsig as possible */
	signer = sig+2+18;
	signer_len = dname_valid(signer, siglen-2-18);
	if(!signer_len) {
		verbose(VERB_QUERY, "verify: malformed signer name");
		*reason = "signer name malformed";
		return sec_status_bogus; /* signer name invalid */
	}
	if(!dname_subdomain_c(rrset->rk.dname, signer)) {
		verbose(VERB_QUERY, "verify: signer name is off-tree");
		*reason = "signer name off-tree";
		return sec_status_bogus; /* signer name offtree */
	}
	sigblock = (unsigned char*)signer+signer_len;
	if(siglen < 2+18+signer_len+1) {
		verbose(VERB_QUERY, "verify: too short, no signature data");
		*reason = "signature too short, no signature data";
		return sec_status_bogus; /* sig rdf is < 1 byte */
	}
	sigblock_len = (unsigned int)(siglen - 2 - 18 - signer_len);

	/* verify key dname == sig signer name */
	if(query_dname_compare(signer, dnskey->rk.dname) != 0) {
		verbose(VERB_QUERY, "verify: wrong key for rrsig");
		log_nametypeclass(VERB_QUERY, "RRSIG signername is", 
			signer, 0, 0);
		log_nametypeclass(VERB_QUERY, "the key name is", 
			dnskey->rk.dname, 0, 0);
		*reason = "signer name mismatches key name";
		return sec_status_bogus;
	}

	/* verify covered type */
	/* memcmp works because type is in network format for rrset */
	if(memcmp(sig+2, &rrset->rk.type, 2) != 0) {
		verbose(VERB_QUERY, "verify: wrong type covered");
		*reason = "signature covers wrong type";
		return sec_status_bogus;
	}
	/* verify keytag and sig algo (possibly again) */
	if((int)sig[2+2] != dnskey_get_algo(dnskey, dnskey_idx)) {
		verbose(VERB_QUERY, "verify: wrong algorithm");
		*reason = "signature has wrong algorithm";
		return sec_status_bogus;
	}
	ktag = htons(dnskey_calc_keytag(dnskey, dnskey_idx));
	if(memcmp(sig+2+16, &ktag, 2) != 0) {
		verbose(VERB_QUERY, "verify: wrong keytag");
		*reason = "signature has wrong keytag";
		return sec_status_bogus;
	}

	/* verify labels is in a valid range */
	if((int)sig[2+3] > dname_signame_label_count(rrset->rk.dname)) {
		verbose(VERB_QUERY, "verify: labelcount out of range");
		*reason = "signature labelcount out of range";
		return sec_status_bogus;
	}

	/* original ttl, always ok */

	if(!*buf_canon) {
		/* create rrset canonical format in buffer, ready for 
		 * signature */
		if(!rrset_canonical(region, buf, rrset, sig+2, 
			18 + signer_len, sortree)) {
			log_err("verify: failed due to alloc error");
			return sec_status_unchecked;
		}
		*buf_canon = 1;
	}

	/* check that dnskey is available */
	dnskey_get_pubkey(dnskey, dnskey_idx, &key, &keylen);
	if(!key) {
		verbose(VERB_QUERY, "verify: short DNSKEY RR");
		return sec_status_unchecked;
	}

	/* verify */
	sec = verify_canonrrset(buf, (int)sig[2+2],
		sigblock, sigblock_len, key, keylen, reason);
	
	if(sec == sec_status_secure) {
		/* check if TTL is too high - reduce if so */
		adjust_ttl(ve, now, rrset, sig+2+4, sig+2+8, sig+2+12);

		/* verify inception, expiration dates 
		 * Do this last so that if you ignore expired-sigs the
		 * rest is sure to be OK. */
		if(!check_dates(ve, now, sig+2+8, sig+2+12, reason)) {
			return sec_status_bogus;
		}
	}

	return sec;
}
void ConcurrentMergeScheduler::message(const String& message) {
    if (verbose() && !_writer.expired()) {
        IndexWriterPtr(_writer)->message(L"CMS: " + message);
    }
}
Ejemplo n.º 8
0
/*
 * Parses data buffer to a query, finds the correct answer 
 * and calls the given function for every packet to send.
 */
void
handle_query(uint8_t* inbuf, ssize_t inlen, struct entry* entries, int* count,
	enum transport_type transport, void (*sendfunc)(uint8_t*, size_t, void*),
	void* userdata, FILE* verbose_out)
{
	ldns_status status;
	ldns_pkt *query_pkt = NULL;
	ldns_pkt *answer_pkt = NULL;
	struct reply_packet *p;
	ldns_rr *query_rr = NULL;
	uint8_t *outbuf = NULL;
	size_t answer_size = 0;
	struct entry* entry = NULL;
	ldns_rdf *stop_command = ldns_dname_new_frm_str("server.stop.");

	status = ldns_wire2pkt(&query_pkt, inbuf, (size_t)inlen);
	if (status != LDNS_STATUS_OK) {
		verbose(1, "Got bad packet: %s\n", ldns_get_errorstr_by_id(status));
		ldns_rdf_free(stop_command);
		return;
	}
	
	query_rr = ldns_rr_list_rr(ldns_pkt_question(query_pkt), 0);
	verbose(1, "query %d: id %d: %s %d bytes: ", ++(*count), (int)ldns_pkt_id(query_pkt), 
		(transport==transport_tcp)?"TCP":"UDP", (int)inlen);
	if(verbose_out) ldns_rr_print(verbose_out, query_rr);
	if(verbose_out) ldns_pkt_print(verbose_out, query_pkt);

	if (ldns_rr_get_type(query_rr) == LDNS_RR_TYPE_TXT &&
	    ldns_rr_get_class(query_rr) == LDNS_RR_CLASS_CH &&
	    ldns_dname_compare(ldns_rr_owner(query_rr), stop_command) == 0) {
		exit(0);
        }
	
	/* fill up answer packet */
	entry = find_match(entries, query_pkt, transport);
	if(!entry || !entry->reply_list) {
		verbose(1, "no answer packet for this query, no reply.\n");
		ldns_pkt_free(query_pkt);
		ldns_rdf_free(stop_command);
		return;
	}
	for(p = entry->reply_list; p; p = p->next)
	{
		verbose(3, "Answer pkt:\n");
		if (p->reply_from_hex) {
			/* try to parse the hex packet, if it can be
			 * parsed, we can use adjust rules. if not,
			 * send packet literally */
			status = ldns_buffer2pkt_wire(&answer_pkt, p->reply_from_hex);
			if (status == LDNS_STATUS_OK) {
				adjust_packet(entry, answer_pkt, query_pkt);
				if(verbose_out) ldns_pkt_print(verbose_out, answer_pkt);
				status = ldns_pkt2wire(&outbuf, answer_pkt, &answer_size);
				verbose(2, "Answer packet size: %u bytes.\n", (unsigned int)answer_size);
				if (status != LDNS_STATUS_OK) {
					verbose(1, "Error creating answer: %s\n", ldns_get_errorstr_by_id(status));
					ldns_pkt_free(query_pkt);
					ldns_rdf_free(stop_command);
					return;
				}
				ldns_pkt_free(answer_pkt);
				answer_pkt = NULL;
			} else {
				verbose(3, "Could not parse hex data (%s), sending hex data directly.\n", ldns_get_errorstr_by_id(status));
				/* still try to adjust ID */
				answer_size = ldns_buffer_capacity(p->reply_from_hex);
				outbuf = LDNS_XMALLOC(uint8_t, answer_size);
				memcpy(outbuf, ldns_buffer_begin(p->reply_from_hex), answer_size);
				if(entry->copy_id) {
					ldns_write_uint16(outbuf, 
						ldns_pkt_id(query_pkt));
				}
			}
		} else {
			answer_pkt = ldns_pkt_clone(p->reply);
			adjust_packet(entry, answer_pkt, query_pkt);
			if(verbose_out) ldns_pkt_print(verbose_out, answer_pkt);
			status = ldns_pkt2wire(&outbuf, answer_pkt, &answer_size);
			verbose(1, "Answer packet size: %u bytes.\n", (unsigned int)answer_size);
			if (status != LDNS_STATUS_OK) {
				verbose(1, "Error creating answer: %s\n", ldns_get_errorstr_by_id(status));
				ldns_pkt_free(query_pkt);
				ldns_rdf_free(stop_command);
				return;
			}
			ldns_pkt_free(answer_pkt);
			answer_pkt = NULL;
		}
		if(p->packet_sleep) {
			verbose(3, "sleeping for next packet %d secs\n", 
				p->packet_sleep);
#ifdef HAVE_SLEEP
			sleep(p->packet_sleep);
#else
			Sleep(p->packet_sleep * 1000);
#endif
			verbose(3, "wakeup for next packet "
				"(slept %d secs)\n", p->packet_sleep);
		}
		sendfunc(outbuf, answer_size, userdata);
		LDNS_FREE(outbuf);
		outbuf = NULL;
		answer_size = 0;
	}
	ldns_pkt_free(query_pkt);
	ldns_rdf_free(stop_command);
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
	libmtd_t mtd_desc;
	struct mtd_dev_info mtd;
	int fd, clmpos = 0, clmlen = 8;
	unsigned long long start;
	unsigned int eb, eb_start, eb_cnt;
	int isNAND;
	int error = 0;
	off_t offset = 0;

	/*
	 * Process user arguments
	 */
	for (;;) {
		int option_index = 0;
		static const char *short_options = "jNqu";
		static const struct option long_options[] = {
			{"help", no_argument, 0, 0},
			{"version", no_argument, 0, 0},
			{"jffs2", no_argument, 0, 'j'},
			{"noskipbad", no_argument, 0, 'N'},
			{"quiet", no_argument, 0, 'q'},
			{"silent", no_argument, 0, 'q'},
			{"unlock", no_argument, 0, 'u'},

			{0, 0, 0, 0},
		};

		int c = getopt_long(argc, argv, short_options,
				long_options, &option_index);
		if (c == EOF)
			break;

		switch (c) {
		case 0:
			switch (option_index) {
			case 0:
				display_help();
				return 0;
			case 1:
				display_version();
				return 0;
			}
			break;
		case 'j':
			jffs2 = 1;
			break;
		case 'N':
			noskipbad = 1;
			break;
		case 'q':
			quiet = 1;
			break;
		case 'u':
			unlock = 1;
			break;
		case '?':
			error = 1;
			break;
		}
	}
	switch (argc - optind) {
	case 3:
		mtd_device = argv[optind];
		start = simple_strtoull(argv[optind + 1], &error);
		eb_cnt = simple_strtoul(argv[optind + 2], &error);
		break;
	default:
	case 0:
		errmsg("no MTD device specified");
	case 1:
		errmsg("no start erase block specified");
	case 2:
		errmsg("no erase block count specified");
		error = 1;
		break;
	}
	if (error)
		return errmsg("Try `--help' for more information");

	/*
	 * Locate MTD and prepare for erasure
	 */
	mtd_desc = libmtd_open();
	if (mtd_desc == NULL)
		return errmsg("can't initialize libmtd");

	if ((fd = open(mtd_device, O_RDWR)) < 0)
		return sys_errmsg("%s", mtd_device);

	if (mtd_get_dev_info(mtd_desc, mtd_device, &mtd) < 0)
		return errmsg("mtd_get_dev_info failed");

	eb_start = start / mtd.eb_size;

	isNAND = mtd.type == MTD_NANDFLASH ? 1 : 0;

	if (jffs2) {
		cleanmarker.magic = cpu_to_je16 (JFFS2_MAGIC_BITMASK);
		cleanmarker.nodetype = cpu_to_je16 (JFFS2_NODETYPE_CLEANMARKER);
		if (!isNAND)
			cleanmarker.totlen = cpu_to_je32(sizeof(cleanmarker));
		else {
			struct nand_oobinfo oobinfo;

			if (ioctl(fd, MEMGETOOBSEL, &oobinfo) != 0)
				return sys_errmsg("%s: unable to get NAND oobinfo", mtd_device);

			/* Check for autoplacement */
			if (oobinfo.useecc == MTD_NANDECC_AUTOPLACE) {
				/* Get the position of the free bytes */
				if (!oobinfo.oobfree[0][1])
					return errmsg(" Eeep. Autoplacement selected and no empty space in oob");
				clmpos = oobinfo.oobfree[0][0];
				clmlen = oobinfo.oobfree[0][1];
				if (clmlen > 8)
					clmlen = 8;
			} else {
				/* Legacy mode */
				switch (mtd.oob_size) {
					case 8:
						clmpos = 6;
						clmlen = 2;
						break;
					case 16:
						clmpos = 8;
						clmlen = 8;
						break;
					case 64:
						clmpos = 16;
						clmlen = 8;
						break;
				}
			}
			cleanmarker.totlen = cpu_to_je32(8);
		}
		cleanmarker.hdr_crc = cpu_to_je32(mtd_crc32(0, &cleanmarker, sizeof(cleanmarker) - 4));
	}

	/*
	 * Now do the actual erasing of the MTD device
	 */
	if (eb_cnt == 0)
		eb_cnt = (mtd.size / mtd.eb_size) - eb_start;

	for (eb = eb_start; eb < eb_start + eb_cnt; eb++) {
		offset = (off_t)eb * mtd.eb_size;

		if (!noskipbad) {
			int ret = mtd_is_bad(&mtd, fd, eb);
			if (ret > 0) {
				verbose(!quiet, "Skipping bad block at %08"PRIxoff_t, offset);
				continue;
			} else if (ret < 0) {
				if (errno == EOPNOTSUPP) {
					noskipbad = 1;
					if (isNAND)
						return errmsg("%s: Bad block check not available", mtd_device);
				} else
					return sys_errmsg("%s: MTD get bad block failed", mtd_device);
			}
		}

		show_progress(&mtd, offset, eb, eb_start, eb_cnt);

		if (unlock) {
			if (mtd_unlock(&mtd, fd, eb) != 0) {
				sys_errmsg("%s: MTD unlock failure", mtd_device);
				continue;
			}
		}

		if (mtd_erase(mtd_desc, &mtd, fd, eb) != 0) {
			sys_errmsg("%s: MTD Erase failure", mtd_device);
			continue;
		}

		/* format for JFFS2 ? */
		if (!jffs2)
			continue;

		/* write cleanmarker */
		if (isNAND) {
			if (mtd_write_oob(mtd_desc, &mtd, fd, (uint64_t)offset + clmpos, clmlen, &cleanmarker) != 0) {
				sys_errmsg("%s: MTD writeoob failure", mtd_device);
				continue;
			}
		} else {
			if (lseek(fd, offset, SEEK_SET) < 0) {
				sys_errmsg("%s: MTD lseek failure", mtd_device);
				continue;
			}
			if (write(fd, &cleanmarker, sizeof(cleanmarker)) != sizeof(cleanmarker)) {
				sys_errmsg("%s: MTD write failure", mtd_device);
				continue;
			}
		}
		verbose(!quiet, " Cleanmarker written at %"PRIxoff_t, offset);
	}
	show_progress(&mtd, offset, eb, eb_start, eb_cnt);
	bareverbose(!quiet, "\n");

	return 0;
}
Ejemplo n.º 10
0
/** match all of the packet */
static int
match_all(ldns_pkt* q, ldns_pkt* p, bool mttl)
{
	if(ldns_pkt_get_opcode(q) != ldns_pkt_get_opcode(p)) 
	{ verbose(3, "allmatch: opcode different"); return 0;}
	if(ldns_pkt_get_rcode(q) != ldns_pkt_get_rcode(p))
	{ verbose(3, "allmatch: rcode different"); return 0;}
	if(ldns_pkt_id(q) != ldns_pkt_id(p))
	{ verbose(3, "allmatch: id different"); return 0;}
	if(cmp_bool(ldns_pkt_qr(q), ldns_pkt_qr(p)) != 0)
	{ verbose(3, "allmatch: qr different"); return 0;}
	if(cmp_bool(ldns_pkt_aa(q), ldns_pkt_aa(p)) != 0)
	{ verbose(3, "allmatch: aa different"); return 0;}
	if(cmp_bool(ldns_pkt_tc(q), ldns_pkt_tc(p)) != 0)
	{ verbose(3, "allmatch: tc different"); return 0;}
	if(cmp_bool(ldns_pkt_rd(q), ldns_pkt_rd(p)) != 0)
	{ verbose(3, "allmatch: rd different"); return 0;}
	if(cmp_bool(ldns_pkt_cd(q), ldns_pkt_cd(p)) != 0)
	{ verbose(3, "allmatch: cd different"); return 0;}
	if(cmp_bool(ldns_pkt_ra(q), ldns_pkt_ra(p)) != 0)
	{ verbose(3, "allmatch: ra different"); return 0;}
	if(cmp_bool(ldns_pkt_ad(q), ldns_pkt_ad(p)) != 0)
	{ verbose(3, "allmatch: ad different"); return 0;}
	if(ldns_pkt_qdcount(q) != ldns_pkt_qdcount(p))
	{ verbose(3, "allmatch: qdcount different"); return 0;}
	if(ldns_pkt_ancount(q) != ldns_pkt_ancount(p))
	{ verbose(3, "allmatch: ancount different"); return 0;}
	if(ldns_pkt_nscount(q) != ldns_pkt_nscount(p))
	{ verbose(3, "allmatch: nscount different"); return 0;}
	if(ldns_pkt_arcount(q) != ldns_pkt_arcount(p))
	{ verbose(3, "allmatch: arcount different"); return 0;}
	if(!match_list(ldns_pkt_question(q), ldns_pkt_question(p), 0))
	{ verbose(3, "allmatch: qd section different"); return 0;}
	if(!match_list(ldns_pkt_answer(q), ldns_pkt_answer(p), mttl))
	{ verbose(3, "allmatch: an section different"); return 0;}
	if(!match_list(ldns_pkt_authority(q), ldns_pkt_authority(p), mttl))
	{ verbose(3, "allmatch: ar section different"); return 0;}
	if(!match_list(ldns_pkt_additional(q), ldns_pkt_additional(p), mttl)) 
	{ verbose(3, "allmatch: ns section different"); return 0;}
	return 1;
}
Ejemplo n.º 11
0
/* finds entry in list, or returns NULL */
struct entry* 
find_match(struct entry* entries, ldns_pkt* query_pkt,
	enum transport_type transport)
{
	struct entry* p = entries;
	ldns_pkt* reply = NULL;
	for(p=entries; p; p=p->next) {
		verbose(3, "comparepkt: ");
		reply = p->reply_list->reply;
		if(p->match_opcode && ldns_pkt_get_opcode(query_pkt) != 
			ldns_pkt_get_opcode(reply)) {
			verbose(3, "bad opcode\n");
			continue;
		}
		if(p->match_qtype && get_qtype(query_pkt) != get_qtype(reply)) {
			verbose(3, "bad qtype\n");
			continue;
		}
		if(p->match_qname) {
			if(!get_owner(query_pkt) || !get_owner(reply) ||
				ldns_dname_compare(
				get_owner(query_pkt), get_owner(reply)) != 0) {
				verbose(3, "bad qname\n");
				continue;
			}
		}
		if(p->match_subdomain) {
			if(!get_owner(query_pkt) || !get_owner(reply) ||
				(ldns_dname_compare(get_owner(query_pkt), 
				get_owner(reply)) != 0 &&
				!ldns_dname_is_subdomain(
				get_owner(query_pkt), get_owner(reply))))
			{
				verbose(3, "bad subdomain\n");
				continue;
			}
		}
		if(p->match_serial && get_serial(query_pkt) != p->ixfr_soa_serial) {
				verbose(3, "bad serial\n");
				continue;
		}
		if(p->match_do && !ldns_pkt_edns_do(query_pkt)) {
			verbose(3, "no DO bit set\n");
			continue;
		}
		if(p->match_noedns && ldns_pkt_edns(query_pkt)) {
			verbose(3, "bad; EDNS OPT present\n");
			continue;
		}
		if(p->match_ednsdata_raw && 
				!match_ednsdata(query_pkt, p->reply_list)) {
			verbose(3, "bad EDNS data match.\n");
			continue;
		}
		if(p->match_transport != transport_any && p->match_transport != transport) {
			verbose(3, "bad transport\n");
			continue;
		}
		if(p->match_all && !match_all(query_pkt, reply, p->match_ttl)) {
			verbose(3, "bad allmatch\n");
			continue;
		}
		verbose(3, "match!\n");
		return p;
	}
	return NULL;
}
Ejemplo n.º 12
0
/**
 * Helper for ports_open. Creates one interface (or NULL for default).
 * @param ifname: The interface ip address.
 * @param do_auto: use automatic interface detection.
 * 	If enabled, then ifname must be the wildcard name.
 * @param do_udp: if udp should be used.
 * @param do_tcp: if udp should be used.
 * @param hints: for getaddrinfo. family and flags have to be set by caller.
 * @param port: Port number to use (as string).
 * @param list: list of open ports, appended to, changed to point to list head.
 * @param rcv: receive buffer size for UDP
 * @param snd: send buffer size for UDP
 * @param ssl_port: ssl service port number
 * @param reuseport: try to set SO_REUSEPORT if nonNULL and true.
 * 	set to false on exit if reuseport failed due to no kernel support.
 * @return: returns false on error.
 */
static int
ports_create_if(const char* ifname, int do_auto, int do_udp, int do_tcp, 
	struct addrinfo *hints, const char* port, struct listen_port** list,
	size_t rcv, size_t snd, int ssl_port, int* reuseport)
{
	int s, noip6=0;
	if(!do_udp && !do_tcp)
		return 0;
	if(do_auto) {
		if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
			&noip6, rcv, snd, reuseport)) == -1) {
			if(noip6) {
				log_warn("IPv6 protocol not available");
				return 1;
			}
			return 0;
		}
		/* getting source addr packet info is highly non-portable */
		if(!set_recvpktinfo(s, hints->ai_family)) {
#ifndef USE_WINSOCK
			close(s);
#else
			closesocket(s);
#endif
			return 0;
		}
		if(!port_insert(list, s, listen_type_udpancil)) {
#ifndef USE_WINSOCK
			close(s);
#else
			closesocket(s);
#endif
			return 0;
		}
	} else if(do_udp) {
		/* regular udp socket */
		if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
			&noip6, rcv, snd, reuseport)) == -1) {
			if(noip6) {
				log_warn("IPv6 protocol not available");
				return 1;
			}
			return 0;
		}
		if(!port_insert(list, s, listen_type_udp)) {
#ifndef USE_WINSOCK
			close(s);
#else
			closesocket(s);
#endif
			return 0;
		}
	}
	if(do_tcp) {
		int is_ssl = ((strchr(ifname, '@') && 
			atoi(strchr(ifname, '@')+1) == ssl_port) ||
			(!strchr(ifname, '@') && atoi(port) == ssl_port));
		if((s = make_sock_port(SOCK_STREAM, ifname, port, hints, 1, 
			&noip6, 0, 0, reuseport)) == -1) {
			if(noip6) {
				/*log_warn("IPv6 protocol not available");*/
				return 1;
			}
			return 0;
		}
		if(is_ssl)
			verbose(VERB_ALGO, "setup TCP for SSL service");
		if(!port_insert(list, s, is_ssl?listen_type_ssl:
			listen_type_tcp)) {
#ifndef USE_WINSOCK
			close(s);
#else
			closesocket(s);
#endif
			return 0;
		}
	}
	return 1;
}
Ejemplo n.º 13
0
// ===========================================================================
// IIncidentListener interfaces overrides: incident handling
// ===========================================================================
void DataOnDemandSvc::handle ( const Incident& incident )
{

  Gaudi::Utils::LockedChrono timer ( m_timer_all , m_locked_all ) ;

  ++m_stat ;
  // proper incident type?
  if ( incident.type() != m_trapType ) { return ; }             // RETURN
  const DataIncident* inc = dynamic_cast<const DataIncident*>(&incident);
  if ( 0 == inc                      ) { return ; }             // RETURN
  // update if needed!
  if ( m_updateRequired ) { update() ; }

  if ( MSG::VERBOSE >= outputLevel() )
  {
    verbose()
      << "Incident: [" << incident.type   () << "] "
      << " = "         << incident.source ()
      << " Location:"  << inc->tag()         << endmsg;
  }
  // ==========================================================================
  // const std::string& tag = inc->tag();
  Gaudi::StringKey tag ( inc->tag() ) ;
  // ==========================================================================
  NodeMap::iterator icl = m_nodes.find ( tag ) ;
  if ( icl != m_nodes.end() )
  {
    StatusCode sc = execHandler ( tag , icl->second ) ;
    if ( sc.isSuccess() ) { ++m_statNode ; }
    return ;                                                        // RETURN
  }
  // ==========================================================================
  AlgMap::iterator ialg = m_algs.find ( tag ) ;
  if ( ialg != m_algs.end() )
  {
    StatusCode sc = execHandler ( tag , ialg->second ) ;
    if ( sc.isSuccess() ) { ++m_statAlg ; }
    return ;                                                        // RETURN
  }
  // ==========================================================================
  // Fall back on the tools
  if (m_toolSvc) {
    if (MSG::VERBOSE >= outputLevel())
      verbose() << "Try to find mapping with mapping tools" << endmsg;
    Finder finder(no_prefix(inc->tag(), m_prefix), m_nodeMappers, m_algMappers);
    //  - try the node mappers
    std::string node = finder.node();
    if (isGood(node)) {
      // if one is found update the internal node mapping and try again.
      if (MSG::VERBOSE >= outputLevel())
        verbose() << "Found Node handler: " << node << endmsg;
      i_setNodeHandler(inc->tag(), node);
      handle(incident);
      --m_stat; // avoid double counting because of recursion
      return;
    }
    //  - try alg mappings
    Gaudi::Utils::TypeNameString alg = finder.alg();
    if (isGood(alg)) {
      // we got an algorithm, update alg map and try to handle again
      if (MSG::VERBOSE >= outputLevel())
        verbose() << "Found Algorithm handler: " << alg << endmsg;
      i_setAlgHandler(inc->tag(), alg).ignore();
      handle(incident);
      --m_stat; // avoid double counting because of recursion
      return;
    }
  }
}
Ejemplo n.º 14
0
void L2OrthoHP::adapt(double thr, int strat, bool h_only, bool iso_only, double conv_exp, int max_order)
{

  if (!have_errors)
    error("Element errors have to be calculated first, see calc_error().");


  int i, j;
  Mesh* mesh[10];
  for (j = 0; j < num; j++) {
    mesh[j] = spaces[j]->get_mesh();
    rsln[j]->set_quad_2d(&g_quad_2d_std);
    rsln[j]->enable_transform(false);
  }

  double err0 = 1000.0;
  double processed_error = 0.0;
  for (i = 0; i < nact; i++)
  {
    int comp = esort[i][1];
    int id = esort[i][0];
    double err = errors[comp][id];

    // first refinement strategy:
    // refine elements until prescribed amount of error is processed
    // if more elements have similar error refine all to keep the mesh symmetric
    if ((strat == 0) && (processed_error > sqrt(thr) * total_err) && fabs((err - err0)/err0) > 1e-3) break;

    // second refinement strategy:
    // refine all elements whose error is bigger than some portion of maximal error
    if ((strat == 1) && (err < thr * errors[esort[0][1]][esort[0][0]])) break;

    Element* e;
    e = mesh[comp]->get_element(id);
    int split = 0;
    int p[4];
    int current = spaces[comp]->get_element_order(id);

    //verbose("Refining element #%d, Component #%d, Error %g%%", e_id, comp, errors[comp][e_id]);

    if (h_only && iso_only)
      p[0] = p[1] = p[2] = p[3] = current;
    else
      get_optimal_refinement(e, current, rsln[comp], split, p, h_only, iso_only, conv_exp, max_order);

    //apply found division
    if (split < 0) {
      spaces[comp]->set_element_order(id, p[0]);
    }
    else if (split == 0) {
      mesh[comp]->refine_element(id);
      for (j = 0; j < 4; j++)
        spaces[comp]->set_element_order(e->sons[j]->id, p[j]);
    }
    else {
      mesh[comp]->refine_element(id, split);
      for (j = 0; j < 2; j++)
        spaces[comp]->set_element_order(e->sons[ (split == 1) ? j : j+2 ]->id, p[j]);
    }

    err0 = err;
    processed_error += err;
  }

  for (j = 0; j < num; j++)
    rsln[j]->enable_transform(true);


  verbose("Refined %d elements.", i);
  have_errors = false;
}
Ejemplo n.º 15
0
static struct exonInfo *buildGIList(char *database, struct genePred *pred, 
    char *mafTable, unsigned options)
{
struct exonInfo *giList = NULL;
unsigned *exonStart = pred->exonStarts;
unsigned *lastStart = &exonStart[pred->exonCount];
unsigned *exonEnd = pred->exonEnds;
int *frames = pred->exonFrames;

boolean includeUtr = options & MAFGENE_INCLUDEUTR;

if (frames == NULL)
    {
    genePredAddExonFrames(pred);
    frames = pred->exonFrames;
    }

assert(frames != NULL);

int start = 0;


/* first skip 5' UTR if the includeUtr option is not set */
if (!includeUtr) 
    {
    for(; exonStart < lastStart; exonStart++, exonEnd++, frames++)
       {
       int size = *exonEnd - *exonStart;

       if (*exonStart + size > pred->cdsStart)
       	   break;
       }
    }

for(; exonStart < lastStart; exonStart++, exonEnd++, frames++)
    {
    struct exonInfo *gi;
    int thisStart = *exonStart;
    int thisEnd = *exonEnd;
    
    if (!includeUtr) 
        {
        if (thisStart > pred->cdsEnd)
	    break;

        if (thisStart < pred->cdsStart)
	    thisStart = pred->cdsStart;


        if (thisEnd > pred->cdsEnd)
	    thisEnd = pred->cdsEnd;
        
	}
    int thisSize = thisEnd - thisStart;
    if (!includeUtr)
        verbose(3, "in %d %d cds %d %d\n",*exonStart,*exonEnd, thisStart, thisEnd);
    AllocVar(gi);
    gi->frame = *frames;
    gi->name = pred->name;
    gi->ali = getAliForRange(database, mafTable, pred->chrom, 
	thisStart, thisEnd);
    gi->chromStart = thisStart;
    gi->chromEnd = thisEnd;
    gi->exonStart = start;
    gi->exonSize = thisSize;
    verbose(3, "exon size %d\n", thisSize);
    gi->strand = pred->strand[0];
    start += gi->exonSize;
    slAddHead(&giList, gi);
 
    if (!includeUtr) 
        {
        if (thisEnd == pred->cdsEnd)
	    break;
        }
    }
slReverse(&giList);

return giList;
}
Ejemplo n.º 16
0
int
main (int argc, char** argv)
{
  gint total = 0;
  gint passed = 0;
  gint failed = 0;
  gint i;

  for (i = 1; i < argc; i++) 
      if (strcmp ("--noisy", argv[i]) == 0)
	noisy = TRUE;

  TEST_COMPILATION("*A?B*", G_MATCH_ALL, "*A?B*", 3);
  TEST_COMPILATION("ABC*DEFGH", G_MATCH_ALL_TAIL, "HGFED*CBA", 8);
  TEST_COMPILATION("ABCDEF*GH", G_MATCH_ALL, "ABCDEF*GH", 8);
  TEST_COMPILATION("ABC**?***??**DEF*GH", G_MATCH_ALL, "ABC*???DEF*GH", 11);
  TEST_COMPILATION("*A?AA", G_MATCH_ALL_TAIL, "AA?A*", 4);
  TEST_COMPILATION("ABCD*", G_MATCH_HEAD, "ABCD", 4);
  TEST_COMPILATION("*ABCD", G_MATCH_TAIL, "ABCD", 4);
  TEST_COMPILATION("ABCDE", G_MATCH_EXACT, "ABCDE", 5);
  TEST_COMPILATION("A?C?E", G_MATCH_ALL, "A?C?E", 5);
  TEST_COMPILATION("*?x", G_MATCH_ALL_TAIL, "x?*", 2);
  TEST_COMPILATION("?*x", G_MATCH_ALL_TAIL, "x?*", 2);
  TEST_COMPILATION("*?*x", G_MATCH_ALL_TAIL, "x?*", 2);
  TEST_COMPILATION("x*??", G_MATCH_ALL_TAIL, "??*x", 3);

  TEST_EQUAL("*A?B*", "*A?B*", TRUE);
  TEST_EQUAL("A*BCD", "A*BCD", TRUE);
  TEST_EQUAL("ABCD*", "ABCD****", TRUE);
  TEST_EQUAL("A1*", "A1*", TRUE);
  TEST_EQUAL("*YZ", "*YZ", TRUE);
  TEST_EQUAL("A1x", "A1x", TRUE);
  TEST_EQUAL("AB*CD", "AB**CD", TRUE);
  TEST_EQUAL("AB*?*CD", "AB*?CD", TRUE);
  TEST_EQUAL("AB*?CD", "AB?*CD", TRUE);
  TEST_EQUAL("AB*CD", "AB*?*CD", FALSE);
  TEST_EQUAL("ABC*", "ABC?", FALSE);

  TEST_MATCH("*x", "x", TRUE);
  TEST_MATCH("*x", "xx", TRUE);
  TEST_MATCH("*x", "yyyx", TRUE);
  TEST_MATCH("*x", "yyxy", FALSE);
  TEST_MATCH("?x", "x", FALSE);
  TEST_MATCH("?x", "xx", TRUE);
  TEST_MATCH("?x", "yyyx", FALSE);
  TEST_MATCH("?x", "yyxy", FALSE);
  TEST_MATCH("*?x", "xx", TRUE);
  TEST_MATCH("?*x", "xx", TRUE);
  TEST_MATCH("*?x", "x", FALSE);
  TEST_MATCH("?*x", "x", FALSE);
  TEST_MATCH("*?*x", "yx", TRUE);
  TEST_MATCH("*?*x", "xxxx", TRUE);
  TEST_MATCH("x*??", "xyzw", TRUE);
  TEST_MATCH("*x", "\xc3\x84x", TRUE);
  TEST_MATCH("?x", "\xc3\x84x", TRUE);
  TEST_MATCH("??x", "\xc3\x84x", FALSE);
  TEST_MATCH("ab\xc3\xa4\xc3\xb6", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab\xc3\xa4\xc3\xb6", "abao", FALSE);
  TEST_MATCH("ab?\xc3\xb6", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab?\xc3\xb6", "abao", FALSE);
  TEST_MATCH("ab\xc3\xa4?", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab\xc3\xa4?", "abao", FALSE);
  TEST_MATCH("ab??", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab*", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab*\xc3\xb6", "ab\xc3\xa4\xc3\xb6", TRUE);
  TEST_MATCH("ab*\xc3\xb6", "aba\xc3\xb6x\xc3\xb6", TRUE);
  TEST_MATCH("", "abc", FALSE);

  TEST_MATCH("", "", TRUE);
  TEST_MATCH("abc", "abc", TRUE);
  TEST_MATCH("*fo1*bar", "yyyfoxfo1bar", TRUE);
  TEST_MATCH("12*fo1g*bar", "12yyyfoxfo1gbar", TRUE);
  TEST_MATCH("__________:*fo1g*bar", "__________:yyyfoxfo1gbar", TRUE);
  TEST_MATCH("*abc*cde", "abcde", FALSE);
  TEST_MATCH("*abc*cde", "abccde", TRUE);
  TEST_MATCH("*abc*cde", "abcxcde", TRUE);
  TEST_MATCH("*abc*?cde", "abccde", FALSE);
  TEST_MATCH("*abc*?cde", "abcxcde", TRUE);
  TEST_MATCH("*abc*def", "abababcdededef", TRUE);
  TEST_MATCH("*abc*def", "abcbcbcdededef", TRUE);
  TEST_MATCH("*acbc*def", "acbcbcbcdededef", TRUE);
  TEST_MATCH("*a?bc*def", "acbcbcbcdededef", TRUE);
  TEST_MATCH("*abc*def", "bcbcbcdefdef", FALSE);
  TEST_MATCH("*abc*def*ghi", "abcbcbcbcbcbcdefefdefdefghi", TRUE);
  TEST_MATCH("*abc*def*ghi", "bcbcbcbcbcbcdefdefdefdefghi", FALSE);
  TEST_MATCH("_1_2_3_4_5_6_7_8_9_0_1_2_3_4_5_*abc*def*ghi", "_1_2_3_4_5_6_7_8_9_0_1_2_3_4_5_abcbcbcbcbcbcdefefdefdefghi", TRUE);
  TEST_MATCH("fooooooo*a*bc", "fooooooo_a_bd_a_bc", TRUE);
    
  verbose ("\n%u tests passed, %u failed\n", passed, failed);

  return failed;
}
Ejemplo n.º 17
0
/**
 * Read a BIND9 like files with trust anchors in named.conf format.
 * Performs wildcard processing of name.
 * @param anchors: anchor storage.
 * @param buffer: parsing buffer.
 * @param pat: pattern string. (can be wildcarded)
 * @return false on error.
 */
static int
anchor_read_bind_file_wild(struct val_anchors* anchors, sldns_buffer* buffer,
	const char* pat)
{
#ifdef HAVE_GLOB
	glob_t g;
	size_t i;
	int r, flags;
	if(!strchr(pat, '*') && !strchr(pat, '?') && !strchr(pat, '[') && 
		!strchr(pat, '{') && !strchr(pat, '~')) {
		return anchor_read_bind_file(anchors, buffer, pat);
	}
	verbose(VERB_QUERY, "wildcard found, processing %s", pat);
	flags = 0 
#ifdef GLOB_ERR
		| GLOB_ERR
#endif
#ifdef GLOB_NOSORT
		| GLOB_NOSORT
#endif
#ifdef GLOB_BRACE
		| GLOB_BRACE
#endif
#ifdef GLOB_TILDE
		| GLOB_TILDE
#endif
	;
	memset(&g, 0, sizeof(g));
	r = glob(pat, flags, NULL, &g);
	if(r) {
		/* some error */
		if(r == GLOB_NOMATCH) {
			verbose(VERB_QUERY, "trusted-keys-file: "
				"no matches for %s", pat);
			return 1;
		} else if(r == GLOB_NOSPACE) {
			log_err("wildcard trusted-keys-file %s: "
				"pattern out of memory", pat);
		} else if(r == GLOB_ABORTED) {
			log_err("wildcard trusted-keys-file %s: expansion "
				"aborted (%s)", pat, strerror(errno));
		} else {
			log_err("wildcard trusted-keys-file %s: expansion "
				"failed (%s)", pat, strerror(errno));
		}
		/* ignore globs that yield no files */
		return 1; 
	}
	/* process files found, if any */
	for(i=0; i<(size_t)g.gl_pathc; i++) {
		if(!anchor_read_bind_file(anchors, buffer, g.gl_pathv[i])) {
			log_err("error reading wildcard "
				"trusted-keys-file: %s", g.gl_pathv[i]);
			globfree(&g);
			return 0;
		}
	}
	globfree(&g);
	return 1;
#else /* not HAVE_GLOB */
	return anchor_read_bind_file(anchors, buffer, pat);
#endif /* HAVE_GLOB */
}
Ejemplo n.º 18
0
void
load_hostkeys(struct hostkeys *hostkeys, const char *host, const char *path)
{
	FILE *f;
	char line[8192];
	u_long linenum = 0, num_loaded = 0;
	char *cp, *cp2, *hashed_host;
	HostkeyMarker marker;
	Key *key;
	int kbits;

	if ((f = fopen(path, "r")) == NULL)
		return;
	debug3("%s: loading entries for host \"%.100s\" from file \"%s\"",
	    __func__, host, path);
	while (read_keyfile_line(f, path, line, sizeof(line), &linenum) == 0) {
		cp = line;

		/* Skip any leading whitespace, comments and empty lines. */
		for (; *cp == ' ' || *cp == '\t'; cp++)
			;
		if (!*cp || *cp == '#' || *cp == '\n')
			continue;

		if ((marker = check_markers(&cp)) == MRK_ERROR) {
			verbose("%s: invalid marker at %s:%lu",
			    __func__, path, linenum);
			continue;
		}

		/* Find the end of the host name portion. */
		for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++)
			;

		/* Check if the host name matches. */
		if (match_hostname(host, cp, (u_int) (cp2 - cp)) != 1) {
			if (*cp != HASH_DELIM)
				continue;
			hashed_host = host_hash(host, cp, (u_int) (cp2 - cp));
			if (hashed_host == NULL) {
				debug("Invalid hashed host line %lu of %s",
				    linenum, path);
				continue;
			}
			if (strncmp(hashed_host, cp, (u_int) (cp2 - cp)) != 0)
				continue;
		}

		/* Got a match.  Skip host name. */
		cp = cp2;

		/*
		 * Extract the key from the line.  This will skip any leading
		 * whitespace.  Ignore badly formatted lines.
		 */
		key = key_new(KEY_UNSPEC);
		if (!hostfile_read_key(&cp, &kbits, key)) {
			key_free(key);
			key = key_new(KEY_RSA1);
			if (!hostfile_read_key(&cp, &kbits, key)) {
				key_free(key);
				continue;
			}
		}
		if (!hostfile_check_key(kbits, key, host, path, linenum))
			continue;

		debug3("%s: found %skey type %s in file %s:%lu", __func__,
		    marker == MRK_NONE ? "" :
		    (marker == MRK_CA ? "ca " : "revoked "),
		    key_type(key), path, linenum);
		hostkeys->entries = xrealloc(hostkeys->entries,
		    hostkeys->num_entries + 1, sizeof(*hostkeys->entries));
		hostkeys->entries[hostkeys->num_entries].host = xstrdup(host);
		hostkeys->entries[hostkeys->num_entries].file = xstrdup(path);
		hostkeys->entries[hostkeys->num_entries].line = linenum;
		hostkeys->entries[hostkeys->num_entries].key = key;
		hostkeys->entries[hostkeys->num_entries].marker = marker;
		hostkeys->num_entries++;
		num_loaded++;
	}
	debug3("%s: loaded %lu keys", __func__, num_loaded);
	fclose(f);
	return;
}	
Ejemplo n.º 19
0
/*
 * update_part - create or update a partition's configuration data
 * IN part_desc - description of partition changes
 * IN create_flag - create a new partition
 * RET 0 or an error code
 * global: part_list - list of partition entries
 *	last_part_update - update time of partition records
 */
extern int update_part (update_part_msg_t * part_desc, bool create_flag)
{
	int error_code;
	struct part_record *part_ptr;

	if (part_desc->name == NULL) {
		info("update_part: invalid partition name, NULL");
		return ESLURM_INVALID_PARTITION_NAME;
	}

	error_code = SLURM_SUCCESS;
	part_ptr = list_find_first(part_list, &list_find_part,
				   part_desc->name);

	if (create_flag) {
		if (part_ptr) {
			verbose("Duplicate partition name for create (%s)",
				part_desc->name);
			return ESLURM_INVALID_PARTITION_NAME;
		}
		info("update_part: partition %s being created",
		     part_desc->name);
		part_ptr = create_part_record();
		xfree(part_ptr->name);
		part_ptr->name = xstrdup(part_desc->name);
	} else {
		if (!part_ptr) {
			verbose("Update for partition not found (%s)",
				part_desc->name);
			return ESLURM_INVALID_PARTITION_NAME;
		}
	}

	last_part_update = time(NULL);

	if (part_desc->max_time != NO_VAL) {
		info("update_part: setting max_time to %u for partition %s",
		     part_desc->max_time, part_desc->name);
		part_ptr->max_time = part_desc->max_time;
	}

	if ((part_desc->default_time != NO_VAL) &&
	    (part_desc->default_time > part_ptr->max_time)) {
		info("update_part: DefaultTime would exceed MaxTime for "
		     "partition %s", part_desc->name);
	} else if (part_desc->default_time != NO_VAL) {
		info("update_part: setting default_time to %u "
		     "for partition %s",
		     part_desc->default_time, part_desc->name);
		part_ptr->default_time = part_desc->default_time;
	}

	if (part_desc->max_nodes != NO_VAL) {
		info("update_part: setting max_nodes to %u for partition %s",
		     part_desc->max_nodes, part_desc->name);
		part_ptr->max_nodes      = part_desc->max_nodes;
		part_ptr->max_nodes_orig = part_desc->max_nodes;
		select_g_alter_node_cnt(SELECT_SET_MP_CNT,
					&part_ptr->max_nodes);
	}

	if (part_desc->min_nodes != NO_VAL) {
		info("update_part: setting min_nodes to %u for partition %s",
		     part_desc->min_nodes, part_desc->name);
		part_ptr->min_nodes      = part_desc->min_nodes;
		part_ptr->min_nodes_orig = part_desc->min_nodes;
		select_g_alter_node_cnt(SELECT_SET_MP_CNT,
					&part_ptr->min_nodes);
	}

	if (part_desc->grace_time != NO_VAL) {
		info("update_part: setting grace_time to %u for partition %s",
		     part_desc->grace_time, part_desc->name);
		part_ptr->grace_time = part_desc->grace_time;
	}

	if (part_desc->flags & PART_FLAG_HIDDEN) {
		info("update_part: setting hidden for partition %s",
		     part_desc->name);
		part_ptr->flags |= PART_FLAG_HIDDEN;
	} else if (part_desc->flags & PART_FLAG_HIDDEN_CLR) {
		info("update_part: clearing hidden for partition %s",
		     part_desc->name);
		part_ptr->flags &= (~PART_FLAG_HIDDEN);
	}

	if (part_desc->flags & PART_FLAG_ROOT_ONLY) {
		info("update_part: setting root_only for partition %s",
		     part_desc->name);
		part_ptr->flags |= PART_FLAG_ROOT_ONLY;
	} else if (part_desc->flags & PART_FLAG_ROOT_ONLY_CLR) {
		info("update_part: clearing root_only for partition %s",
		     part_desc->name);
		part_ptr->flags &= (~PART_FLAG_ROOT_ONLY);
	}

	if (part_desc->flags & PART_FLAG_NO_ROOT) {
		info("update_part: setting no_root for partition %s",
		     part_desc->name);
		part_ptr->flags |= PART_FLAG_NO_ROOT;
	} else if (part_desc->flags & PART_FLAG_NO_ROOT_CLR) {
		info("update_part: clearing no_root for partition %s",
		     part_desc->name);
		part_ptr->flags &= (~PART_FLAG_NO_ROOT);
	}

	if (part_desc->flags & PART_FLAG_DEFAULT) {
		if (default_part_name == NULL) {
			info("update_part: setting default partition to %s",
			     part_desc->name);
		} else if (strcmp(default_part_name, part_desc->name) != 0) {
			info("update_part: changing default "
			     "partition from %s to %s",
			     default_part_name, part_desc->name);
		}
		xfree(default_part_name);
		default_part_name = xstrdup(part_desc->name);
		default_part_loc = part_ptr;
		part_ptr->flags |= PART_FLAG_DEFAULT;
	} else if ((part_desc->flags & PART_FLAG_DEFAULT_CLR) &&
		   (default_part_loc == part_ptr)) {
		info("update_part: clearing default partition from %s",
		     part_desc->name);
		xfree(default_part_name);
		default_part_loc = NULL;
		part_ptr->flags &= (~PART_FLAG_DEFAULT);
	}

	if (part_desc->state_up != (uint16_t) NO_VAL) {
		info("update_part: setting state_up to %u for partition %s",
		     part_desc->state_up, part_desc->name);
		part_ptr->state_up = part_desc->state_up;
	}

	if (part_desc->max_share != (uint16_t) NO_VAL) {
		uint16_t force = part_desc->max_share & SHARED_FORCE;
		uint16_t val = part_desc->max_share & (~SHARED_FORCE);
		char tmp_str[24];
		if (val == 0)
			snprintf(tmp_str, sizeof(tmp_str), "EXCLUSIVE");
		else if (force)
			snprintf(tmp_str, sizeof(tmp_str), "FORCE:%u", val);
		else if (val == 1)
			snprintf(tmp_str, sizeof(tmp_str), "NO");
		else
			snprintf(tmp_str, sizeof(tmp_str), "YES:%u", val);
		info("update_part: setting share to %s for partition %s",
		     tmp_str, part_desc->name);
		part_ptr->max_share = part_desc->max_share;
	}

	if (part_desc->preempt_mode != (uint16_t) NO_VAL) {
		uint16_t new_mode;
		new_mode = part_desc->preempt_mode & (~PREEMPT_MODE_GANG);
		if (new_mode <= PREEMPT_MODE_CANCEL) {
			info("update_part: setting preempt_mode to %s for "
			     "partition %s",
			     preempt_mode_string(new_mode), part_desc->name);
			part_ptr->preempt_mode = new_mode;
		} else {
			info("update_part: invalid preempt_mode %u", new_mode);
		}
	}

	if (part_desc->priority != (uint16_t) NO_VAL) {
		info("update_part: setting priority to %u for partition %s",
		     part_desc->priority, part_desc->name);
		part_ptr->priority = part_desc->priority;

		/* If the max_priority changes we need to change all
		 * the normalized priorities of all the other
		 * partitions. If not then just set this partition.
		 */
		if(part_ptr->priority > part_max_priority) {
			ListIterator itr = list_iterator_create(part_list);
			struct part_record *part2 = NULL;

			part_max_priority = part_ptr->priority;

			while((part2 = list_next(itr))) {
				part2->norm_priority = (double)part2->priority
					/ (double)part_max_priority;
			}
			list_iterator_destroy(itr);
		} else {
			part_ptr->norm_priority = (double)part_ptr->priority
				/ (double)part_max_priority;
		}
	}

	if (part_desc->allow_groups != NULL) {
		xfree(part_ptr->allow_groups);
		xfree(part_ptr->allow_uids);
		if ((strcasecmp(part_desc->allow_groups, "ALL") == 0) ||
		    (part_desc->allow_groups[0] == '\0')) {
			info("update_part: setting allow_groups to ALL for "
				"partition %s",
				part_desc->name);
		} else {
			part_ptr->allow_groups = part_desc->allow_groups;
			part_desc->allow_groups = NULL;
			info("update_part: setting allow_groups to %s for "
				"partition %s",
				part_ptr->allow_groups, part_desc->name);
			part_ptr->allow_uids =
				_get_groups_members(part_ptr->allow_groups);
			clear_group_cache();
		}
	}

	if (part_desc->allow_alloc_nodes != NULL) {
		xfree(part_ptr->allow_alloc_nodes);
		if ((part_desc->allow_alloc_nodes[0] == '\0') ||
		    (strcasecmp(part_desc->allow_alloc_nodes, "ALL") == 0)) {
			part_ptr->allow_alloc_nodes = NULL;
			info("update_part: setting allow_alloc_nodes to ALL"
			     " for partition %s",part_desc->name);
		}
		else {
			part_ptr->allow_alloc_nodes = part_desc->
						      allow_alloc_nodes;
			part_desc->allow_alloc_nodes = NULL;
			info("update_part: setting allow_alloc_nodes to %s for "
			     "partition %s",
			     part_ptr->allow_alloc_nodes, part_desc->name);
		}
	}
	if (part_desc->alternate != NULL) {
		xfree(part_ptr->alternate);
		if ((strcasecmp(part_desc->alternate, "NONE") == 0) ||
		    (part_desc->alternate[0] == '\0'))
			part_ptr->alternate = NULL;
		else
			part_ptr->alternate = xstrdup(part_desc->alternate);
		part_desc->alternate = NULL;
		info("update_part: setting alternate to %s for "
		     "partition %s",
		     part_ptr->alternate, part_desc->name);
	}

	if (part_desc->def_mem_per_cpu != NO_VAL) {
		char *key;
		uint32_t value;
		if (part_desc->def_mem_per_cpu & MEM_PER_CPU) {
			key = "DefMemPerCpu";
			value = part_desc->def_mem_per_cpu & (~MEM_PER_CPU);
		} else {
			key = "DefMemPerNode";
			value = part_desc->def_mem_per_cpu;
		}
		info("update_part: setting %s to %u for partition %s",
		     key, value, part_desc->name);
		part_ptr->def_mem_per_cpu = part_desc->def_mem_per_cpu;
	}

	if (part_desc->max_mem_per_cpu != NO_VAL) {
		char *key;
		uint32_t value;
		if (part_desc->max_mem_per_cpu & MEM_PER_CPU) {
			key = "MaxMemPerCpu";
			value = part_desc->max_mem_per_cpu & (~MEM_PER_CPU);
		} else {
			key = "MaxMemPerNode";
			value = part_desc->max_mem_per_cpu;
		}
		info("update_part: setting %s to %u for partition %s",
		     key, value, part_desc->name);
		part_ptr->max_mem_per_cpu = part_desc->max_mem_per_cpu;
	}

	if (part_desc->nodes != NULL) {
		char *backup_node_list = part_ptr->nodes;

		if (part_desc->nodes[0] == '\0')
			part_ptr->nodes = NULL;	/* avoid empty string */
		else {
			int i;
			part_ptr->nodes = xstrdup(part_desc->nodes);
			for (i=0; part_ptr->nodes[i]; i++) {
				if (isspace(part_ptr->nodes[i]))
					part_ptr->nodes[i] = ',';
			}
		}

		error_code = _build_part_bitmap(part_ptr);
		if (error_code) {
			xfree(part_ptr->nodes);
			part_ptr->nodes = backup_node_list;
		} else {
			info("update_part: setting nodes to %s "
			     "for partition %s",
			     part_ptr->nodes, part_desc->name);
			xfree(backup_node_list);
		}
	} else if (part_ptr->node_bitmap == NULL) {
		/* Newly created partition needs a bitmap, even if empty */
		part_ptr->node_bitmap = bit_alloc(node_record_count);
	}

	if (error_code == SLURM_SUCCESS) {
		slurm_sched_partition_change();	/* notify sched plugin */
		select_g_reconfigure();		/* notify select plugin too */
	}

	return error_code;
}
Ejemplo n.º 20
0
/**
 * Check a canonical sig+rrset and signature against a dnskey
 * @param buf: buffer with data to verify, the first rrsig part and the
 *	canonicalized rrset.
 * @param algo: DNSKEY algorithm.
 * @param sigblock: signature rdata field from RRSIG
 * @param sigblock_len: length of sigblock data.
 * @param key: public key data from DNSKEY RR.
 * @param keylen: length of keydata.
 * @param reason: bogus reason in more detail.
 * @return secure if verification succeeded, bogus on crypto failure,
 *	unchecked on format errors and alloc failures.
 */
enum sec_status
verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock,
                  unsigned int sigblock_len, unsigned char* key, unsigned int keylen,
                  char** reason)
{
    /* uses libNSS */
    /* large enough for the different hashes */
    unsigned char hash[HASH_LENGTH_MAX];
    unsigned char hash2[HASH_LENGTH_MAX*2];
    HASH_HashType htype = 0;
    SECKEYPublicKey* pubkey = NULL;
    SECItem secsig = {siBuffer, sigblock, sigblock_len};
    SECItem sechash = {siBuffer, hash, 0};
    SECStatus res;
    unsigned char* prefix = NULL; /* prefix for hash, RFC3110, RFC5702 */
    size_t prefixlen = 0;
    int err;

    if(!nss_setup_key_digest(algo, &pubkey, &htype, key, keylen,
                             &prefix, &prefixlen)) {
        verbose(VERB_QUERY, "verify: failed to setup key");
        *reason = "use of key for crypto failed";
        SECKEY_DestroyPublicKey(pubkey);
        return sec_status_bogus;
    }

#ifdef USE_DSA
    /* need to convert DSA, ECDSA signatures? */
    if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3)) {
        if(sigblock_len == 1+2*SHA1_LENGTH) {
            secsig.data ++;
            secsig.len --;
        } else {
            SECItem* p = DSAU_DecodeDerSig(&secsig);
            if(!p) {
                verbose(VERB_QUERY, "verify: failed DER decode");
                *reason = "signature DER decode failed";
                SECKEY_DestroyPublicKey(pubkey);
                return sec_status_bogus;
            }
            if(SECITEM_CopyItem(pubkey->arena, &secsig, p)) {
                log_err("alloc failure in DER decode");
                SECKEY_DestroyPublicKey(pubkey);
                SECITEM_FreeItem(p, PR_TRUE);
                return sec_status_unchecked;
            }
            SECITEM_FreeItem(p, PR_TRUE);
        }
    }
#endif /* USE_DSA */

    /* do the signature cryptography work */
    /* hash the data */
    sechash.len = HASH_ResultLen(htype);
    if(sechash.len > sizeof(hash)) {
        verbose(VERB_QUERY, "verify: hash too large for buffer");
        SECKEY_DestroyPublicKey(pubkey);
        return sec_status_unchecked;
    }
    if(HASH_HashBuf(htype, hash, (unsigned char*)sldns_buffer_begin(buf),
                    (unsigned int)sldns_buffer_limit(buf)) != SECSuccess) {
        verbose(VERB_QUERY, "verify: HASH_HashBuf failed");
        SECKEY_DestroyPublicKey(pubkey);
        return sec_status_unchecked;
    }
    if(prefix) {
        int hashlen = sechash.len;
        if(prefixlen+hashlen > sizeof(hash2)) {
            verbose(VERB_QUERY, "verify: hashprefix too large");
            SECKEY_DestroyPublicKey(pubkey);
            return sec_status_unchecked;
        }
        sechash.data = hash2;
        sechash.len = prefixlen+hashlen;
        memcpy(sechash.data, prefix, prefixlen);
        memmove(sechash.data+prefixlen, hash, hashlen);
    }

    /* verify the signature */
    res = PK11_Verify(pubkey, &secsig, &sechash, NULL /*wincx*/);
    SECKEY_DestroyPublicKey(pubkey);

    if(res == SECSuccess) {
        return sec_status_secure;
    }
    err = PORT_GetError();
    if(err != SEC_ERROR_BAD_SIGNATURE) {
        /* failed to verify */
        verbose(VERB_QUERY, "verify: PK11_Verify failed: %s",
                PORT_ErrorToString(err));
        /* if it is not supported, like ECC is removed, we get,
         * SEC_ERROR_NO_MODULE */
        if(err == SEC_ERROR_NO_MODULE)
            return sec_status_unchecked;
        /* but other errors are commonly returned
         * for a bad signature from NSS.  Thus we return bogus,
         * not unchecked */
        *reason = "signature crypto failed";
        return sec_status_bogus;
    }
    verbose(VERB_QUERY, "verify: signature mismatch: %s",
            PORT_ErrorToString(err));
    *reason = "signature crypto failed";
    return sec_status_bogus;
}
Ejemplo n.º 21
0
/** This function implements a callback from the nuclear data
    library modules.  The arguments for this function are the data as
    read from the library (Note that single precision is sufficient
    for library data).  These data are copied into
    NuclearData::nPaths, NuclearData::E, NuclearData::relations,
    NuclearData::emitted, NuclearData::paths, NuclearData::D[ngroups],
    and NuclearData::single respectively. */
void NuclearData::setData(int numRxns, float* radE, int* daugKza, 
			  char** emissions, float** xSection, 
			  float thalf, float *totalXSection)
{
  int gNum, rxnNum, totalRxnNum=-1;
  
  verbose(4,"Setting NuclearData members.");

  cleanUp();

  /* set dimensions */
  nPaths = numRxns;
  origNPaths = nPaths;

  if (nPaths < 0)
    return;

  /* only need relations and emitted if nPaths > 0 */
  if (nPaths > 0)
    {
      relations = new int[nPaths];
      memCheck(relations,"NuclearData::setData(...) : relations");
      
      emitted = new char*[nPaths];
      memCheck(emitted,"NuclearData::setData(...) : emitted");
    }

  paths = new double*[nPaths+1];
  memCheck(paths,"NuclearData::setData(...) : paths");

  E[0] = radE[0];  
  E[1] = radE[1];  
  E[2] = radE[2];

  /* initialize total x-sections */

  /* total of all paths */
  paths[nPaths] = new double[nGroups+1];
  memCheck(paths[nPaths],"NuclearData::setData(...) : paths[n]");
  for (gNum=0;gNum<nGroups;gNum++)
    paths[nPaths][gNum] = 0;

  /* if we are passed a total xsection (we must be in reverse mode) */
  if ( (NuclearData::mode == MODE_REVERSE) && (totalXSection != NULL) )
    {  
      delete[] single;
      single = NULL;
      P = NULL;

      single = new double[nGroups+1];
      for (gNum=0;gNum<nGroups;gNum++)
	single[gNum] = totalXSection[gNum]*1e-24;
      D = single;
    }
  else
    D = paths[nPaths];

  //For FEINDLib, a value of thalf is "inf" for a stable isotope. D[nGroups] will be re-initialized. 
  if (thalf>0)
    D[nGroups] = log(2.0)/thalf;
  else
    D[nGroups] = 0;

  /* setup each reaction */
  if ( (NuclearData::mode == MODE_REVERSE) || (totalXSection == NULL) ) // ALARALib and ADJLib always yield "true"
    for (rxnNum=0;rxnNum<nPaths;rxnNum++)
      {
        debug(4,"Copying reaction %d with %d groups.",rxnNum,nGroups+1);
        relations[rxnNum] = daugKza[rxnNum];
        /* log location of total reaction */
        if (daugKza[rxnNum] == 0)
	  totalRxnNum = rxnNum;
        emitted[rxnNum] = new char[strlen(emissions[rxnNum])+1];
        memCheck(emitted[rxnNum],"NuclearData::setData(...) : emitted[n]");
        strcpy(emitted[rxnNum],emissions[rxnNum]);

        paths[rxnNum] = new double[nGroups+1];
        memCheck(paths[rxnNum],"NuclearData::setData(...) : paths[n]");

        for (gNum=0;gNum<nGroups;gNum++)
	  {
	    paths[rxnNum][gNum] = xSection[rxnNum][gNum]*1e-24;
	    if (strcmp(emitted[rxnNum],"x"))
	      paths[nPaths][gNum] += paths[rxnNum][gNum];
	  }
        paths[rxnNum][nGroups] = xSection[rxnNum][nGroups];
      }
  else //FIENDLib always comes here. It doesn't have a emitted particle implemented
    {
    for (rxnNum=0;rxnNum<nPaths;rxnNum++)
      {
        debug(4,"Copying reaction %d with %d groups.",rxnNum,nGroups+1);
        relations[rxnNum] = daugKza[rxnNum];
        /* log location of total reaction */
        if (daugKza[rxnNum] == 0)
	  totalRxnNum = rxnNum;
        emitted[rxnNum] = new char[strlen(emissions[rxnNum])+1];
        memCheck(emitted[rxnNum],"NuclearData::setData(...) : emitted[n]");
        strcpy(emitted[rxnNum],emissions[rxnNum]);

        paths[rxnNum] = new double[nGroups+1];
        memCheck(paths[rxnNum],"NuclearData::setData(...) : paths[n]");

        for (gNum=0;gNum<nGroups;gNum++)
	  {
	    paths[rxnNum][gNum] = xSection[rxnNum][gNum]*1e-24;
// 	    if (strcmp(emitted[rxnNum],"x"))
// 	      paths[nPaths][gNum] += paths[rxnNum][gNum];
	  }
        paths[rxnNum][nGroups] = xSection[rxnNum][nGroups];
      }

      //Initialize path[nPaths] with totalXSection
       for (gNum=0; gNum<nGroups;gNum++)
         paths[nPaths][gNum] = totalXSection[gNum]*1e-24;

       paths[nPaths][nGroups] = totalXSection[nGroups];
    }

  if (totalRxnNum>-1)
    {
      /* make sure that the decay constant is copied */
      paths[totalRxnNum][nGroups] = paths[nPaths][nGroups];

      /* check where D is pointing */
      if (D == paths[nPaths])
	D = paths[totalRxnNum];

      /* delete summation based total reaction rate */
      delete[] paths[nPaths];

      /* point nPaths to the totalRxnNum */
      paths[nPaths] = paths[totalRxnNum];

      /* delete the emitted entry for the total reaction rate */
      delete[] emitted[totalRxnNum];

      /* shift all channel reactions down by one */
      for (rxnNum=totalRxnNum;rxnNum<nPaths-1;rxnNum++)
	{
	  paths[rxnNum] = paths[rxnNum+1];
	  relations[rxnNum] = relations[rxnNum+1];
	  emitted[rxnNum] = emitted[rxnNum+1];
	}
      /* unpoint the last emitted */
      emitted[nPaths-1] = NULL;
      
      /* shift the total destruction rate down */
      nPaths--;
      paths[nPaths]=paths[nPaths+1];
      paths[nPaths+1] = NULL;
      
    }

  origNPaths = nPaths;

}
Ejemplo n.º 22
0
/**
 * Setup key and digest for verification. Adjust sig if necessary.
 *
 * @param algo: key algorithm
 * @param evp_key: EVP PKEY public key to create.
 * @param digest_type: digest type to use
 * @param key: key to setup for.
 * @param keylen: length of key.
 * @return false on failure.
 */
static int
setup_key_digest(int algo, EVP_PKEY** evp_key, const EVP_MD** digest_type,
                 unsigned char* key, size_t keylen)
{
#ifdef USE_DSA
    DSA* dsa;
#endif
    RSA* rsa;

    switch(algo) {
#ifdef USE_DSA
    case LDNS_DSA:
    case LDNS_DSA_NSEC3:
        *evp_key = EVP_PKEY_new();
        if(!*evp_key) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        dsa = sldns_key_buf2dsa_raw(key, keylen);
        if(!dsa) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_key_buf2dsa_raw failed");
            return 0;
        }
        if(EVP_PKEY_assign_DSA(*evp_key, dsa) == 0) {
            verbose(VERB_QUERY, "verify: "
                    "EVP_PKEY_assign_DSA failed");
            return 0;
        }
        *digest_type = EVP_dss1();

        break;
#endif /* USE_DSA */
    case LDNS_RSASHA1:
    case LDNS_RSASHA1_NSEC3:
#if defined(HAVE_EVP_SHA256) && defined(USE_SHA2)
    case LDNS_RSASHA256:
#endif
#if defined(HAVE_EVP_SHA512) && defined(USE_SHA2)
    case LDNS_RSASHA512:
#endif
        *evp_key = EVP_PKEY_new();
        if(!*evp_key) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        rsa = sldns_key_buf2rsa_raw(key, keylen);
        if(!rsa) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_key_buf2rsa_raw SHA failed");
            return 0;
        }
        if(EVP_PKEY_assign_RSA(*evp_key, rsa) == 0) {
            verbose(VERB_QUERY, "verify: "
                    "EVP_PKEY_assign_RSA SHA failed");
            return 0;
        }

        /* select SHA version */
#if defined(HAVE_EVP_SHA256) && defined(USE_SHA2)
        if(algo == LDNS_RSASHA256)
            *digest_type = EVP_sha256();
        else
#endif
#if defined(HAVE_EVP_SHA512) && defined(USE_SHA2)
            if(algo == LDNS_RSASHA512)
                *digest_type = EVP_sha512();
            else
#endif
                *digest_type = EVP_sha1();

        break;
    case LDNS_RSAMD5:
        *evp_key = EVP_PKEY_new();
        if(!*evp_key) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        rsa = sldns_key_buf2rsa_raw(key, keylen);
        if(!rsa) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_key_buf2rsa_raw MD5 failed");
            return 0;
        }
        if(EVP_PKEY_assign_RSA(*evp_key, rsa) == 0) {
            verbose(VERB_QUERY, "verify: "
                    "EVP_PKEY_assign_RSA MD5 failed");
            return 0;
        }
        *digest_type = EVP_md5();

        break;
#ifdef USE_GOST
    case LDNS_ECC_GOST:
        *evp_key = sldns_gost2pkey_raw(key, keylen);
        if(!*evp_key) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_gost2pkey_raw failed");
            return 0;
        }
        *digest_type = EVP_get_digestbyname("md_gost94");
        if(!*digest_type) {
            verbose(VERB_QUERY, "verify: "
                    "EVP_getdigest md_gost94 failed");
            return 0;
        }
        break;
#endif
#ifdef USE_ECDSA
    case LDNS_ECDSAP256SHA256:
        *evp_key = sldns_ecdsa2pkey_raw(key, keylen,
                                        LDNS_ECDSAP256SHA256);
        if(!*evp_key) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_ecdsa2pkey_raw failed");
            return 0;
        }
#ifdef USE_ECDSA_EVP_WORKAROUND
        *digest_type = &ecdsa_evp_256_md;
#else
        *digest_type = EVP_sha256();
#endif
        break;
    case LDNS_ECDSAP384SHA384:
        *evp_key = sldns_ecdsa2pkey_raw(key, keylen,
                                        LDNS_ECDSAP384SHA384);
        if(!*evp_key) {
            verbose(VERB_QUERY, "verify: "
                    "sldns_ecdsa2pkey_raw failed");
            return 0;
        }
#ifdef USE_ECDSA_EVP_WORKAROUND
        *digest_type = &ecdsa_evp_384_md;
#else
        *digest_type = EVP_sha384();
#endif
        break;
#endif /* USE_ECDSA */
    default:
        verbose(VERB_QUERY, "verify: unknown algorithm %d",
                algo);
        return 0;
    }
    return 1;
}
Ejemplo n.º 23
0
/** Report on memory usage by this thread and global */
static void
worker_mem_report(struct worker* ATTR_UNUSED(worker), 
	struct serviced_query* ATTR_UNUSED(cur_serv))
{
#ifdef UNBOUND_ALLOC_STATS
	/* debug func in validator module */
	size_t total, front, back, mesh, msg, rrset, infra, ac, superac;
	size_t me, iter, val;
	int i;
	if(verbosity < VERB_ALGO) 
		return;
	front = listen_get_mem(worker->front);
	back = outnet_get_mem(worker->back);
	msg = slabhash_get_mem(worker->env.msg_cache);
	rrset = slabhash_get_mem(&worker->env.rrset_cache->table);
	infra = infra_get_mem(worker->env.infra_cache);
	mesh = mesh_get_mem(worker->env.mesh);
	ac = alloc_get_mem(&worker->alloc);
	superac = alloc_get_mem(&worker->daemon->superalloc);
	iter = 0;
	val = 0;
	for(i=0; i<worker->env.mesh->mods.num; i++) {
		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
			mods.mod[i]->get_mem));
		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
			val += (*worker->env.mesh->mods.mod[i]->get_mem)
				(&worker->env, i);
		else	iter += (*worker->env.mesh->mods.mod[i]->get_mem)
				(&worker->env, i);
	}
	me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig)
		+ comm_point_get_mem(worker->cmd_com) 
		+ sizeof(worker->rndstate) 
		+ regional_get_mem(worker->scratchpad) 
		+ sizeof(*worker->env.scratch_buffer) 
		+ ldns_buffer_capacity(worker->env.scratch_buffer)
		+ forwards_get_mem(worker->env.fwds);
	if(cur_serv) {
		me += serviced_get_mem(cur_serv);
	}
	total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me;
	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
		"rrset=%u infra=%u iter=%u val=%u "
		"alloccache=%u globalalloccache=%u me=%u",
		(unsigned)total, (unsigned)front, (unsigned)back, 
		(unsigned)mesh, (unsigned)msg, (unsigned)rrset, 
		(unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)ac, 
		(unsigned)superac, (unsigned)me);
	debug_total_mem(total);
#else /* no UNBOUND_ALLOC_STATS */
	size_t val = 0;
	int i;
	if(verbosity < VERB_QUERY)
		return;
	for(i=0; i<worker->env.mesh->mods.num; i++) {
		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
			mods.mod[i]->get_mem));
		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
			val += (*worker->env.mesh->mods.mod[i]->get_mem)
				(&worker->env, i);
	}
	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u",
		(unsigned)slabhash_get_mem(worker->env.msg_cache),
		(unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
		(unsigned)infra_get_mem(worker->env.infra_cache),
		(unsigned)val);
#endif /* UNBOUND_ALLOC_STATS */
}
Ejemplo n.º 24
0
/**
 * Check a canonical sig+rrset and signature against a dnskey
 * @param buf: buffer with data to verify, the first rrsig part and the
 *	canonicalized rrset.
 * @param algo: DNSKEY algorithm.
 * @param sigblock: signature rdata field from RRSIG
 * @param sigblock_len: length of sigblock data.
 * @param key: public key data from DNSKEY RR.
 * @param keylen: length of keydata.
 * @param reason: bogus reason in more detail.
 * @return secure if verification succeeded, bogus on crypto failure,
 *	unchecked on format errors and alloc failures.
 */
enum sec_status
verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock,
                  unsigned int sigblock_len, unsigned char* key, unsigned int keylen,
                  char** reason)
{
    const EVP_MD *digest_type;
    EVP_MD_CTX* ctx;
    int res, dofree = 0, docrypto_free = 0;
    EVP_PKEY *evp_key = NULL;

    if(!setup_key_digest(algo, &evp_key, &digest_type, key, keylen)) {
        verbose(VERB_QUERY, "verify: failed to setup key");
        *reason = "use of key for crypto failed";
        EVP_PKEY_free(evp_key);
        return sec_status_bogus;
    }
#ifdef USE_DSA
    /* if it is a DSA signature in bind format, convert to DER format */
    if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) &&
    sigblock_len == 1+2*SHA_DIGEST_LENGTH) {
        if(!setup_dsa_sig(&sigblock, &sigblock_len)) {
            verbose(VERB_QUERY, "verify: failed to setup DSA sig");
            *reason = "use of key for DSA crypto failed";
            EVP_PKEY_free(evp_key);
            return sec_status_bogus;
        }
        docrypto_free = 1;
    }
#endif
#if defined(USE_ECDSA) && defined(USE_DSA)
    else
#endif
#ifdef USE_ECDSA
        if(algo == LDNS_ECDSAP256SHA256 || algo == LDNS_ECDSAP384SHA384) {
            /* EVP uses ASN prefix on sig, which is not in the wire data */
            if(!setup_ecdsa_sig(&sigblock, &sigblock_len)) {
                verbose(VERB_QUERY, "verify: failed to setup ECDSA sig");
                *reason = "use of signature for ECDSA crypto failed";
                EVP_PKEY_free(evp_key);
                return sec_status_bogus;
            }
            dofree = 1;
        }
#endif /* USE_ECDSA */

    /* do the signature cryptography work */
#ifdef HAVE_EVP_MD_CTX_NEW
    ctx = EVP_MD_CTX_new();
#else
    ctx = (EVP_MD_CTX*)malloc(sizeof(*ctx));
    if(ctx) EVP_MD_CTX_init(ctx);
#endif
    if(!ctx) {
        log_err("EVP_MD_CTX_new: malloc failure");
        EVP_PKEY_free(evp_key);
        if(dofree) free(sigblock);
        else if(docrypto_free) OPENSSL_free(sigblock);
        return sec_status_unchecked;
    }
    if(EVP_VerifyInit(ctx, digest_type) == 0) {
        verbose(VERB_QUERY, "verify: EVP_VerifyInit failed");
        EVP_MD_CTX_destroy(ctx);
        EVP_PKEY_free(evp_key);
        if(dofree) free(sigblock);
        else if(docrypto_free) OPENSSL_free(sigblock);
        return sec_status_unchecked;
    }
    if(EVP_VerifyUpdate(ctx, (unsigned char*)sldns_buffer_begin(buf),
                        (unsigned int)sldns_buffer_limit(buf)) == 0) {
        verbose(VERB_QUERY, "verify: EVP_VerifyUpdate failed");
        EVP_MD_CTX_destroy(ctx);
        EVP_PKEY_free(evp_key);
        if(dofree) free(sigblock);
        else if(docrypto_free) OPENSSL_free(sigblock);
        return sec_status_unchecked;
    }

    res = EVP_VerifyFinal(ctx, sigblock, sigblock_len, evp_key);
#ifdef HAVE_EVP_MD_CTX_NEW
    EVP_MD_CTX_destroy(ctx);
#else
    EVP_MD_CTX_cleanup(ctx);
    free(ctx);
#endif
    EVP_PKEY_free(evp_key);

    if(dofree) free(sigblock);
    else if(docrypto_free) OPENSSL_free(sigblock);

    if(res == 1) {
        return sec_status_secure;
    } else if(res == 0) {
        verbose(VERB_QUERY, "verify: signature mismatch");
        *reason = "signature crypto failed";
        return sec_status_bogus;
    }

    log_crypto_error("verify:", ERR_get_error());
    return sec_status_unchecked;
}
Ejemplo n.º 25
0
int 
worker_handle_request(struct comm_point* c, void* arg, int error,
	struct comm_reply* repinfo)
{
	struct worker* worker = (struct worker*)arg;
	int ret;
	hashvalue_t h;
	struct lruhash_entry* e;
	struct query_info qinfo;
	struct edns_data edns;
	enum acl_access acl;

	if(error != NETEVENT_NOERROR) {
		/* some bad tcp query DNS formats give these error calls */
		verbose(VERB_ALGO, "handle request called with err=%d", error);
		return 0;
	}
	acl = acl_list_lookup(worker->daemon->acl, &repinfo->addr, 
		repinfo->addrlen);
	if(acl == acl_deny) {
		comm_point_drop_reply(repinfo);
		if(worker->stats.extended)
			worker->stats.unwanted_queries++;
		return 0;
	} else if(acl == acl_refuse) {
		ldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
		ldns_buffer_write_at(c->buffer, 4, 
			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), 
			LDNS_RCODE_REFUSED);
		log_addr(VERB_ALGO, "refused query from",
			&repinfo->addr, repinfo->addrlen);
		log_buf(VERB_ALGO, "refuse", c->buffer);
		if(worker->stats.extended)
			worker->stats.unwanted_queries++;
		return 1;
	}
	if((ret=worker_check_request(c->buffer, worker)) != 0) {
		verbose(VERB_ALGO, "worker check request: bad query.");
		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
		if(ret != -1) {
			LDNS_QR_SET(ldns_buffer_begin(c->buffer));
			LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), ret);
			return 1;
		}
		comm_point_drop_reply(repinfo);
		return 0;
	}
	worker->stats.num_queries++;
	/* see if query is in the cache */
	if(!query_info_parse(&qinfo, c->buffer)) {
		verbose(VERB_ALGO, "worker parse request: formerror.");
		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
		ldns_buffer_rewind(c->buffer);
		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), 
			LDNS_RCODE_FORMERR);
		server_stats_insrcode(&worker->stats, c->buffer);
		return 1;
	}
	if(qinfo.qtype == LDNS_RR_TYPE_AXFR || 
		qinfo.qtype == LDNS_RR_TYPE_IXFR) {
		verbose(VERB_ALGO, "worker request: refused zone transfer.");
		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), 
			LDNS_RCODE_REFUSED);
		if(worker->stats.extended) {
			worker->stats.qtype[qinfo.qtype]++;
			server_stats_insrcode(&worker->stats, c->buffer);
		}
		return 1;
	}
	if((ret=parse_edns_from_pkt(c->buffer, &edns)) != 0) {
		verbose(VERB_ALGO, "worker parse edns: formerror.");
		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
		ldns_buffer_rewind(c->buffer);
		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), ret);
		server_stats_insrcode(&worker->stats, c->buffer);
		return 1;
	}
	if(edns.edns_present && edns.edns_version != 0) {
		edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4);
		edns.edns_version = EDNS_ADVERTISED_VERSION;
		edns.udp_size = EDNS_ADVERTISED_SIZE;
		edns.bits &= EDNS_DO;
		verbose(VERB_ALGO, "query with bad edns version.");
		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
		error_encode(c->buffer, EDNS_RCODE_BADVERS&0xf, &qinfo,
			*(uint16_t*)ldns_buffer_begin(c->buffer),
			ldns_buffer_read_u16_at(c->buffer, 2), NULL);
		attach_edns_record(c->buffer, &edns);
		return 1;
	}
Ejemplo n.º 26
0
/**
 * Setup key and digest for verification. Adjust sig if necessary.
 *
 * @param algo: key algorithm
 * @param evp_key: EVP PKEY public key to create.
 * @param digest_type: digest type to use
 * @param key: key to setup for.
 * @param keylen: length of key.
 * @param prefix: if returned, the ASN prefix for the hashblob.
 * @param prefixlen: length of the prefix.
 * @return false on failure.
 */
static int
nss_setup_key_digest(int algo, SECKEYPublicKey** pubkey, HASH_HashType* htype,
                     unsigned char* key, size_t keylen, unsigned char** prefix,
                     size_t* prefixlen)
{
    /* uses libNSS */

    /* hash prefix for md5, RFC2537 */
    static unsigned char p_md5[] = {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a,
                                    0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
                                   };
    /* hash prefix to prepend to hash output, from RFC3110 */
    static unsigned char p_sha1[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
                                     0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14
                                    };
    /* from RFC5702 */
    static unsigned char p_sha256[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
                                       0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
                                      };
    static unsigned char p_sha512[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
                                       0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40
                                      };
    /* from RFC6234 */
    /* for future RSASHA384 ..
    static unsigned char p_sha384[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
    0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30};
    */

    switch(algo) {
#ifdef USE_DSA
    case LDNS_DSA:
    case LDNS_DSA_NSEC3:
        *pubkey = nss_buf2dsa(key, keylen);
        if(!*pubkey) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        *htype = HASH_AlgSHA1;
        /* no prefix for DSA verification */
        break;
#endif
    case LDNS_RSASHA1:
    case LDNS_RSASHA1_NSEC3:
#ifdef USE_SHA2
    case LDNS_RSASHA256:
#endif
#ifdef USE_SHA2
    case LDNS_RSASHA512:
#endif
        *pubkey = nss_buf2rsa(key, keylen);
        if(!*pubkey) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        /* select SHA version */
#ifdef USE_SHA2
        if(algo == LDNS_RSASHA256) {
            *htype = HASH_AlgSHA256;
            *prefix = p_sha256;
            *prefixlen = sizeof(p_sha256);
        } else
#endif
#ifdef USE_SHA2
            if(algo == LDNS_RSASHA512) {
                *htype = HASH_AlgSHA512;
                *prefix = p_sha512;
                *prefixlen = sizeof(p_sha512);
            } else
#endif
            {
                *htype = HASH_AlgSHA1;
                *prefix = p_sha1;
                *prefixlen = sizeof(p_sha1);
            }

        break;
    case LDNS_RSAMD5:
        *pubkey = nss_buf2rsa(key, keylen);
        if(!*pubkey) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        *htype = HASH_AlgMD5;
        *prefix = p_md5;
        *prefixlen = sizeof(p_md5);

        break;
#ifdef USE_ECDSA
    case LDNS_ECDSAP256SHA256:
        *pubkey = nss_buf2ecdsa(key, keylen,
                                LDNS_ECDSAP256SHA256);
        if(!*pubkey) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        *htype = HASH_AlgSHA256;
        /* no prefix for DSA verification */
        break;
    case LDNS_ECDSAP384SHA384:
        *pubkey = nss_buf2ecdsa(key, keylen,
                                LDNS_ECDSAP384SHA384);
        if(!*pubkey) {
            log_err("verify: malloc failure in crypto");
            return 0;
        }
        *htype = HASH_AlgSHA384;
        /* no prefix for DSA verification */
        break;
#endif /* USE_ECDSA */
    case LDNS_ECC_GOST:
    default:
        verbose(VERB_QUERY, "verify: unknown algorithm %d",
                algo);
        return 0;
    }
    return 1;
}
Ejemplo n.º 27
0
/** daemonize, drop user priviliges and chroot if needed */
static void
perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
	const char** cfgfile)
{
#ifdef HAVE_KILL
	int pidinchroot;
#endif
#ifdef HAVE_GETPWNAM
	struct passwd *pwd = NULL;

	if(cfg->username && cfg->username[0]) {
		if((pwd = getpwnam(cfg->username)) == NULL)
			fatal_exit("user '%s' does not exist.", cfg->username);
		/* endpwent below, in case we need pwd for setusercontext */
	}
#endif
#ifdef UB_ON_WINDOWS
	w_config_adjust_directory(cfg);
#endif

	/* init syslog (as root) if needed, before daemonize, otherwise
	 * a fork error could not be printed since daemonize closed stderr.*/
	if(cfg->use_syslog) {
		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
	}
	/* if using a logfile, we cannot open it because the logfile would
	 * be created with the wrong permissions, we cannot chown it because
	 * we cannot chown system logfiles, so we do not open at all.
	 * So, using a logfile, the user does not see errors unless -d is
	 * given to unbound on the commandline. */

	/* read ssl keys while superuser and outside chroot */
#ifdef HAVE_SSL
	if(!(daemon->rc = daemon_remote_create(cfg)))
		fatal_exit("could not set up remote-control");
	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
		if(!(daemon->listen_sslctx = listen_sslctx_create(
			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
			fatal_exit("could not set up listen SSL_CTX");
	}
	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
		fatal_exit("could not set up connect SSL_CTX");
#endif

#ifdef HAVE_KILL
	/* true if pidfile is inside chrootdir, or nochroot */
	pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
				(cfg->chrootdir && cfg->chrootdir[0] &&
				strncmp(cfg->pidfile, cfg->chrootdir,
				strlen(cfg->chrootdir))==0);

	/* check old pid file before forking */
	if(cfg->pidfile && cfg->pidfile[0]) {
		/* calculate position of pidfile */
		if(cfg->pidfile[0] == '/')
			daemon->pidfile = strdup(cfg->pidfile);
		else	daemon->pidfile = fname_after_chroot(cfg->pidfile, 
				cfg, 1);
		if(!daemon->pidfile)
			fatal_exit("pidfile alloc: out of memory");
		checkoldpid(daemon->pidfile, pidinchroot);
	}
#endif

	/* daemonize because pid is needed by the writepid func */
	if(!debug_mode && cfg->do_daemonize) {
		detach();
	}

	/* write new pidfile (while still root, so can be outside chroot) */
#ifdef HAVE_KILL
	if(cfg->pidfile && cfg->pidfile[0]) {
		writepid(daemon->pidfile, getpid());
		if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
			pidinchroot) {
#  ifdef HAVE_CHOWN
			if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
				verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
					(unsigned)cfg_uid, (unsigned)cfg_gid,
					daemon->pidfile, strerror(errno));
			}
#  endif /* HAVE_CHOWN */
		}
	}
#else
	(void)daemon;
#endif /* HAVE_KILL */

	/* Set user context */
#ifdef HAVE_GETPWNAM
	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
#ifdef HAVE_SETUSERCONTEXT
		/* setusercontext does initgroups, setuid, setgid, and
		 * also resource limits from login config, but we
		 * still call setresuid, setresgid to be sure to set all uid*/
		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
			log_warn("unable to setusercontext %s: %s",
				cfg->username, strerror(errno));
#endif /* HAVE_SETUSERCONTEXT */
	}
#endif /* HAVE_GETPWNAM */

	/* box into the chroot */
#ifdef HAVE_CHROOT
	if(cfg->chrootdir && cfg->chrootdir[0]) {
		if(chdir(cfg->chrootdir)) {
			fatal_exit("unable to chdir to chroot %s: %s",
				cfg->chrootdir, strerror(errno));
		}
		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
		if(chroot(cfg->chrootdir))
			fatal_exit("unable to chroot to %s: %s", 
				cfg->chrootdir, strerror(errno));
		if(chdir("/"))
			fatal_exit("unable to chdir to / in chroot %s: %s",
				cfg->chrootdir, strerror(errno));
		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
		if(strncmp(*cfgfile, cfg->chrootdir, 
			strlen(cfg->chrootdir)) == 0) 
			(*cfgfile) += strlen(cfg->chrootdir);

		/* adjust stored pidfile for chroot */
		if(daemon->pidfile && daemon->pidfile[0] && 
			strncmp(daemon->pidfile, cfg->chrootdir,
			strlen(cfg->chrootdir))==0) {
			char* old = daemon->pidfile;
			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
			free(old);
			if(!daemon->pidfile)
				log_err("out of memory in pidfile adjust");
		}
		daemon->chroot = strdup(cfg->chrootdir);
		if(!daemon->chroot)
			log_err("out of memory in daemon chroot dir storage");
	}
#else
	(void)cfgfile;
#endif
	/* change to working directory inside chroot */
	if(cfg->directory && cfg->directory[0]) {
		char* dir = cfg->directory;
		if(cfg->chrootdir && cfg->chrootdir[0] &&
			strncmp(dir, cfg->chrootdir, 
			strlen(cfg->chrootdir)) == 0)
			dir += strlen(cfg->chrootdir);
		if(dir[0]) {
			if(chdir(dir)) {
				fatal_exit("Could not chdir to %s: %s",
					dir, strerror(errno));
			}
			verbose(VERB_QUERY, "chdir to %s", dir);
		}
	}

	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
#ifdef HAVE_GETPWNAM
	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
#  ifdef HAVE_INITGROUPS
		if(initgroups(cfg->username, cfg_gid) != 0)
			log_warn("unable to initgroups %s: %s",
				cfg->username, strerror(errno));
#  endif /* HAVE_INITGROUPS */
#  ifdef HAVE_ENDPWENT
		endpwent();
#  endif

#ifdef HAVE_SETRESGID
		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
		if(setregid(cfg_gid,cfg_gid) != 0)
#else /* use setgid */
		if(setgid(cfg_gid) != 0)
#endif /* HAVE_SETRESGID */
			fatal_exit("unable to set group id of %s: %s", 
				cfg->username, strerror(errno));
#ifdef HAVE_SETRESUID
		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
		if(setreuid(cfg_uid,cfg_uid) != 0)
#else /* use setuid */
		if(setuid(cfg_uid) != 0)
#endif /* HAVE_SETRESUID */
			fatal_exit("unable to set user id of %s: %s", 
				cfg->username, strerror(errno));
		verbose(VERB_QUERY, "drop user privileges, run as %s", 
			cfg->username);
	}
#endif /* HAVE_GETPWNAM */
	/* file logging inited after chroot,chdir,setuid is done so that 
	 * it would succeed on SIGHUP as well */
	if(!cfg->use_syslog)
		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
}
Ejemplo n.º 28
0
/* copyMafs - copy all the maf alignments into 
 * one sequence for each species
 */
static void copyMafs(struct hash *siHash, struct exonInfo **giList, 
    boolean inExons)
{
int start = 0;
struct exonInfo *gi = *giList;

for(; gi; gi = gi->next)
    {
    int thisSize = 0;
    struct mafAli *ali = gi->ali;

    for(; ali; ali = ali->next)
	{
	int newStart = copyAli(siHash, ali, start);
	thisSize += newStart - start;
	start = newStart;
	}
    struct hashCookie cookie =  hashFirst(siHash);
    struct hashEl *hel;

    if (inExons || (gi->next == NULL))
	while ((hel = hashNext(&cookie)) != NULL)
	    {
	    struct speciesInfo *si = hel->val;

	    pushPosString(si);
	    }
    }

boolean frameNeg = ((*giList)->strand == '-');

if (frameNeg)
    {
    int size = 0;
    struct hashCookie cookie =  hashFirst(siHash);
    struct hashEl *hel;
    
    verbose(3, "flipping exons\n");
    while ((hel = hashNext(&cookie)) != NULL)
	{
	struct speciesInfo *si = hel->val;

	if (si == NULL)
	    continue;

	if (size != 0)
	    assert(size == si->size);
	else
	    size = si->size;
	reverseComplement(si->nucSequence, si->size);

	slReverse(&si->posStrings);
	}

    gi = *giList;
    for(; gi; gi = gi->next)
	{
	verbose(3, "old start %d ",gi->exonStart);
	gi->exonStart = size - (gi->exonStart + gi->exonSize);
	verbose(3, "new start %d size %d \n",gi->exonStart, gi->exonSize);
	if (gi->next == NULL)
	    assert(gi->exonStart == 0);
	}

    slReverse(giList);
    }
}
Ejemplo n.º 29
0
/**
 * See if response-ip or tag data should override the original answer rrset
 * (which is rep->rrsets[rrset_id]) and if so override it.
 * This is (mostly) equivalent to localzone.c:local_data_answer() but for
 * response-ip actions.
 * Note that this function distinguishes error conditions from "success but
 * not overridden".  This is because we want to avoid accidentally applying
 * the "no data" action in case of error.
 * @param raddr: address span that requires an action
 * @param action: action to apply
 * @param qtype: original query type
 * @param rep: original reply message
 * @param rrset_id: the rrset ID in 'rep' to which the action should apply
 * @param new_repp: see respip_rewrite_reply
 * @param tag: if >= 0 the tag ID used to determine the action and data
 * @param tag_datas: data corresponding to 'tag'.
 * @param tag_datas_size: size of 'tag_datas'
 * @param tagname: array of tag names, used for logging
 * @param num_tags: size of 'tagname', used for logging
 * @param redirect_rrsetp: ptr to redirect record
 * @param region: region for building new reply
 * @return 1 if overridden, 0 if not overridden, -1 on error.
 */
static int
respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
	uint16_t qtype, const struct reply_info* rep,
	size_t rrset_id, struct reply_info** new_repp, int tag,
	struct config_strlist** tag_datas, size_t tag_datas_size,
	char* const* tagname, int num_tags,
	struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
{
	struct ub_packed_rrset_key* rp = raddr->data;
	struct reply_info* new_rep;
	*redirect_rrsetp = NULL;

	if(action == respip_redirect && tag != -1 &&
		(size_t)tag<tag_datas_size && tag_datas[tag]) {
		struct query_info dataqinfo;
		struct ub_packed_rrset_key r;

		/* Extract parameters of the original answer rrset that can be
		 * rewritten below, in the form of query_info.  Note that these
		 * can be different from the info of the original query if the
		 * rrset is a CNAME target.*/
		memset(&dataqinfo, 0, sizeof(dataqinfo));
		dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
		dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
		dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
		dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);

		memset(&r, 0, sizeof(r));
		if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
			region)) {
			verbose(VERB_ALGO,
				"response-ip redirect with tag data [%d] %s",
				tag, (tag<num_tags?tagname[tag]:"null"));
			/* use copy_rrset() to 'normalize' memory layout */
			rp = copy_rrset(&r, region);
			if(!rp)
				return -1;
		}
	}
	if(!rp)
		return 0;

	/* If we are using response-ip-data, we need to make a copy of rrset
	 * to replace the rrset's dname.  Note that, unlike local data, we
	 * rename the dname for other actions than redirect.  This is because
	 * response-ip-data isn't associated to any specific name. */
	if(rp == raddr->data) {
		rp = copy_rrset(rp, region);
		if(!rp)
			return -1;
		rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
		rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
	}

	/* Build a new reply with redirect rrset.  We keep any preceding CNAMEs
	 * and replace the address rrset that triggers the action.  If it's
	 * type ANY query, however, no other answer records should be kept
	 * (note that it can't be a CNAME chain in this case due to
	 * sanitizing). */
	if(qtype == LDNS_RR_TYPE_ANY)
		rrset_id = 0;
	new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
	if(!new_rep)
		return -1;
	rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
	new_rep->rrsets[rrset_id] = rp;

	*redirect_rrsetp = rp;
	*new_repp = new_rep;
	return 1;
}
Ejemplo n.º 30
0
void os_ReportdStart(report_filter *r_filter)
{
    int alerts_processed = 0;
    int alerts_filtered = 0;
    char *first_alert = NULL;
    char *last_alert = NULL;
    void **data_to_clean = NULL;


    time_t tm;
    struct tm *p;


    file_queue *fileq;
    alert_data *al_data;


    /* Getting current time before starting */
    tm = time(NULL);
    p = localtime(&tm);	




    /* Initating file queue - to read the alerts */
    os_calloc(1, sizeof(file_queue), fileq);

    if(r_filter->report_type == REPORT_TYPE_DAILY && r_filter->filename)
    {
        fileq->fp = fopen(r_filter->filename, "r");
        if(!fileq->fp)
        {
            merror("%s: ERROR: Unable to open alerts file to generate report.", __local_name);
            return;
        }
        if(r_filter->fp)
        {
            __g_rtype = r_filter->fp;
        }
    }
    else
    {
        fileq->fp = stdin;
    }


    /* Creating top hashes. */
    r_filter->top_user = OSStore_Create();
    r_filter->top_srcip = OSStore_Create();
    r_filter->top_level = OSStore_Create();
    r_filter->top_rule = OSStore_Create();
    r_filter->top_group = OSStore_Create();
    r_filter->top_location = OSStore_Create();
    r_filter->top_files = OSStore_Create();

    Init_FileQueue(fileq, p, CRALERT_READ_ALL|CRALERT_FP_SET);



    /* Reading the alerts. */
    while(1)
    {
        /* Get message if available */
        al_data = Read_FileMon(fileq, p, 1);
        if(!al_data)
        {
            break;
        }

        alerts_processed++;


        /* Checking the filters. */
        if(!_os_report_check_filters(al_data, r_filter))
        {
            FreeAlertData(al_data);
            continue;
        }


        alerts_filtered++;
        data_to_clean = os_AddPtArray(al_data, data_to_clean);


        /* Setting first and last alert for summary. */
        if(!first_alert)
            first_alert = al_data->date;
        last_alert = al_data->date;


        /* Adding source ip if it is set properly. */
        if(al_data->srcip != NULL && strcmp(al_data->srcip, "(none)") != 0)
            _os_report_add_tostore(al_data->srcip, r_filter->top_srcip, al_data);


        /* Adding user if it is set properly. */
        if(al_data->user != NULL && strcmp(al_data->user, "(none)") != 0)
            _os_report_add_tostore(al_data->user, r_filter->top_user, al_data);


        /* Adding level and severity. */
        {
            char mlevel[16];
            char mrule[76 +1];
            mrule[76] = '\0';
            snprintf(mlevel, 16, "Severity %d" , al_data->level);
            snprintf(mrule, 76, "%d - %s" , al_data->rule, al_data->comment);

            _os_report_add_tostore(strdup(mlevel), r_filter->top_level,
                                   al_data);
            _os_report_add_tostore(strdup(mrule), r_filter->top_rule,
                                   al_data);
        }

        /* Dealing with the group. */
        {
            char *tmp_str;
            char **mgroup;

            mgroup = OS_StrBreak(',', al_data->group, 32);
            if(mgroup)
            {
                while(*mgroup)
                {
                    tmp_str = *mgroup;
                    while(*tmp_str == ' ')
                        tmp_str++;
                    if(*tmp_str == '\0')
                    {
                        mgroup++;
                        continue;
                    }

                    _os_report_add_tostore(tmp_str, r_filter->top_group,
                                           al_data);
                    mgroup++;
                }
            }
            else
            {
                tmp_str = al_data->group;
                while(*tmp_str == ' ')
                    tmp_str++;
                if(*tmp_str != '\0')
                {
                    _os_report_add_tostore(tmp_str, r_filter->top_group,
                                           al_data);
                }
            }
        }


        /* Adding to the location top filter. */
        _os_report_add_tostore(al_data->location, r_filter->top_location,
                               al_data);


        if(al_data->filename != NULL)
        {
            _os_report_add_tostore(al_data->filename, r_filter->top_files,
                                   al_data);
        }
    }

    /* No report available */
    if(alerts_filtered == 0)
    {
        if(!r_filter->report_name)
            merror("%s: INFO: Report completed and zero alerts post-filter.", __local_name);
        else
            merror("%s: INFO: Report '%s' completed and zero alerts post-filter.", __local_name, r_filter->report_name);
        return;
    }


    if(r_filter->report_name)
        verbose("%s: INFO: Report '%s' completed. Creating output...", __local_name, r_filter->report_name);
    else
        verbose("%s: INFO: Report completed. Creating output...", __local_name);


    l_print_out(" ");
    if(r_filter->report_name)
        l_print_out("Report '%s' completed.", r_filter->report_name);
    else
        l_print_out("Report completed. ==");
    l_print_out("------------------------------------------------");

    l_print_out("->Processed alerts: %d", alerts_processed);
    l_print_out("->Post-filtering alerts: %d", alerts_filtered);
    l_print_out("->First alert: %s", first_alert);
    l_print_out("->Last alert: %s", last_alert);
    l_print_out(" ");
    l_print_out(" ");

    OSStore_Sort(r_filter->top_srcip, _os_report_sort_compare);
    OSStore_Sort(r_filter->top_user,  _os_report_sort_compare);
    OSStore_Sort(r_filter->top_level, _os_report_sort_compare);
    OSStore_Sort(r_filter->top_group, _os_report_sort_compare);
    OSStore_Sort(r_filter->top_location, _os_report_sort_compare);
    OSStore_Sort(r_filter->top_rule, _os_report_sort_compare);
    OSStore_Sort(r_filter->top_files, _os_report_sort_compare);

    if(r_filter->top_srcip)
        os_report_printtop(r_filter->top_srcip, "Source ip", 0);

    if(r_filter->top_user)
        os_report_printtop(r_filter->top_user, "Username", 0);

    if(r_filter->top_level)
        os_report_printtop(r_filter->top_level, "Level", 0);

    if(r_filter->top_group)
        os_report_printtop(r_filter->top_group, "Group", 0);

    if(r_filter->top_location)
        os_report_printtop(r_filter->top_location, "Location", 0);

    if(r_filter->top_rule)
        os_report_printtop(r_filter->top_rule, "Rule", 0);

    if(r_filter->top_files)
        os_report_printtop(r_filter->top_files, "Filenames", 0);


    /* Print related events. */
    if(r_filter->related_srcip)
        os_report_printtop(r_filter->top_srcip, "Source ip",
                           r_filter->related_srcip);

    if(r_filter->related_user)
        os_report_printtop(r_filter->top_user, "Username",
                           r_filter->related_user);

    if(r_filter->related_level)
        os_report_printtop(r_filter->top_level, "Level",
                           r_filter->related_level);

    if(r_filter->related_group)
        os_report_printtop(r_filter->top_group, "Group",
                           r_filter->related_group);

    if(r_filter->related_location)
        os_report_printtop(r_filter->top_location, "Location",
                           r_filter->related_location);

    if(r_filter->related_rule)
        os_report_printtop(r_filter->top_rule, "Rule",
                           r_filter->related_rule);

    if(r_filter->related_file)
        os_report_printtop(r_filter->top_files, "Filename",
                           r_filter->related_file);


    /* If we have to dump the alerts. */
    if(data_to_clean)
    {
        int i = 0;

        if(r_filter->show_alerts)
        {
            l_print_out("Log dump:");
            l_print_out("------------------------------------------------");
        }
        while(data_to_clean[i])
        {
            alert_data *md = data_to_clean[i];
            if(r_filter->show_alerts)
                l_print_out("%s %s\nRule: %d (level %d) -> '%s'\n%s\n\n", md->date, md->location, md->rule, md->level, md->comment, md->log[0]);
            FreeAlertData(md);
            i++;
        }
        free(data_to_clean);
        data_to_clean = NULL;
    }
}