struct ext_include_script_info *ext_include_binary_script_include
(struct ext_include_binary_context *binctx, 
	enum ext_include_script_location location, enum ext_include_flags flags,
	struct sieve_script *script,	struct sieve_binary_block *inc_block)
{
	pool_t pool = sieve_binary_pool(binctx->binary);
	struct ext_include_script_info *incscript;

	incscript = p_new(pool, struct ext_include_script_info, 1);
	incscript->id = array_count(&binctx->include_index)+1;
	incscript->location = location;
	incscript->flags = flags;
	incscript->script = script;
	incscript->block = inc_block;

	/* Unreferenced on binary_free */
	sieve_script_ref(script);

	hash_table_insert(binctx->included_scripts, script, incscript);
	array_append(&binctx->include_index, &incscript, 1);

	return incscript;
}
Ejemplo n.º 2
0
bool
record2map(uint32_t addr, const logrecord_t *record, port_type_t type)
{
    hash_table_t *map = get_map_by_type(type);
    if (!map)
        return false;

    logrecord_t* original_record =
            (logrecord_t*) hash_table_lookup(map, &addr);
    if (original_record == NULL) {
        uint32_t* ip = (uint32_t* )mem_cache_alloc(key_cache);
        original_record = (logrecord_t* )mem_cache_alloc(value_cache);
        *original_record = *record;
        *ip = addr;
        hash_table_insert(map, ip, original_record);
    } else {
        original_record->count += record->count;
        original_record->bytes += record->bytes;
        original_record->flag |= record->flag;
    }

    return true;
}
void KVServer::handle_insert(KVRequest* request)
{
	KeyVal* newKV = NULL;

	// If the key is already present, we need to remove it first
	// (because hash_table doesn't like inserts for existing values)
	newKV = (KeyVal*) hash_table_lookup(&db, &request->kv);
	if (newKV != NULL) {
		hash_table_remove(&db, newKV);
		free(newKV);
	}

	// Now copy the request and insert it into our database
	newKV = KV_clone(&request->kv);
	uint32_t hash131 = hash_buf(newKV->val.bytes, newKV->val.len);
	lite_assert(newKV);
	hash_table_insert(&db, newKV);
	annotate("insert", newKV);

	int rc;
	rc = sendto(sock, &hash131, sizeof(hash131), 0, (sockaddr*)&remote_addr, sizeof(remote_addr));
	if (rc == -1) { fprintf(stderr, "(KeyValueServer) Failed to send insert reply!\n"); }
}
Ejemplo n.º 4
0
int* twoSum(int* nums, int numsSize, int target)
{
    hash_table ht = NULL;
    hash_entry entry = NULL;
    int i, complement;
    int* result = malloc(2 * sizeof(int));
    if(result == NULL)
        err(-1, "malloc: result: out of space!");

    for(i = 0; i < numsSize; i++) {
        complement = target - nums[i];
        if(entry = hash_find_key(complement, &ht)) {
            result[0] = entry->h_value;
            result[1] = i;
            break;
        }
        else {
            hash_table_insert(nums[i], i, &ht);
        }
    }

    return result;
}
Ejemplo n.º 5
0
Archivo: dag.c Proyecto: badi/cctools
/* Adds remotename to the local name filename in the namespace of
 * the given node. If remotename is NULL, then a new name is
 * found using dag_node_translate_filename. If the remotename
 * given is different from a previosly specified, a warning is
 * written to the debug output, but otherwise this is ignored. */
const char *dag_node_add_remote_name(struct dag_node *n, const char *filename, const char *remotename)
{
	char *oldname;
	struct dag_file *f = dag_file_from_name(n->d, filename);

	if(!f)
		fatal("trying to add remote name %s to unknown file %s.\n", remotename, filename);

	if(!remotename)
		remotename = dag_node_translate_filename(n, filename);
	else
		remotename = xxstrdup(remotename);

	oldname = hash_table_lookup(n->remote_names_inv, remotename);

	if(oldname && strcmp(oldname, filename) == 0)
		debug(D_DEBUG, "Remote name %s for %s already in use for %s\n", remotename, filename, oldname);

	itable_insert(n->remote_names, (uintptr_t) f, remotename);
	hash_table_insert(n->remote_names_inv, remotename, (void *) f);

	return remotename;
}
Ejemplo n.º 6
0
static void check_rehash(HashTable* table)
{
	float load = (float)table->size / table->capacity;
	if (load < LOAD_MAX)
		return;
	int oldCapacity = table->capacity;
	Node** oldTable = table->table;
	table->capacity *= 2;
	table->table = (Node**)calloc(table->capacity, sizeof(Node*));
	clear_table(table, FALSE);
	int i;
	for (i = 0; i < oldCapacity; i++)
	{
		Node* pNode = oldTable[i];
		while (pNode)
		{
			hash_table_insert(table, pNode->key, pNode->val);
			Node* pNodeC = pNode;
			pNode = pNode->next;
			free(pNodeC);
		}
	}
	free(oldTable);
}
Ejemplo n.º 7
0
void dag_variable_add_value(const char *name, struct hash_table *current_table, int nodeid, const char *value)
{
    struct dag_variable *var = hash_table_lookup(current_table, name);
    if(!var)
    {
        char *value_env = getenv(name);
        var = dag_variable_create(name, value_env);
        hash_table_insert(current_table, name, var);
    }

    struct dag_variable_value *v = dag_variable_value_create(value);
    v->nodeid = nodeid;

    if(var->count < 1 || var->values[var->count - 1]->nodeid != v->nodeid)
    {
        var->count++;
        var->values = realloc(var->values, var->count * sizeof(struct dag_variable_value *));
    } else {
        dag_variable_value_free(var->values[var->count-1]);
    }

    //possible memory leak...
    var->values[var->count - 1] = v;
}
Ejemplo n.º 8
0
struct mail_ip *mail_ip_login(const struct ip_addr *ip_addr)
{
	struct mail_ip *ip;

	ip = hash_table_lookup(mail_ips_hash, ip_addr);
	if (ip != NULL) {
		ip->num_logins++;
		mail_ip_refresh(ip, NULL);
		return ip;
	}

	ip = i_new(struct mail_ip, 1);
	ip->ip = *ip_addr;
	ip->reset_timestamp = ioloop_time;

	hash_table_insert(mail_ips_hash, &ip->ip, ip);
	DLLIST_PREPEND_FULL(&stable_mail_ips, ip, stable_prev, stable_next);
	DLLIST2_APPEND_FULL(&mail_ips_head, &mail_ips_tail, ip,
			    sorted_prev, sorted_next);
	ip->num_logins++;
	ip->last_update = ioloop_timeval;
	global_memory_alloc(mail_ip_memsize(ip));
	return ip;
}
Ejemplo n.º 9
0
// Add chrome name to hash table
void init_chrome_hash(HashNode** hashTable, int* hash_table_size, char* chrLenFile, int* chrCnt)
{
	
	FILE* fPtr = fopen(chrLenFile, "r");
	if(!fPtr) { 
		// Check file existance
		printf("File %s open error.\n", chrLenFile);
		exit(1);
	}
	fclose(fPtr);
	
	char* token = NULL;
	char readBuffer[500];
	char seps[] = " \t\n\r";
	*chrCnt = 0;
	fPtr = fopen(chrLenFile, "r");
	while(fgets(readBuffer, 500, fPtr)) {
		token = strtok(readBuffer, seps);
		hash_table_insert(hashTable, hash_table_size, token, *chrCnt);
		(*chrCnt)++;
	}
	fclose(fPtr);
	printf("%d chromes loaded.\n", *chrCnt);
}
Ejemplo n.º 10
0
bool build_wb_list(const char *filename)
{
    size_t      len;
    ssize_t     linelen = 0;
    char        *line = NULL;

    FILE *file = fopen(filename, "r");
    if (!file) {
        LOG(LOG_LEVEL_ERROR, "Open %s failed", filename);
        return false;
    }
    assert(file != NULL);

    while ((linelen = getline(&line, &len, file)) != -1) {
        line[linelen-1] = '\0';
        //if (!validate_wb(line, linelen))
        //    continue;

        ip_seg ipseg = get_ip_seg_from_mask_str(line);
        if (ipseg.end == 0)
            continue;

        for (uint32_t ip = ipseg.start; ip <= ipseg.end; ip++) {
            uint32_t* key = (uint32_t* )mem_cache_alloc(key_cache);
            *key = ip;
            hash_table_insert(wb_list_map, key, NULL);
        }
        //LOG(LOG_LEVEL_TRACE, "Read a line: %s, length: %zu", line, linelen);
    }

    if (line)
        free(line);

    fclose(file);
    return true;
}
Ejemplo n.º 11
0
static bool ATTR_NOWARN_UNUSED_RESULT
export_change_get(struct dsync_transaction_log_scan *ctx, uint32_t uid,
		  enum dsync_mail_change_type type,
		  struct dsync_mail_change **change_r)
{
	struct dsync_mail_change *change;
	const char *orig_guid;

	i_assert(uid > 0);
	i_assert(type != DSYNC_MAIL_CHANGE_TYPE_SAVE);

	*change_r = NULL;

	if (uid > ctx->highest_wanted_uid)
		return FALSE;

	change = hash_table_lookup(ctx->changes, POINTER_CAST(uid));
	if (change == NULL) {
		/* first change for this UID */
		change = p_new(ctx->pool, struct dsync_mail_change, 1);
		change->uid = uid;
		change->type = type;
		hash_table_insert(ctx->changes, POINTER_CAST(uid), change);
	} else if (type == DSYNC_MAIL_CHANGE_TYPE_EXPUNGE) {
Ejemplo n.º 12
0
const glsl_type *
glsl_type::get_record_instance(const glsl_struct_field *fields,
			       unsigned num_fields,
			       const char *name)
{
   const glsl_type key(fields, num_fields, name);

   if (record_types == NULL) {
      record_types = hash_table_ctor(64, record_key_hash, record_key_compare);
   }

   const glsl_type *t = (glsl_type *) hash_table_find(record_types, & key);
   if (t == NULL) {
      t = new glsl_type(fields, num_fields, name);

      hash_table_insert(record_types, (void *) t, t);
   }

   assert(t->base_type == GLSL_TYPE_STRUCT);
   assert(t->length == num_fields);
   assert(strcmp(t->name, name) == 0);

   return t;
}
Ejemplo n.º 13
0
static void
checkpassword_lookup(struct auth_request *request, userdb_callback_t *callback)
{
	struct userdb_module *_module = request->userdb->userdb;
	struct checkpassword_userdb_module *module =
		(struct checkpassword_userdb_module *)_module;
	struct chkpw_auth_request *chkpw_auth_request;
	int fd_in[2], fd_out[2];
	pid_t pid;

	fd_in[0] = -1;
	if (pipe(fd_in) < 0 || pipe(fd_out) < 0) {
		auth_request_log_error(request, "userdb-checkpassword",
				       "pipe() failed: %m");
		callback(USERDB_RESULT_INTERNAL_FAILURE, request);
		if (fd_in[0] != -1) {
			(void)close(fd_in[0]);
			(void)close(fd_in[1]);
		}
		return;
	}

	pid = fork();
	if (pid == -1) {
		auth_request_log_error(request, "userdb-checkpassword",
				       "fork() failed: %m");
		callback(USERDB_RESULT_INTERNAL_FAILURE, request);
		(void)close(fd_in[0]);
		(void)close(fd_in[1]);
		(void)close(fd_out[0]);
		(void)close(fd_out[1]);
		return;
	}

	if (pid == 0) {
		(void)close(fd_in[0]);
		(void)close(fd_out[1]);
		checkpassword_lookup_child(request, module,
						 fd_in[1], fd_out[0]);
		/* not reached */
	}

	if (close(fd_in[1]) < 0) {
		auth_request_log_error(request, "userdb-checkpassword",
				       "close(fd_in[1]) failed: %m");
	}
	if (close(fd_out[0]) < 0) {
		auth_request_log_error(request, "userdb-checkpassword",
				       "close(fd_out[0]) failed: %m");
	}

	auth_request_ref(request);
	chkpw_auth_request = i_new(struct chkpw_auth_request, 1);
	chkpw_auth_request->fd_in = fd_in[0];
	chkpw_auth_request->fd_out = fd_out[1];
	chkpw_auth_request->pid = pid;
	chkpw_auth_request->request = request;
	chkpw_auth_request->callback = callback;
	chkpw_auth_request->half_finish_callback =
		checkpassword_request_half_finish;
	chkpw_auth_request->finish_callback =
		checkpassword_request_finish;
	chkpw_auth_request->internal_failure_code =
		USERDB_RESULT_INTERNAL_FAILURE;

	chkpw_auth_request->io_in =
		io_add(fd_in[0], IO_READ, checkpassword_child_input,
		       chkpw_auth_request);
	chkpw_auth_request->io_out =
		io_add(fd_out[1], IO_WRITE, checkpassword_child_output,
		       chkpw_auth_request);

	hash_table_insert(module->clients, POINTER_CAST(pid),
			  chkpw_auth_request);

	if (checkpassword_userdb_children != NULL)
		child_wait_add_pid(checkpassword_userdb_children, pid);
	else {
		checkpassword_userdb_children =
			child_wait_new_with_pid(pid, sigchld_handler, module);
	}
}
Ejemplo n.º 14
0
int s3_getacl(char* bucketname, char* filename, char* owner, struct hash_table* acls, const char* access_key_id, const char* access_key) {
	struct s3_message mesg;
	struct link* server;
	time_t stoptime = time(0)+s3_timeout;
	char path[HEADER_LINE_MAX];
	char response[HEADER_LINE_MAX];
	char * text;
	char * start;
	char * temp;
	int length;
 
	if(!s3_endpoint) return -1;
	if(filename) sprintf(path, "%s?acl", filename);
	else sprintf(path, "/?acl");

	mesg.type = S3_MESG_GET;
	mesg.path = path;
	mesg.bucket = bucketname;
	mesg.content_type = NULL;
	mesg.content_md5 = NULL;
	mesg.content_length = 0;
	mesg.date = time(0);
	mesg.expect = 0;
	mesg.amz_headers = NULL;

	//server = link_connect(s3_address, 80, stoptime);

	sign_message(&mesg, access_key_id, access_key);
	server = s3_send_message(&mesg, NULL, stoptime);
	if(!server)
		return -1;
	//length = s3_message_to_string(&mesg, &text);

	//link_putlstring(server, text, length, stoptime);
	//free(text);

	link_readline(server, response, HEADER_LINE_MAX, stoptime);
	if(strcmp(response, "HTTP/1.1 200 OK")) {
		// Error: transfer failed; close connection and return failure
		//fprintf(stderr, "Error: request file failed\nResponse: %s\n", response);
		link_close(server);
		return -1;
	}

	do {
		if(!strncmp(response, "Content-Length:", 14)) sscanf(response, "Content-Length: %d", &length);
		if(!strcmp(response, "Transfer-Encoding: chunked")) length = 0;
		if(!strcmp(response, "Server: AmazonS3")) break;
	} while(link_readline(server, response, HEADER_LINE_MAX, stoptime));
	link_readline(server, response, HEADER_LINE_MAX, stoptime);

	if(length) {
		text = malloc(length+1);
		link_read(server, text, length, stoptime);
	} else {
		struct list *buf;
		char *temp;
		unsigned int clen = 0;
		buf = list_create();
		do {
			link_readline(server, response, HEADER_LINE_MAX, stoptime);
			sscanf(response, "%x", &clen);
			//link_readline(server, response, HEADER_LINE_MAX, stoptime);
			if(clen) {
				text = malloc(clen+1);
				link_read(server, text, clen, stoptime);
				link_readline(server, response, HEADER_LINE_MAX, stoptime);
				list_push_tail(buf, text);
				length += clen;
			}
		} while(clen);
		text = malloc(length+1);
		text[0] = '\0';
		while((temp = list_pop_head(buf))) {
			sprintf(text, "%s%s", text, temp);
			free(temp);
		}
		list_delete(buf);
	}
	link_close(server);

	if(owner) sscanf(strstr(text, "<Owner>"), "<Owner><ID>%[^<]</ID>", owner);
	temp = text;
	while( (start = strstr(temp, "<Grant>")) ) {
		char id[1024];
		char display_name[1024];
		char permission[1024];
		char type;
		struct s3_acl_object *acl;
		char *end;

		end = strstr(start, "</Grant>");
		end[7] = '\0';
		temp = end + 8;

		memset(display_name, 0, 1024);
		type = S3_ACL_ID;
		if( sscanf(start, "<Grant><Grantee %*[^>]><ID>%[^<]</ID><DisplayName>%[^<]</DisplayName></Grantee><Permission>%[^<]</Permission></Grantee>", id, display_name, permission) != 3 ) {
			type = S3_ACL_URI;
			sscanf(start, "<Grant><Grantee %*[^>]><URI>http://acs.amazonaws.com/groups/global/%[^<]</URI></Grantee><Permission>%[^<]</Permission></Grantee>", id, permission);
		}

		if( !(acl = hash_table_lookup(acls, id)) ) {
			acl = malloc(sizeof(*acl));
			acl->acl_type = type;
			if(*display_name) acl->display_name = strdup(display_name);
			else acl->display_name = NULL;
			acl->perm = 0;
			hash_table_insert(acls, id, acl);
		}

		if(!strcmp(permission, "FULL_CONTROL")) {
			acl->perm = acl->perm | S3_ACL_FULL_CONTROL;
		} else if(!strcmp(permission, "READ")) {
			acl->perm = acl->perm | S3_ACL_READ;
		} else if(!strcmp(permission, "WRITE")) {
			acl->perm = acl->perm | S3_ACL_WRITE;
		} else if(!strcmp(permission, "READ_ACP")) {
			acl->perm = acl->perm | S3_ACL_READ_ACP;
		} else if(!strcmp(permission, "WRITE_ACP")) {
			acl->perm = acl->perm | S3_ACL_WRITE_ACP;
		}
	}

	free(text);
	return 0;
}
Ejemplo n.º 15
0
static int maildir_keywords_sync(struct maildir_keywords *mk)
{
	struct istream *input;
	struct stat st;
	char *line, *p, *new_name;
	const char **strp;
	unsigned int idx;
	int fd;

        /* Remember that we rely on uidlist file locking in here. That's why
           we rely on stat()'s timestamp and don't bother handling ESTALE
           errors. */

	if (mk->storage->set->mail_nfs_storage) {
		/* file is updated only by replacing it, no need to flush
		   attribute cache */
		nfs_flush_file_handle_cache(mk->path);
	}

	if (nfs_safe_stat(mk->path, &st) < 0) {
		if (errno == ENOENT) {
			maildir_keywords_clear(mk);
			mk->synced = TRUE;
			return 0;
		}
                mail_storage_set_critical(mk->storage,
					  "stat(%s) failed: %m", mk->path);
		return -1;
	}

	if (st.st_mtime == mk->synced_mtime) {
		/* hasn't changed */
		mk->synced = TRUE;
		return 0;
	}
	mk->synced_mtime = st.st_mtime;

	fd = open(mk->path, O_RDONLY);
	if (fd == -1) {
		if (errno == ENOENT) {
			maildir_keywords_clear(mk);
			mk->synced = TRUE;
			return 0;
		}
                mail_storage_set_critical(mk->storage,
					  "open(%s) failed: %m", mk->path);
		return -1;
	}

	maildir_keywords_clear(mk);
	input = i_stream_create_fd(fd, 1024, FALSE);
	while ((line = i_stream_read_next_line(input)) != NULL) {
		p = strchr(line, ' ');
		if (p == NULL) {
			/* note that when converting .customflags file this
			   case happens in the first line. */
			continue;
		}
		*p++ = '\0';

		if (str_to_uint(line, &idx) < 0 ||
		    idx >= MAILDIR_MAX_KEYWORDS || *p == '\0') {
			/* shouldn't happen */
			continue;
		}

		/* save it */
		new_name = p_strdup(mk->pool, p);
		hash_table_insert(mk->hash, new_name, POINTER_CAST(idx + 1));

		strp = array_idx_modifiable(&mk->list, idx);
		*strp = new_name;
	}
	i_stream_destroy(&input);

	if (close(fd) < 0) {
                mail_storage_set_critical(mk->storage,
					  "close(%s) failed: %m", mk->path);
		return -1;
	}

	mk->synced = TRUE;
	return 0;
}
Ejemplo n.º 16
0
static int log_play( struct deltadb *db, FILE *stream )
{
	time_t current = 0;
	time_t previous_time = 0;
	int line_number = 0;

	char line[NVPAIR_LINE_MAX];
	char key[NVPAIR_LINE_MAX];
	char name[NVPAIR_LINE_MAX];
	char value[NVPAIR_LINE_MAX];
	char oper;
	
	while(fgets(line,sizeof(line),stream)) {
		//debug(D_NOTICE,"Processed line: %s",line);
		line_number += 1;
		
		if (line[0]=='\n') break;
		
		int n = sscanf(line,"%c %s %s %[^\n]",&oper,key,name,value);
		if(n<1) continue;
		
		struct nvpair *nv;
		
		switch(oper) {
			case 'C':
				nv = nvpair_create();
				int num_pairs = nvpair_parse_stream(nv,stream);
				if(num_pairs>0) {
					nvpair_delete(hash_table_remove(db->table,key));
					hash_table_insert(db->table,key,nv);
				} else if (num_pairs == -1) {
					nvpair_delete(nv);
					break;
				} else {
					nvpair_delete(nv);
				}


				break;
			case 'D':
				nv = hash_table_remove(db->table,key);
				if(nv) nvpair_delete(nv);
				break;
			case 'U':
				nv = hash_table_lookup(db->table,key);
				if(nv) nvpair_insert_string(nv,name,value);
				break;
			case 'R':
				nv = hash_table_lookup(db->table,key);
				if(nv) nvpair_remove(nv,name);
				break;
			case 'T':
				previous_time = current;
				current = atol(key);
				emit_table_values(db,previous_time);
				break;
			default:
				debug(D_NOTICE,"corrupt log data[%i]: %s",line_number,line);
				fflush(stderr);
				break;
		}
	}
	emit_table_values(db,current);
	return 1;
}
static int mailbox_list_index_parse_records(struct mailbox_list_index *ilist,
					    struct mail_index_view *view,
					    const char **error_r)
{
	struct mailbox_list_index_node *node;
	const struct mail_index_record *rec;
	const struct mailbox_list_index_record *irec;
	const void *data;
	bool expunged;
	uint32_t seq, uid, count;

	*error_r = NULL;

	count = mail_index_view_get_messages_count(view);
	for (seq = 1; seq <= count; seq++) {
		node = p_new(ilist->mailbox_pool,
			     struct mailbox_list_index_node, 1);
		rec = mail_index_lookup(view, seq);
		node->uid = rec->uid;
		node->flags = rec->flags;

		mail_index_lookup_ext(view, seq, ilist->ext_id,
				      &data, &expunged);
		if (data == NULL) {
			*error_r = "Missing list extension data";
			return -1;
		}
		irec = data;

		node->name_id = irec->name_id;
		node->name = hash_table_lookup(ilist->mailbox_names,
					       POINTER_CAST(irec->name_id));
		if (node->name == NULL) {
			*error_r = "name_id not in index header";
			if (ilist->has_backing_store)
				return -1;
			/* generate a new name and use it */
			mailbox_list_index_generate_name(ilist, node);
		}
		hash_table_insert(ilist->mailbox_hash,
				  POINTER_CAST(node->uid), node);
	}

	/* do a second scan to create the actual mailbox tree hierarchy.
	   this is needed because the parent_uid may be smaller or higher than
	   the current node's uid */
	for (seq = 1; seq <= count; seq++) {
		mail_index_lookup_uid(view, seq, &uid);
		mail_index_lookup_ext(view, seq, ilist->ext_id,
				      &data, &expunged);
		irec = data;

		node = mailbox_list_index_lookup_uid(ilist, uid);
		i_assert(node != NULL);

		if (irec->parent_uid != 0) {
			/* node should have a parent */
			node->parent = mailbox_list_index_lookup_uid(ilist,
							irec->parent_uid);
			if (node->parent != NULL) {
				node->next = node->parent->children;
				node->parent->children = node;
				continue;
			}
			*error_r = "parent_uid points to nonexistent record";
			if (ilist->has_backing_store)
				return -1;
			/* just place it under the root */
		}
		node->next = ilist->mailbox_tree;
		ilist->mailbox_tree = node;
	}
	return *error_r == NULL ? 0 : -1;
}
Ejemplo n.º 18
0
void dram_system_read_config(void)
{
	int i ;
	struct config_t *config;
	struct list_t *dram_system_list;
	char *section;

	if (!*dram_config_file_name)
	{
		dram_domain_index = esim_new_domain(dram_frequency);
		return;
	}

	config = config_create(dram_config_file_name);
	if (*dram_config_file_name)
		config_load(config);

	/* Section with Generic Configuration Parameters */
	section = "General";

	/* Frequency */
	dram_frequency = config_read_int(config, section, "Frequency", dram_frequency);
	if (!IN_RANGE(dram_frequency, 1, ESIM_MAX_FREQUENCY))
		fatal("%s: Invalid value for 'Frequency'", dram_config_file_name);

	/* Creating the Frequency Domain */
	dram_domain_index = esim_new_domain(dram_frequency);

	/* Create a temporary List of all Dram Systems found in
	 * the configuration file */
	dram_system_list = list_create();
	for (section = config_section_first(config); section;
			section = config_section_next(config))
	{
		char *delim = ".";

		char section_str[MAX_STRING_SIZE];
		char *token;
		char *dram_system_name;

		/*Creating a copy of the name of the section */
		snprintf(section_str, sizeof section_str, "%s", section);
		section = section_str;

		/* First Token Must be 'DRAMsystem' */
		token = strtok(section, delim);
		if (strcasecmp(token, "DRAMsystem"))
			continue;

		/* Second Token must be the system Name */
		dram_system_name = strtok(NULL, delim);
		if (!dram_system_name)
			continue;

		/* No third term is required */
		token = strtok(NULL, delim);
		if (token)
			continue;

		/* Insert the new DRAM system name */
		dram_system_name = xstrdup(dram_system_name);
		list_add(dram_system_list, dram_system_name);
	}

	/* Print DRAM system Names in debug */
	dram_debug("%s: loading DRAM system configuration file \n",
			dram_config_file_name);
	dram_debug("DRAM systems found:\n");
	for (i = 0; i < dram_system_list->count; i++)
		dram_debug("\t%s\n", (char *) list_get(dram_system_list, i));
	dram_debug("\n");

	/* Load DRAM systems */
	dram_system_table = hash_table_create(0, 0);
	for ( i = 0; i < dram_system_list->count; i++)
	{
		struct dram_system_t *system;
		char *dram_system_name;

		dram_system_name = list_get(dram_system_list, i);
		system = dram_system_config_with_file(config, dram_system_name);

		hash_table_insert(dram_system_table, dram_system_name, system);
	}
	while (dram_system_list->count)
		free(list_remove_at(dram_system_list, 0));
	list_free(dram_system_list);
	config_free(config);
}
Ejemplo n.º 19
0
/* 
 * main code
 * */
int main(int argc, char *argv[]) {
	Option *option;
	FILE *fp;
	char buffer[BUFSIZ];
	HashTable *hash_table = NULL;
	YoutubeID youtube_id;
	int num_record_readed = 0,
		num_record_added = 0;

	/* parse option */
	option = option_new(argc, argv);
	if (strcmp(option->id_list_path, "") == 0|| option->size_hash_table == 0) {
		printf_help_info();
		exit(0);
	}

	/* open id list file */
	fp = fopen(option->id_list_path, "a+");
	if (fp == NULL) {
		printf("open id list file '%s' fail\n", option->id_list_path);
		exit(0);
	}

	/* create hash table */
	hash_table = hash_table_new(option->size_hash_table);
	fseek(fp, 0, SEEK_SET);
	while (fgets(buffer, BUFSIZ, fp) != NULL) {
		buffer[strlen(buffer) - 1] = '\0'; // delete '\n'
		hash_table_insert(hash_table, (YoutubeID*) buffer);
	}
	fseek(fp, 0, SEEK_END);

	fprintf(stderr, "INFO: hash_table->size  = %zd\n", hash_table->size);
	fprintf(stderr, "INFO: hash_table->count = %zd\n", hash_table->count);

	/* filte input */
	while (fgets(buffer, BUFSIZ, stdin) != NULL) {
		if (extract_video_id(buffer, (char*) &youtube_id)) {
			if (!hash_table_find(hash_table, &youtube_id)) {
				fputs(buffer, stdout);
				hash_table_insert(hash_table, &youtube_id);
				fprintf(fp, "%s\n", youtube_id.id);
				num_record_added++;
				if (hash_table_is_fulled(hash_table)) {
					fprintf(stderr, "ERROR: the hash table is full!\n");
					fprintf(stderr, "hash table size: %zd\n", hash_table->size);
					exit(0);
				}
			}
		}

		num_record_readed++;
	}
	fprintf(stderr, "INFO: num_record_readed = %d\n", num_record_readed);
	fprintf(stderr, "INFO: num_record_added  = %d\n", num_record_added);

	
	
	fclose(fp);
	hash_table_free(hash_table);

	return 0;
}
void
flatten_named_interface_blocks_declarations::run(exec_list *instructions)
{
   interface_namespace = hash_table_ctor(0, hash_table_string_hash,
                                         hash_table_string_compare);

   /* First pass: adjust instance block variables with an instance name
    * to not have an instance name.
    *
    * The interface block variables are stored in the interface_namespace
    * hash table so they can be used in the second pass.
    */
   foreach_list_safe(node, instructions) {
      ir_variable *var = ((ir_instruction *) node)->as_variable();
      if (!var || !var->is_interface_instance())
         continue;

      /* It should be possible to handle uniforms during this pass,
       * but, this will require changes to the other uniform block
       * support code.
       */
      if (var->data.mode == ir_var_uniform)
         continue;

      const glsl_type * iface_t = var->type;
      const glsl_type * array_t = NULL;
      exec_node *insert_pos = var;

      if (iface_t->is_array()) {
         array_t = iface_t;
         iface_t = array_t->fields.array;
      }

      assert (iface_t->is_interface());

      for (unsigned i = 0; i < iface_t->length; i++) {
         const char * field_name = iface_t->fields.structure[i].name;
         char *iface_field_name =
            ralloc_asprintf(mem_ctx, "%s.%s.%s",
                            iface_t->name, var->name, field_name);

         ir_variable *found_var =
            (ir_variable *) hash_table_find(interface_namespace,
                                            iface_field_name);
         if (!found_var) {
            ir_variable *new_var;
            char *var_name =
               ralloc_strdup(mem_ctx, iface_t->fields.structure[i].name);
            if (array_t == NULL) {
               new_var =
                  new(mem_ctx) ir_variable(iface_t->fields.structure[i].type,
                                           var_name,
                                           (ir_variable_mode) var->data.mode);
               new_var->data.from_named_ifc_block_nonarray = 1;
            } else {
               const glsl_type *new_array_type =
                  glsl_type::get_array_instance(
                     iface_t->fields.structure[i].type,
                     array_t->length);
               new_var =
                  new(mem_ctx) ir_variable(new_array_type,
                                           var_name,
                                           (ir_variable_mode) var->data.mode);
               new_var->data.from_named_ifc_block_array = 1;
            }
            new_var->data.location = iface_t->fields.structure[i].location;
            new_var->data.explicit_location = (new_var->data.location >= 0);
            new_var->data.interpolation =
               iface_t->fields.structure[i].interpolation;
            new_var->data.centroid = iface_t->fields.structure[i].centroid;
            new_var->data.sample = iface_t->fields.structure[i].sample;

            new_var->init_interface_type(iface_t);
            hash_table_insert(interface_namespace, new_var,
                              iface_field_name);
            insert_pos->insert_after(new_var);
            insert_pos = new_var;
         }
      }
      var->remove();
   }
Ejemplo n.º 21
0
// insert into the current scope an entry binding a name to a symbol object
void scope_bind(const char * name, struct symbol *sym){
	hash_table_insert(h, name, sym);
}  
Ejemplo n.º 22
0
int mail_session_connect_parse(const char *const *args, const char **error_r)
{
	struct mail_session *session;
	guid_128_t session_guid;
	uint8_t *guid_p;
	pid_t pid;
	struct ip_addr ip;
	unsigned int i;

	/* <session guid> <username> <service> <pid> [key=value ..] */
	if (str_array_length(args) < 4) {
		*error_r = "CONNECT: Too few parameters";
		return -1;
	}
	if (guid_128_from_string(args[0], session_guid) < 0) {
		*error_r = "CONNECT: Invalid GUID";
		return -1;
	}
	if (str_to_pid(args[3], &pid) < 0) {
		*error_r = "CONNECT: Invalid pid";
		return -1;
	}

	guid_p = session_guid;
	session = hash_table_lookup(mail_sessions_hash, guid_p);
	if (session != NULL) {
		*error_r = "CONNECT: Duplicate session GUID";
		return -1;
	}
	session = i_new(struct mail_session, 1);
	session->refcount = 1; /* unrefed at disconnect */
	session->service = i_strdup(args[2]);
	memcpy(session->guid, session_guid, sizeof(session->guid));
	session->pid = pid;
	session->last_update = ioloop_timeval;
	session->to_idle = timeout_add(MAIL_SESSION_IDLE_TIMEOUT_MSECS,
				       mail_session_idle_timeout, session);

	session->user = mail_user_login(args[1]);
	for (i = 3; args[i] != NULL; i++) {
		if (strncmp(args[i], "rip=", 4) == 0 &&
		    net_addr2ip(args[i] + 4, &ip) == 0)
			session->ip = mail_ip_login(&ip);
	}

	guid_p = session->guid;
	hash_table_insert(mail_sessions_hash, guid_p, session);
	DLLIST_PREPEND_FULL(&stable_mail_sessions, session,
			    stable_prev, stable_next);
	DLLIST2_APPEND_FULL(&mail_sessions_head, &mail_sessions_tail, session,
			    sorted_prev, sorted_next);
	DLLIST_PREPEND_FULL(&session->user->sessions, session,
			    user_prev, user_next);
	mail_user_ref(session->user);
	if (session->ip != NULL) {
		DLLIST_PREPEND_FULL(&session->ip->sessions, session,
				    ip_prev, ip_next);
		mail_ip_ref(session->ip);
	}
	global_memory_alloc(mail_session_memsize(session));
	return 0;
}
Ejemplo n.º 23
0
int main(int argc, char **argv)
{
	int n, a, b, choice, ris, i, j;
	int *path;
	char tmp1[MAX_STR], tmp2[MAX_STR];
	Hash_table ht;
	Graph g;
	FILE *fp;

	if(argc < 2){
		fprintf(stderr, "Parameters error!\nUsage: %s <input file>\n", argv[0]);
		return -1;
	}

	if((fp=fopen(argv[1], "r")) == NULL){
		fprintf(stderr, "Can't open file %s\n", argv[1]);
		return -2;
	}

	fscanf(fp, "%d", &n);
	ht = hash_table_init(n);
	g  = graph_init(n);

	while(fscanf(fp, "%s %s", tmp1, tmp2) == 2)
	{
		if((a = hash_table_get(ht, tmp1)) == -1)
			a = hash_table_insert(ht, tmp1);
		if((b = hash_table_get(ht, tmp2)) == -1)
			b = hash_table_insert(ht, tmp2);
		graph_insert(g, create_edge(a,b));
	}
	fclose(fp);

	printf( "===== G R A P H =====\n"
		"1 - Shortest simple path between two nodes\n"
		"2 - Longest simple path between two nodes\n"
		"3 - Number of all simple paths between two nodes\n"
		"4 - Show strong connected nodes\n"
		"5 - Show edges to strong connect the graph\n"
		"6 - Exit\n");

	do{
		printf("\nChoice: ");
		scanf("%d", &choice);
		switch(choice)
		{
			case 1:
				printf("Start node: ");
				scanf("%s", tmp1);
				printf("End node:   ");
				scanf("%s", tmp2);
				if(hash_table_get(ht, tmp1) != -1 && hash_table_get(ht, tmp2) != -1)
				{
					ris = graph_get_shortest_path(g, hash_table_get(ht, tmp1), hash_table_get(ht, tmp2), &path);
					if(ris > 0)
					{
						printf("\nDistance = %d\n\nPath:\n", ris);
						for(i=0; i<=ris; i++)
							printf("%s\n", hash_table_get_name(ht, path[i]));
						free(path);
					}
					else
						printf("There is no path between these two nodes\n");
				}
				else
					printf("Error, inexistent nodes\n");
			break;

			case 2:
				printf("Start node: ");
				scanf("%s", tmp1);
				printf("End node:   ");
				scanf("%s", tmp2);
				if(hash_table_get(ht, tmp1) != -1 && hash_table_get(ht, tmp2) != -1)
				{
					ris = graph_get_longest_path(g, hash_table_get(ht, tmp1), hash_table_get(ht, tmp2), &path);
					if(ris > 0)
					{
						printf("\nDistance = %d\n\nPath:\n", ris);
						for(i=0; i<=ris; i++)
							printf("%s\n", hash_table_get_name(ht, path[i]));
						free(path);
					}
					else
						printf("There is no path between these two nodes\n");
				} 
				else
					printf("Error, inexistent nodes\n");
			break;
			
			case 3:
				printf("Start node: ");
				scanf("%s", tmp1);
				printf("End node:   ");
				scanf("%s", tmp2);
				if(hash_table_get(ht, tmp1) != -1 && hash_table_get(ht, tmp2) != -1)
					printf("Number of simple paths: %d\n",
							graph_number_of_simple_path(g, hash_table_get(ht, tmp1), hash_table_get(ht, tmp2)));	
				else
					printf("Error, inexistent nodes\n");
			break;
			case 4:
				path = graph_get_scc(g);
				//for every scc group
				for(i=0; i<n; i++)
				{
					a = 0;	//counter
					for(j=0; j<n; j++)
						if(path[j] == i)
						{
							printf("%s\n", hash_table_get_name(ht, j));
							a++;
						}
					if(a != 0)
						printf("============\n");
					else
						break;
				}
			break;
		}
	}while(choice != 6);

	hash_table_destroy(ht);
	graph_destroy(g);

	return 0;
}
Ejemplo n.º 24
0
static struct irods_server * connect_to_host( const char *hostport )
{
	struct irods_server *server;
	rcComm_t *conn;
	rErrMsg_t errmsg;
	char host[PFS_PATH_MAX];
	int port;

	if(!hostport[0]) {
		errno = EACCES;
		return 0;
	}

	if(!connect_cache) connect_cache = hash_table_create(0,0);

	time_t current = time(0);

	server = (struct irods_server*) hash_table_lookup(connect_cache,hostport);
	if(server) {
		if((current-server->lastused)>DISCONNECT_TIMEOUT) {
			debug(D_IRODS,"discarding stale connection to %s",hostport);
			rcDisconnect(server->conn);
			free(server);
			server = 0;
		} else {
			server->lastused = current;
			return server;
		}
	}

	if(!got_irods_env) {
		rodsLogLevel(pfs_irods_debug_level);
		if(getRodsEnv(&irods_env)<0) {
			debug(D_IRODS,"couldn't load irods environment!");
			return 0;
		}
		got_irods_env = 1;
	}

	debug(D_IRODS,"connecting to %s",hostport);

	sscanf(hostport,"%[^:]:%d",host,&port);

	conn = rcConnect(host,port,irods_env.rodsUserName,irods_env.rodsZone,1,&errmsg);
	if(!conn) {
		if(errno==EINPROGRESS) {
			errno = ECONNREFUSED;
		}
		debug(D_IRODS,"couldn't connect: %s\n",strerror(errno));
		return 0;
	}

	debug(D_IRODS,"logging in...");

	if(clientLogin(conn)!=0) {
		debug(D_IRODS,"unable to login as %s",irods_env.rodsUserName);
		rcDisconnect(conn);
		return 0;
	}

	server = malloc(sizeof(*server));
	server->conn = conn;
	server->lastused = current;
	server->serial = irods_serial++;

	hash_table_insert(connect_cache,hostport,server);

	return server;
}
Ejemplo n.º 25
0
static int log_replay( struct jx_database *db, const char *filename, time_t snapshot)
{
	char line[LOG_LINE_MAX];
	char value[LOG_LINE_MAX];
	char name[LOG_LINE_MAX];
	char key[LOG_LINE_MAX];
	int n;
	struct jx *jvalue, *jobject;

	long long current = 0;

	FILE *file = fopen(filename,"r");
	if(!file) return 0;

	while(fgets(line,sizeof(line),file)) {
		if(line[0]=='C') {
			n = sscanf(line,"C %s %[^\n]",key,value);
			if(n==1) {
				struct nvpair *nv = nvpair_create();
				nvpair_parse_stream(nv,file);
				jvalue = nvpair_to_jx(nv);
				hash_table_insert(db->table,key,jvalue);
			} else if(n==2) {
				jvalue = jx_parse_string(value);
				if(jvalue) {
					hash_table_insert(db->table,key,jvalue);
				} else {
					corrupt_data(filename,line);
				}
			} else {
				corrupt_data(filename,line);
				continue;
			}
		} else if(line[0]=='D') {
			n = sscanf(line,"D %s\n",key);
			if(n!=1) {
				corrupt_data(filename,line);
				continue;
			}
			jx_delete(hash_table_remove(db->table,key));
		} else if(line[0]=='U') {
			n=sscanf(line,"U %s %s %[^\n],",key,name,value);
			if(n!=3) {
				corrupt_data(filename,line);
				continue;
			}
			jobject = hash_table_lookup(db->table,key);
			if(!jobject) {
				corrupt_data(filename,line);
				continue;
			}
			jvalue = jx_parse_string(value);
			if(!jvalue) jvalue = jx_string(value);

			struct jx *jname = jx_string(name);
			jx_delete(jx_remove(jobject,jname));
			jx_insert(jobject,jname,jvalue);
		} else if(line[0]=='R') {
			n=sscanf(line,"R %s %s",key,name);
			if(n!=2) {
				corrupt_data(filename,line);
				continue;
			}
			jobject = hash_table_lookup(db->table,key);
			if(!jobject) {
				corrupt_data(filename,line);
				continue;
			}
			struct jx *jname = jx_string(name);
			jx_delete(jx_remove(jobject,jname));
			jx_delete(jname);
		} else if(line[0]=='T') {
			n = sscanf(line,"T %lld",&current);
			if(n!=1) {
				corrupt_data(filename,line);
				continue;
			}
			if(current>snapshot) break;
		} else if(line[0]=='\n') {
			continue;
		} else {
			corrupt_data(filename,line);
		}

	}

	fclose(file);
	return 1;
}
Ejemplo n.º 26
0
static int tls_drv_control(ErlDrvData handle,
			   unsigned int command,
			   char *buf, int len,
			   char **rbuf, int rlen)
{
   tls_data *d = (tls_data *)handle;
   int res;
   int size;
   ErlDrvBinary *b;
   X509 *cert;
   unsigned int flags = command;

   command &= 0xffff;

   ERR_clear_error();
   switch (command)
   {
      case SET_CERTIFICATE_FILE_ACCEPT:
      case SET_CERTIFICATE_FILE_CONNECT: {
	 time_t mtime = 0;
	 SSL_CTX *ssl_ctx = hash_table_lookup(buf, &mtime);
	 if (is_key_file_modified(buf, &mtime) || ssl_ctx == NULL)
	 {
	    SSL_CTX *ctx;

	    hash_table_insert(buf, mtime, NULL);

	    ctx = SSL_CTX_new(SSLv23_method());
	    die_unless(ctx, "SSL_CTX_new failed");

	    res = SSL_CTX_use_certificate_chain_file(ctx, buf);
	    die_unless(res > 0, "SSL_CTX_use_certificate_file failed");

	    res = SSL_CTX_use_PrivateKey_file(ctx, buf, SSL_FILETYPE_PEM);
	    die_unless(res > 0, "SSL_CTX_use_PrivateKey_file failed");

	    res = SSL_CTX_check_private_key(ctx);
	    die_unless(res > 0, "SSL_CTX_check_private_key failed");

	    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
	    SSL_CTX_set_default_verify_paths(ctx);
#ifdef SSL_MODE_RELEASE_BUFFERS
	    SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
#endif

	    if (command == SET_CERTIFICATE_FILE_ACCEPT)
	    {
	       SSL_CTX_set_verify(ctx,
				  SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
				  verify_callback);
	    }

	    ssl_ctx = ctx;
	    hash_table_insert(buf, mtime, ssl_ctx);
	 }

	 d->ssl = SSL_new(ssl_ctx);
	 die_unless(d->ssl, "SSL_new failed");

	 if (flags & VERIFY_NONE)
	    SSL_set_verify(d->ssl, SSL_VERIFY_NONE, verify_callback);

	 d->bio_read = BIO_new(BIO_s_mem());
	 d->bio_write = BIO_new(BIO_s_mem());

	 SSL_set_bio(d->ssl, d->bio_read, d->bio_write);

	 if (command == SET_CERTIFICATE_FILE_ACCEPT) {
	    SSL_set_options(d->ssl, SSL_OP_NO_TICKET);
	    SSL_set_accept_state(d->ssl);
	 } else {
	    SSL_set_options(d->ssl, SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
	    SSL_set_connect_state(d->ssl);
	 }
	 break;
      }
      case SET_ENCRYPTED_INPUT:
	 die_unless(d->ssl, "SSL not initialized");
	 BIO_write(d->bio_read, buf, len);
	 break;
      case SET_DECRYPTED_OUTPUT:
	 die_unless(d->ssl, "SSL not initialized");
	 res = SSL_write(d->ssl, buf, len);
	 if (res <= 0) 
	 {
	    res = SSL_get_error(d->ssl, res);
	    if (res == SSL_ERROR_WANT_READ || res == SSL_ERROR_WANT_WRITE) 
	    {
	       b = driver_alloc_binary(1);
	       b->orig_bytes[0] = 2;
	       *rbuf = (char *)b;
	       return 1;
	    } else {
	       die_unless(0, "SSL_write failed");
	    }
	 }
	 break;
      case GET_ENCRYPTED_OUTPUT:
	 die_unless(d->ssl, "SSL not initialized");
	 size = BUF_SIZE + 1;
	 rlen = 1;
	 b = driver_alloc_binary(size);
	 b->orig_bytes[0] = 0;
	 while ((res = BIO_read(d->bio_write,
				b->orig_bytes + rlen, BUF_SIZE)) > 0)
	 {
	    //printf("%d bytes of encrypted data read from state machine\r\n", res);

	    rlen += res;
	    size += BUF_SIZE;
	    b = driver_realloc_binary(b, size);
	 }
	 b = driver_realloc_binary(b, rlen);
	 *rbuf = (char *)b;
	 return rlen;
      case GET_DECRYPTED_INPUT:
	 if (!SSL_is_init_finished(d->ssl))
	 {
	    res = SSL_do_handshake(d->ssl);
	    if (res <= 0)
	       die_unless(SSL_get_error(d->ssl, res) == SSL_ERROR_WANT_READ,
			  "SSL_do_handshake failed");
	 } else {
	    size = BUF_SIZE + 1;
	    rlen = 1;
	    b = driver_alloc_binary(size);
	    b->orig_bytes[0] = 0;

	    while ((res = SSL_read(d->ssl,
				   b->orig_bytes + rlen, BUF_SIZE)) > 0)
	    {
	       //printf("%d bytes of decrypted data read from state machine\r\n",res);
	       rlen += res;
	       size += BUF_SIZE;
	       b = driver_realloc_binary(b, size);
	    }

	    if (res < 0)
	    {
	       int err = SSL_get_error(d->ssl, res);

	       if (err == SSL_ERROR_WANT_READ)
	       {
		  //printf("SSL_read wants more data\r\n");
		  //return 0;
	       }
	       // TODO
	    }
	    b = driver_realloc_binary(b, rlen);
	    *rbuf = (char *)b;
	    return rlen;
	 }
	 break;
      case GET_PEER_CERTIFICATE:
	 cert = SSL_get_peer_certificate(d->ssl);
	 if (cert == NULL)
	 {
	    b = driver_alloc_binary(1);
	    b->orig_bytes[0] = 1;
	    *rbuf = (char *)b;
	    return 1;
	 } else {
	    unsigned char *tmp_buf;
	    rlen = i2d_X509(cert, NULL);
	    if (rlen >= 0)
	    {
	       rlen++;
	       b = driver_alloc_binary(rlen);
	       b->orig_bytes[0] = 0;
	       tmp_buf = (unsigned char *)&b->orig_bytes[1];
	       i2d_X509(cert, &tmp_buf);
	       X509_free(cert);
	       *rbuf = (char *)b;
	       return rlen;
	    } else
	       X509_free(cert);
	 }
	 break;
      case GET_VERIFY_RESULT:
	 b = driver_alloc_binary(1);
	 b->orig_bytes[0] = SSL_get_verify_result(d->ssl);
	 *rbuf = (char *)b;
	 return 1;
	 break;
   }

   b = driver_alloc_binary(1);
   b->orig_bytes[0] = 0;
   *rbuf = (char *)b;
   return 1;
}
Ejemplo n.º 27
0
/*
 * Reload trusted table to new hash table and when done, make new hash table
 * current one.
 */
int reload_trusted_table(void)
{
	db_key_t cols[6];
	db1_res_t* res = NULL;
	db_row_t* row;
	db_val_t* val;

	struct trusted_list **new_hash_table;
	struct trusted_list **old_hash_table;
	int i;
	int priority;

	char *pattern, *ruri_pattern, *tag;

	if (hash_table == 0) {
	    LM_ERR("in-memory hash table not initialized\n");
	    return -1;
	}

	if (db_handle == 0) {
	    LM_ERR("no connection to database\n");
	    return -1;
	}

	cols[0] = &source_col;
	cols[1] = &proto_col;
	cols[2] = &from_col;
	cols[3] = &ruri_col;
	cols[4] = &tag_col;
	cols[5] = &priority_col;

	if (perm_dbf.use_table(db_handle, &trusted_table) < 0) {
		LM_ERR("failed to use trusted table\n");
		return -1;
	}

	if (perm_dbf.query(db_handle, NULL, 0, NULL, cols, 0, 6, 0, &res) < 0) {
		LM_ERR("failed to query database\n");
		return -1;
	}

	/* Choose new hash table and free its old contents */
	if (*hash_table == hash_table_1) {
		new_hash_table = hash_table_2;
	} else {
		new_hash_table = hash_table_1;
	}
	empty_hash_table(new_hash_table);

	row = RES_ROWS(res);

	LM_DBG("number of rows in trusted table: %d\n", RES_ROW_N(res));
		
	for (i = 0; i < RES_ROW_N(res); i++) {
	    val = ROW_VALUES(row + i);
	    if ((ROW_N(row + i) == 6) &&
		((VAL_TYPE(val) == DB1_STRING) || (VAL_TYPE(val) == DB1_STR) ) && 
		!VAL_NULL(val) &&
		((VAL_TYPE(val + 1) == DB1_STRING) || (VAL_TYPE(val + 1) == DB1_STR))
		&& !VAL_NULL(val + 1) &&
		(VAL_NULL(val + 2) ||
		 (((VAL_TYPE(val + 2) == DB1_STRING) || (VAL_TYPE(val + 2) == DB1_STR)) &&
		!VAL_NULL(val + 2))) && (VAL_NULL(val + 3) ||
		 (((VAL_TYPE(val + 3) == DB1_STRING) || (VAL_TYPE(val + 3) == DB1_STR) )&&
		!VAL_NULL(val + 3))) && (VAL_NULL(val + 4) ||
		 (((VAL_TYPE(val + 4) == DB1_STRING) || (VAL_TYPE(val + 4) == DB1_STR) )&&
		!VAL_NULL(val + 4)))) {
		if (VAL_NULL(val + 2)) {
		    pattern = 0;
		} else {
		    pattern = (char *)VAL_STRING(val + 2);
		}
		if (VAL_NULL(val + 3)) {
		    ruri_pattern = 0;
		} else {
		    ruri_pattern = (char *)VAL_STRING(val + 3);
		}
		if (VAL_NULL(val + 4)) {
		    tag = 0;
		} else {
		    tag = (char *)VAL_STRING(val + 4);
		}
		if (VAL_NULL(val + 5)) {
		    priority = 0;
		} else {
		    priority = (int)VAL_INT(val + 5);
		}
		if (hash_table_insert(new_hash_table,
				      (char *)VAL_STRING(val),
				      (char *)VAL_STRING(val + 1),
				      pattern, ruri_pattern, tag, priority) == -1) {
		    LM_ERR("hash table problem\n");
		    perm_dbf.free_result(db_handle, res);
		    empty_hash_table(new_hash_table);
		    return -1;
		}
		LM_DBG("tuple <%s, %s, %s, %s, %s> inserted into trusted hash "
		    "table\n", VAL_STRING(val), VAL_STRING(val + 1),
		    pattern, ruri_pattern, tag);
	    } else {
		LM_ERR("database problem\n");
		perm_dbf.free_result(db_handle, res);
		empty_hash_table(new_hash_table);
		return -1;
	    }
	}

	perm_dbf.free_result(db_handle, res);

	old_hash_table = *hash_table;
	*hash_table = new_hash_table;
	empty_hash_table(old_hash_table);

	LM_DBG("trusted table reloaded successfully.\n");
	
	return 1;
}
Ejemplo n.º 28
0
void net_read_config(void) {
    struct config_t *config;
    struct list_t *net_name_list;
    char *section;
    int i;

    /* Configuration file */
    if (!*net_config_file_name) {
        net_domain_index = esim_new_domain(net_frequency);
        return;
    }

    /* Open network configuration file */
    config = config_create(net_config_file_name);
    if (*net_config_file_name) config_load(config);

    /* Section with generic configuration parameters */
    section = "General";

    /* Frequency */
    net_frequency = config_read_int(config, section, "Frequency", net_frequency);
    if (!IN_RANGE(net_frequency, 1, ESIM_MAX_FREQUENCY))
        fatal("%s: invalid value for 'Frequency'", net_config_file_name);

    /* Create frequency domain */
    net_domain_index = esim_new_domain(net_frequency);

    /* Create a temporary list of network names found in configuration
     * file */
    net_name_list = list_create();
    for (section = config_section_first(config); section;
            section = config_section_next(config)) {
        char *delim = ".";

        char section_str[MAX_STRING_SIZE];
        char *token;
        char *net_name;

        /* Create a copy of section name */
        snprintf(section_str, sizeof section_str, "%s", section);
        section = section_str;

        /* First token must be 'Network' */
        token = strtok(section, delim);
        if (strcasecmp(token, "Network")) continue;

        /* Second token is network name */
        net_name = strtok(NULL, delim);
        if (!net_name) continue;

        /* No third token */
        token = strtok(NULL, delim);
        if (token) continue;

        /* Insert new network name */
        net_name = xstrdup(net_name);
        list_add(net_name_list, net_name);
    }

    /* Print network names */
    net_debug("%s: loading network configuration file\n", net_config_file_name);
    net_debug("networks found:\n");
    for (i = 0; i < net_name_list->count; i++)
        net_debug("\t%s\n", (char *)list_get(net_name_list, i));
    net_debug("\n");

    /* Load networks */
    net_table = hash_table_create(0, 0);
    for (i = 0; i < net_name_list->count; i++) {
        struct net_t *network;
        char *net_name;

        net_name = list_get(net_name_list, i);
        network = net_create_from_config(config, net_name);

        hash_table_insert(net_table, net_name, network);
    }

    /* Free list of network names and configuration file */
    while (net_name_list->count) free(list_remove_at(net_name_list, 0));
    list_free(net_name_list);
    config_free(config);
}
Ejemplo n.º 29
0
struct service_process *service_process_create(struct service *service)
{
	static unsigned int uid_counter = 0;
	struct service_process *process;
	unsigned int uid = ++uid_counter;
	const char *hostdomain;
	pid_t pid;
	bool process_forked;

	i_assert(service->status_fd[0] != -1);

	if (service->to_throttle != NULL) {
		/* throttling service, don't create new processes */
		return NULL;
	}
	if (service->list->destroying) {
		/* these services are being destroyed, no point in creating
		   new processes now */
		return NULL;
	}
	/* look this up before fork()ing so that it gets cached for all the
	   future lookups. */
	hostdomain = my_hostdomain();

	if (service->type == SERVICE_TYPE_ANVIL &&
	    service_anvil_global->pid != 0) {
		pid = service_anvil_global->pid;
		uid = service_anvil_global->uid;
		process_forked = FALSE;
	} else {
		pid = fork();
		process_forked = TRUE;
		service->list->fork_counter++;
	}

	if (pid < 0) {
		service_error(service, "fork() failed: %m");
		return NULL;
	}
	if (pid == 0) {
		/* child */
		service_process_setup_environment(service, uid, hostdomain);
		service_reopen_inet_listeners(service);
		service_dup_fds(service);
		drop_privileges(service);
		process_exec(service->executable, NULL);
	}
	i_assert(hash_table_lookup(service_pids, POINTER_CAST(pid)) == NULL);

	process = i_new(struct service_process, 1);
	process->service = service;
	process->refcount = 1;
	process->pid = pid;
	process->uid = uid;
	if (process_forked) {
		process->to_status =
			timeout_add(SERVICE_FIRST_STATUS_TIMEOUT_SECS * 1000,
				    service_process_status_timeout, process);
	}

	process->available_count = service->client_limit;
	service->process_count++;
	service->process_avail++;
	DLLIST_PREPEND(&service->processes, process);

	service_list_ref(service->list);
	hash_table_insert(service_pids, POINTER_CAST(process->pid), process);

	if (service->type == SERVICE_TYPE_ANVIL && process_forked)
		service_anvil_process_created(process);
	return process;
}
bool auth_request_handler_auth_begin(struct auth_request_handler *handler,
				     const char *args)
{
	const struct mech_module *mech;
	struct auth_request *request;
	const char *const *list, *name, *arg, *initial_resp;
	void *initial_resp_data;
	unsigned int id;
	buffer_t *buf;

	i_assert(!handler->destroyed);

	/* <id> <mechanism> [...] */
	list = t_strsplit_tab(args);
	if (list[0] == NULL || list[1] == NULL ||
	    str_to_uint(list[0], &id) < 0) {
		i_error("BUG: Authentication client %u "
			"sent broken AUTH request", handler->client_pid);
		return FALSE;
	}

	if (handler->token_auth) {
		mech = &mech_dovecot_token;
		if (strcmp(list[1], mech->mech_name) != 0) {
			/* unsupported mechanism */
			i_error("BUG: Authentication client %u requested invalid "
				"authentication mechanism %s (DOVECOT-TOKEN required)",
				handler->client_pid, str_sanitize(list[1], MAX_MECH_NAME_LEN));
			return FALSE;
		}
	} else {		 
		mech = mech_module_find(list[1]);
		if (mech == NULL) {
			/* unsupported mechanism */
			i_error("BUG: Authentication client %u requested unsupported "
				"authentication mechanism %s", handler->client_pid,
				str_sanitize(list[1], MAX_MECH_NAME_LEN));
			return FALSE;
		}
	}

	request = auth_request_new(mech);
	request->handler = handler;
	request->connect_uid = handler->connect_uid;
	request->client_pid = handler->client_pid;
	request->id = id;
	request->auth_only = handler->master_callback == NULL;

	/* parse optional parameters */
	initial_resp = NULL;
	for (list += 2; *list != NULL; list++) {
		arg = strchr(*list, '=');
		if (arg == NULL) {
			name = *list;
			arg = "";
		} else {
			name = t_strdup_until(*list, arg);
			arg++;
		}

		if (auth_request_import_auth(request, name, arg))
			;
		else if (strcmp(name, "resp") == 0) {
			initial_resp = arg;
			/* this must be the last parameter */
			list++;
			break;
		}
	}

	if (*list != NULL) {
		i_error("BUG: Authentication client %u "
			"sent AUTH parameters after 'resp'",
			handler->client_pid);
		auth_request_unref(&request);
		return FALSE;
	}

	if (request->service == NULL) {
		i_error("BUG: Authentication client %u "
			"didn't specify service in request",
			handler->client_pid);
		auth_request_unref(&request);
		return FALSE;
	}
	if (hash_table_lookup(handler->requests, POINTER_CAST(id)) != NULL) {
		i_error("BUG: Authentication client %u "
			"sent a duplicate ID %u", handler->client_pid, id);
		auth_request_unref(&request);
		return FALSE;
	}
	auth_request_init(request);

	request->to_abort = timeout_add(MASTER_AUTH_SERVER_TIMEOUT_SECS * 1000,
					auth_request_timeout, request);
	hash_table_insert(handler->requests, POINTER_CAST(id), request);

	if (request->set->ssl_require_client_cert &&
	    !request->valid_client_cert) {
		/* we fail without valid certificate */
                auth_request_handler_auth_fail(handler, request,
			"Client didn't present valid SSL certificate");
		return TRUE;
	}

	/* Empty initial response is a "=" base64 string. Completely empty
	   string shouldn't really be sent, but at least Exim does it,
	   so just allow it for backwards compatibility.. */
	if (initial_resp != NULL && *initial_resp != '\0') {
		size_t len = strlen(initial_resp);

		buf = buffer_create_dynamic(pool_datastack_create(),
					    MAX_BASE64_DECODED_SIZE(len));
		if (base64_decode(initial_resp, len, NULL, buf) < 0) {
                        auth_request_handler_auth_fail(handler, request,
				"Invalid base64 data in initial response");
			return TRUE;
		}
		initial_resp_data =
			p_malloc(request->pool, I_MAX(buf->used, 1));
		memcpy(initial_resp_data, buf->data, buf->used);
		request->initial_response = initial_resp_data;
		request->initial_response_len = buf->used;
	}

	/* handler is referenced until auth_request_handler_reply()
	   is called. */
	handler->refcount++;

	/* before we start authenticating, see if we need to wait first */
	auth_penalty_lookup(auth_penalty, request, auth_penalty_callback);
	return TRUE;
}