static int
ssdmd_add(ssd_cache_struct_t *cache_struct, ssdcachemd_entry_t *md_entry,
          log_ctx_t *ctx)
{
    ssdcachelru_entry_t *lru_entry = NULL;
    rb_red_blk_node *node = NULL;
    time_t t;

    // Parameter validation
    if (NULL == cache_struct || NULL == md_entry) {
        sfs_log(ctx, SFS_ERR, "%s: Invalid parameters specified \n",
                __FUNCTION__);
        errno = EINVAL;

        return -1;
    }

    // Insert into md_tree
    pthread_spin_lock(&cache_struct->md_lock);
    node = RBTreeInsert(cache_struct->md_tree,
                        (void *) md_entry->ssd_ce, (void *) md_entry);
    if (NULL == node) {
        sfs_log(ctx, SFS_ERR, "%s: Failed to insert mdentry for ce"
                " %d\n", __FUNCTION__, md_entry->ssd_ce);
        pthread_spin_unlock(&cache_struct->md_lock);

        return -1;
    }
    pthread_spin_lock(&cache_struct->md_lock);

    // Insert into lru_tree
    lru_entry = calloc(sizeof(ssdcachelru_entry_t), 1);
    if (NULL == lru_entry) {
        sfs_log(ctx, SFS_ERR, "%s: Failed to allocate memory for lruentry\n",
                __FUNCTION__);
        RBDelete(cache_struct->md_tree, node);

        return -1;
    }

    t = time(NULL);
    pthread_spin_lock(&cache_struct->lru_lock);
    node = RBTreeInsert(cache_struct->lru_tree,
                        (void*) t, (void *) lru_entry);
    if (NULL == node) {
        sfs_log(ctx, SFS_ERR, "%s: Failed to insert lruentry for ce"
                " %d\n", __FUNCTION__, md_entry->ssd_ce);
        pthread_spin_unlock(&cache_struct->lru_lock);
        free(lru_entry);
        RBDelete(cache_struct->md_tree, node);

        return -1;
    }
    pthread_spin_unlock(&cache_struct->lru_lock);

    return 0;
}
void handle_new_client(Maintainer* maintainer) {
    int new_socket = accept(maintainer->master_socket,
                            (struct sockaddr *)&(maintainer->address),
                            (socklen_t*)&(maintainer->addrlen));
    if (new_socket < 0) {
        logger("<Server><handle_new_client>failure at handle new client accept error\n");
        exit(EXIT_FAILURE);
    }
    logger("<Server><handle_new_client>New connection, socket fd is %d, ip is : %s, port : %d\n",
           new_socket , inet_ntoa(maintainer->address.sin_addr) , ntohs(maintainer->address.sin_port));
    Node* new_node = mymalloc(sizeof(Node));
    init_node(new_node);
    new_node->ip = maintainer->address.sin_addr.s_addr;
    new_node->socket_fd = new_socket;
    new_node->read_msg.total_len = BUFFER_SIZE;
    new_node->write_msg.total_len = BUFFER_SIZE;
    int* new_ip = mymalloc(sizeof(int)); /*TODO memory leak*/
    *new_ip = maintainer->address.sin_addr.s_addr;
    RBTreeInsert(maintainer->nodes_ip, new_ip, new_node);
    FD_SET(new_socket, &(maintainer->fd_read_set));
    FD_SET(new_socket, &(maintainer->fd_exception_set));
    maintainer->max_sd = (maintainer->max_sd > new_socket) ? maintainer->max_sd : new_socket;
    struct Nodes_ll* new_ll_element = mymalloc(sizeof(struct Nodes_ll));
    new_ll_element->node=new_node;
    new_ll_element->next=maintainer->clients;
    maintainer->clients=new_ll_element;
}
//gets the node at that location, creates one if necessary
rb_red_blk_node *get_node(rb_red_blk_tree *tree, int x, unsigned int type) {
  circ_tree_node query_node;
  query_node.pos = x;
  rb_red_blk_node *node = RBExactQuery(tree, &query_node);
  if (!node) { 
    //construct a new tree and copy contents from the one less than this
    circ_tree_node *new_node = (circ_tree_node *) malloc(sizeof(circ_tree_node));
    new_node->type = type;
    new_node->pos = x;
    rb_red_blk_node *node_prev = RBLTEQuery(tree, &query_node);
    circ_tree_node *circ_node_prev;
    if (node_prev)
      circ_node_prev = (circ_tree_node *) node_prev->key;
    if (type == TOP_LEVEL) {
      if (node_prev) { //add the nodes only if the previous is not null
	new_node->data.tree = RBTreeCopy(circ_node_prev->data.tree, circ_tree_node_copy, dummy_fun); 
      } else {
	new_node->data.tree = create_circ_tree_raw();
      }
    } else {
      if (node_prev)
	new_node->data.state = circ_node_prev->data.state;
      else
	new_node->data.state = 0;
    }

    node = RBTreeInsert(tree, new_node, NULL);
  }
  return node;
}
Exemple #4
0
uthread_t *cfs_preemt_current_uthread(kthread_t *k_ctx)
{
	checkpoint("k%d: CFS: Preempting uthread", k_ctx->cpuid);
	uthread_t *cur_uthread = k_ctx->current_uthread;
	if (cur_uthread == NULL)
		return NULL;

	cfs_kthread_t *cfs_kthread = cfs_get_kthread(k_ctx);
	cfs_uthread_t *cfs_cur_uthread = cfs_kthread->current_cfs_uthread;

	if (cur_uthread->state == UTHREAD_DONE) {
		checkpoint("u%d: CFS: uthread done", cur_uthread->tid);
		cfs_kthread->load -= cfs_cur_uthread->priority;
		// FIXME free the node and the uthread?
		return NULL;
	}

	checkpoint("u%d: CFS: uthread still runnable", cur_uthread->tid);
	cur_uthread->state = UTHREAD_RUNNABLE;

	cfs_update_vruntime(cfs_cur_uthread);
	cfs_cur_uthread->key = cfs_cur_uthread->vruntime
	        - cfs_kthread->min_vruntime;

	checkpoint("u%d: CFS: insert into rb tree", cur_uthread->tid);
	RBTreeInsert(cfs_kthread->tree, cfs_cur_uthread->node);

	return cur_uthread;
}
Exemple #5
0
int main()
{
    int w, h, n, x;
    char Cmd[2];
    scanf("%d %d %d", &w, &h, &n);
    RBTreeInitialize(&SetH);
    RBTreeInitialize(&SetV);
    RBTreeInitialize(&LenH);
    RBTreeInitialize(&LenV);
    RBTreeAdd(&SetH, 0);
    RBTreeAdd(&SetH, h);
    RBTreeAdd(&SetV, 0);
    RBTreeAdd(&SetV, w);
    RBTreeAdd(&LenH, h);
    RBTreeAdd(&LenV, w);
    while(n--) {
        scanf("%s %d", Cmd, &x);
        if(Cmd[0] == 'H') {
            struct RBNode_t *node = (struct RBNode_t *)malloc(sizeof(struct RBNode_t));
            node->mKey.mPrimaryVal = x;
            RBTreeInsert(&SetH, node);
            struct RBNode_t *p = RBTreePredecessor(node, &SetH.mSentinelLeaf);
            struct RBNode_t *s = RBTreeSuccessor(node, &SetH.mSentinelLeaf);
            RBTreeDel(&LenH, s->mKey.mPrimaryVal - p->mKey.mPrimaryVal);
            RBTreeAdd(&LenH, x - p->mKey.mPrimaryVal);
            RBTreeAdd(&LenH, s->mKey.mPrimaryVal - x);
        } else {
            struct RBNode_t *node = (struct RBNode_t *)malloc(sizeof(struct RBNode_t));
            node->mKey.mPrimaryVal = x;
            RBTreeInsert(&SetV, node);
            struct RBNode_t *p = RBTreePredecessor(node, &SetV.mSentinelLeaf);
            struct RBNode_t *s = RBTreeSuccessor(node, &SetV.mSentinelLeaf);
            RBTreeDel(&LenV, s->mKey.mPrimaryVal - p->mKey.mPrimaryVal);
            RBTreeAdd(&LenV, x - p->mKey.mPrimaryVal);
            RBTreeAdd(&LenV, s->mKey.mPrimaryVal - x);
        }
        long long Ans = RBTreeMaximum(LenH.mTreeRoot, &LenH.mSentinelLeaf)->mKey.mPrimaryVal;
        Ans *= RBTreeMaximum(LenV.mTreeRoot, &LenV.mSentinelLeaf)->mKey.mPrimaryVal;
        printf("%I64d\n", Ans);
    }
    RBTreeDestroy(&SetH);
    RBTreeDestroy(&SetV);
    RBTreeDestroy(&LenH);
    RBTreeDestroy(&LenV);
    return 0;
}
Exemple #6
0
rb_red_blk_tree* buildEventMap()
{
    printf("--- Generating Event Rule Map ... \n");
    rb_red_blk_tree* EventTree = RBTreeCreate(Compare_EventType,DestroyEventType,DestroyInfoEventKey,PrintEventKey,PrintInfoEventKey);

    if(!EventTree)
    {
        printf("Error Building the Event Rule Map.\n");
        return NULL;
    }

    int i=0;
    term_t a0 = PL_new_term_refs(3);
    term_t b0 = PL_new_term_refs(2);

    static predicate_t p;
    static functor_t event_functor;

    char myEvents[256][256];
    int  arity;
    eventType* temp=NULL;

    if ( !event_functor )
        event_functor = PL_new_functor(PL_new_atom("event"), 2);
    PL_cons_functor(a0+1,event_functor,b0,b0+1);

    if ( !p )
        p = PL_predicate("trClause", 3, NULL);

    qid_t qid = PL_open_query(NULL, PL_Q_NORMAL, p, a0);
    while(PL_next_solution(qid) != FALSE)
    {
        //termToString(b0,myEvents[i]);
        atom_t name;
        PL_get_name_arity(b0, &name, &arity);
        sprintf(myEvents[i],"%s",PL_atom_chars(name));
        temp=(eventType*)calloc(1,sizeof(eventType));
        trClause* trc=(trClause*)calloc(1,sizeof(trClause));

        strcpy(temp->name,PL_atom_chars(name));
        temp->arity = arity;
        RBTreeInsert(EventTree,temp,trc);
        temp=NULL;
        trc=NULL;
        padding(' ',4);
        printf("+New Event Signature : %s/%d\n",myEvents[i],arity);
        i++;
    }
    PL_close_query(qid);
#if DEBUG
    RBTreePrint(EventTree);
#endif
    printf("--- Done!\n");


    return EventTree;
}
Exemple #7
0
// red-black index searching
void ixPut(cmpString fname, analSet *anl) {
  int ix;
  char *nName = (char*)malloc(sizeof(cmpString));
  float *nFloat = (float*)malloc(sizeof(float) * MAXINDEX);

  strcpy(nName, fname);
  for(ix = 0; ix < MAXINDEX; ix++) {
  //  printf("(rb) %d\n", anl->indexes[ix]);
    nFloat[ix] = ((float*)anl->data)[anl->indexes[ix]];
    RBTreeInsert(  tree[anl->indexes[ix]],
        (void*)&nFloat[ix],
        (void*)nName);
  }
}
void handle_new_client(Client* client)
{
    logger("<Client><handle_new_client>got a new client\n");
    struct sockaddr address;
    int add_len = sizeof(address);
    int new_socket = accept(client->listening_fd,
                            (struct sockaddr *)&(address),
                            (socklen_t*)&(add_len));
    int* new_socket_ptr = mymalloc(sizeof(int));
    *new_socket_ptr = new_socket;
    File_msg* file_msg = mymalloc(sizeof(File_msg));
    file_msg->file_fd=-1;
    file_msg->aes_key[0]='\0';
    RBTreeInsert(client->transfers, new_socket_ptr, file_msg);
    FD_SET(new_socket, &(client->fd_read_set));
    FD_SET(new_socket, &(client->fd_write_set));
    client->fdmax = (client->fdmax > new_socket) ? client->fdmax : new_socket;
}
/* add taskname [task_name, task_code] to tree  
 * check that there is no repetition of task names
 */
static void add_taskname_to_tree(const char* task_name, t_taskcode task_code, rb_red_blk_tree* tree) {
   char *newName;
   t_taskcode *newCode;
   
#if library_TESTING   
   /* make sure there is NOT already present taskname  */
   rb_red_blk_node *newNode;
   newNode = RBExactQuery( tree, task_name);
   if (newNode != NULL) 
      PANIC("duplication of tasknames, repeated taskname: new -> %s    and old -> %s\n",
            task_name,  (char *)(newNode->key));
#endif   
   
   /* make space for storing taskname and taskcode  */
   newName  = make_persistant_taskname(task_name);
   newCode  = make_persistant_taskcode(task_code);   
     
   /* insert to the tree  */   
   RBTreeInsert(tree, newName, newCode);   
   
}
Exemple #10
0
static kthread_t *cfs_uthread_init(uthread_t *uthread)
{
	checkpoint("u%d: CFS: init uthread", uthread->tid);

	cfs_data_t *cfs_data = SCHED_DATA;
	cfs_uthread_t *cfs_uthread = emalloc(sizeof(*cfs_uthread));
	cfs_uthread->uthread = uthread;
	cfs_uthread->priority = CFS_DEFAULT_PRIORITY;
	cfs_uthread->gid = uthread->attr->gid;

	gt_spin_lock(&cfs_data->lock);
	cfs_kthread_t *cfs_kthread = cfs_find_kthread_target(cfs_uthread,
	                                                     cfs_data);
	gt_spin_unlock(&cfs_data->lock);

	if(cfs_uthread->gid > cfs_kthread->tree->max_gid){
	  cfs_kthread->tree->max_gid = cfs_uthread->gid;
	}

	/* update the kthread's load and latency, if necessary */
	gt_spin_lock(&cfs_kthread->lock);
	cfs_kthread->cfs_uthread_count++;
	cfs_kthread->latency =
	        max(CFS_DEFAULT_LATENCY_us,
	            cfs_kthread->cfs_uthread_count * CFS_MIN_GRANULARITY_us);
	cfs_kthread->load += cfs_uthread->priority;
	cfs_uthread->vruntime = cfs_kthread->min_vruntime;
	cfs_uthread->key = 0;
	gt_spin_unlock(&cfs_kthread->lock);

	checkpoint("u%d: CFS: Creating node", uthread->tid);
	cfs_uthread->node = RBNodeCreate(&cfs_uthread->key, cfs_uthread);
	checkpoint("u%d: CFS: Insert into rb tree", cfs_uthread->uthread->tid);
	RBTreeInsert(cfs_kthread->tree, cfs_uthread->node);

	return cfs_kthread->k_ctx;
}
void read_client_msg(Client* client, int read_fd)
{
    rb_red_blk_node* transfer = RBExactQuery(client->transfers, &read_fd);
    File_msg* file_msg = (File_msg*)(transfer->info);
    int valread = read(read_fd, file_msg->msg.buffer+file_msg->msg.offset, BUFFER_SIZE-file_msg->msg.offset);
    if(valread == 0) {
        logger("<Client><read_client_msg>client disconnected\n");
        RBDelete(client->transfers, transfer);
        close(read_fd);
        FD_CLR(read_fd, &(client->fd_read_set));
        FD_CLR(read_fd, &(client->fd_write_set));
        return;
    }
    file_msg->msg.offset += valread;
    if(file_msg->msg.offset == BUFFER_SIZE) {
        if(file_msg->aes_key[0] == '\0') {
            if(ENCRYPTION_ENABLED) {
                logger("<Client><read_client_msg>got a full RSA message from another client\n");
                char encrypted[BUFFER_SIZE];
                for(int i = 0; i<BUFFER_SIZE; ++i)
                    encrypted[i] = file_msg->msg.buffer[i];
                private_decrypt(encrypted,BUFFER_SIZE,client->keypair,file_msg->msg.buffer);
            }
            char command = file_msg->msg.buffer[0];
            if(command == 'r') {
                logger("<Client><read_client_msg>got a request message\n");
                /*rname token AES => cname ip token*/
                sscanf(file_msg->msg.buffer+1, "%s %s %s", file_msg->file_name, file_msg->token, file_msg->aes_key);
                struct sockaddr address;
                int add_len = sizeof(address);
                getpeername(read_fd, (struct sockaddr*)&(address),
                            (socklen_t*)&(add_len));
                struct in_addr ip_struct;
                inet_aton(address.sa_data, & ip_struct);
                int ip = ip_struct.s_addr;
                RBTreeInsert(client->waiting_list, file_msg->token, &read_fd);
                sprintf(client->server_msg.buffer, "c%s %d %s", file_msg->file_name, ip, file_msg->token);
                FD_SET(client->maintainer_fd, &(client->fd_write_set));
                file_msg->msg.offset=0;
            } else {
                exit(1);
            }
        } else {
            if(ENCRYPTION_ENABLED) {
                char partial_msg[128];
                for(int i = 0; i < (BUFFER_SIZE/128); ++i) {
                    for(int j=0; j<128; ++j)
                        partial_msg[j] = file_msg->msg.buffer[i*128+j];
                    AES128_ECB_decrypt(partial_msg,file_msg->aes_key,file_msg->msg.buffer+i*128);
                }
                logger("<Client><read_client_msg>AES decrypted the message\n");
            }
            if(file_msg->file_fd == -1) {
                /*ttoken size => in data mode*/
                char token[8];
                sscanf(file_msg->msg.buffer, "t%s %d", token, file_msg->msg.total_len);
                logger("<Client><read_client_msg>got a transfer message with %s for and with size %d\n", token, file_msg->msg.total_len);
                file_msg->token[0] = '\0';
                file_msg->msg.offset=0;
            } else {
                /*read data mode (write to file)*/
                if(ENCRYPTION_ENABLED) {
                    char file_write_buffer[BUFFER_SIZE];
                    AES128_ECB_decrypt(file_msg->msg.buffer, file_msg->aes_key, file_write_buffer);
                    file_msg->msg.offset += write(file_msg->file_fd, file_write_buffer, (file_msg->msg.total_len-file_msg->msg.offset) > 0 ? BUFFER_SIZE : (file_msg->msg.total_len-file_msg->msg.offset));
                }
                else
                    file_msg->msg.offset += write(file_msg->file_fd, file_msg->msg.buffer, (file_msg->msg.total_len-file_msg->msg.offset) > 0 ? BUFFER_SIZE : (file_msg->msg.total_len-file_msg->msg.offset));
                logger("<Client><read_client_msg>wrote to file\n");
                if(file_msg->msg.offset == file_msg->msg.total_len)
                    close(file_msg->file_fd);
            }
        }
    }
}
void process_server_msg(Client* client)
{
    char command = client->server_msg.buffer[0];
    if(command == 'n')
        logger("<Client><process_server_msg>file not found : %s", client->server_msg.buffer+1);
    else if(command == 'h') {
        if(ENCRYPTION_ENABLED) {
            client->server_msg.extended_buffer = mymalloc(BUFFER_SIZE);
            for(int i=0; i<BUFFER_SIZE; ++i)
                client->server_msg.extended_buffer[i] = client->server_msg.buffer[i];
        } else {
            int host_ip, host_port;
            char file_name[32];
            char* token = mymalloc(8);
            sscanf(client->server_msg.buffer,"h%d:%d %s %s",&host_ip, &host_port, file_name, token);
            int* new_socket=mymalloc(sizeof(int));
            File_msg* file_msg = mymalloc(sizeof(File_msg));
            strcpy(file_msg->token, token);
            file_msg->msg.offset=0;
            file_msg->msg.dual_msg=FALSE;
            file_msg->file_fd=-1;
            file_msg->msg.total_len=BUFFER_SIZE;
            struct sockaddr_in remote_addr;
            memset(&remote_addr, 0, sizeof(remote_addr));
            remote_addr.sin_family = AF_INET;
            remote_addr.sin_addr.s_addr = host_ip;
            remote_addr.sin_port = htons(host_port);
            *new_socket = socket(AF_INET, SOCK_STREAM, 0);
            connect(*new_socket, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr));
            strcpy(file_msg->aes_key, "NO_KEY");
            sprintf(file_msg->msg.buffer, "r%s %s %s", file_name, token, file_msg->aes_key);
            FD_SET(*new_socket, &(client->fd_read_set));
            FD_SET(*new_socket, &(client->fd_write_set));
            client->fdmax = client->fdmax > *new_socket ? client->fdmax : *new_socket;
            RBTreeInsert(client->waiting_list, token, new_socket);
            RBTreeInsert(client->transfers, new_socket, file_msg);
            write(*new_socket, file_msg->msg.buffer, BUFFER_SIZE);
            logger("<Client><process_server_msg>got \'h\'\n");
        }
    } else if(command == 'i') {
        int host_ip, host_port;
        char file_name[32];
        char* token = mymalloc(8);
        int read_size = sscanf(client->server_msg.extended_buffer,"h%d:%d %s %s",
                               &host_ip, &host_port, &file_name, token);
        /*extBuffer+buffer == pub_key*/
        char tmp_key[PUBKEY_SIZE];
        for(int i=read_size; i<BUFFER_SIZE; ++i)
            tmp_key[i-read_size]=client->server_msg.extended_buffer[i];
        myfree(client->server_msg.extended_buffer);
        client->server_msg.offset=0;
        for(int i=BUFFER_SIZE-read_size; i<read_size+PUBKEY_SIZE-BUFFER_SIZE; ++i)
            tmp_key[i]=client->server_msg.buffer[i-BUFFER_SIZE+read_size+1];
        /*we have the other end's public key*/
        int* new_socket=mymalloc(sizeof(int));
        File_msg* file_msg = mymalloc(sizeof(File_msg));
        strcpy(file_msg->token, token);
        file_msg->msg.offset=0;
        file_msg->msg.dual_msg=FALSE;
        file_msg->file_fd=-1;
        file_msg->msg.total_len=BUFFER_SIZE;
        strcpy(file_msg->file_name, file_name);
        struct sockaddr_in remote_addr;
        memset(&remote_addr, 0, sizeof(remote_addr));
        remote_addr.sin_family = AF_INET;
        remote_addr.sin_addr.s_addr = host_ip;
        remote_addr.sin_port = htons(host_port);
        *new_socket = socket(AF_INET, SOCK_STREAM, 0);
        connect(*new_socket, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr));
        generate_random_aes_key(file_msg->aes_key);
        sprintf(file_msg->msg.buffer, "r%s %s %s", file_name, token, file_msg->aes_key);
        encrypt_buffer_with_key(file_msg->msg.buffer, tmp_key);
        FD_SET(*new_socket, &(client->fd_write_set));
        FD_SET(*new_socket, &(client->fd_read_set));
        client->fdmax = client->fdmax > *new_socket ? client->fdmax : *new_socket;
        RBTreeInsert(client->waiting_list, token, new_socket);
        RBTreeInsert(client->transfers, new_socket, file_msg);
        write(*new_socket, file_msg->msg.buffer, BUFFER_SIZE);
        logger("<Client><process_server_msg>got \'i\'\n");
    } else if(command == 'o') {
        char given_token[8];
        strcpy(given_token, client->server_msg.buffer+1);
        rb_red_blk_node* request_node = RBExactQuery(client->waiting_list, given_token);
        if(request_node == NULL)
            exit(1);
        FD_SET(*(int*)(request_node->info), &(client->fd_write_set));
        rb_red_blk_node* transfer = RBExactQuery(client->transfers, request_node->info);
        RBDelete(client->waiting_list, request_node);
        File_msg* file_msg = (File_msg*)(transfer->key);
        file_msg->file_fd = open(file_msg->file_name, O_RDONLY, 666);
        if(file_msg->file_fd == -1)
            exit(1);
        //make the transfer msg
        struct stat stat_buf;
        fstat(file_msg->file_fd, &stat_buf);
        sprintf(file_msg->msg.buffer, "t %s %d", file_msg->token, stat_buf.st_size);
        file_msg->msg.offset=0;
        file_msg->msg.total_len=BUFFER_SIZE;
        logger("<Client><process_server_msg>got \'o\'\n");
    }
    else if(command == 'f') {
        char given_token[8];
        strcpy(given_token, client->server_msg.buffer+1);
        rb_red_blk_node* request_node = RBExactQuery(client->waiting_list, given_token);
        if(request_node == NULL)
            exit(1);
        rb_red_blk_node* transfer = RBExactQuery(client->transfers, request_node->info);
        RBDelete(client->waiting_list, request_node);
        RBDelete(client->transfers, transfer);
        logger("<Client><process_server_msg>got \'f\'\n");
    }
}
Exemple #13
0
int main(int argc, char** argv) {
  int option=0;
  int64_t newKey,newKey2;
  rb_red_blk_node* newNode;
  rb_red_blk_tree* tree;
  int64_t* array = 0;
  int64_t* array2 = 0;
  unsigned int N = 65536; //total number of elements to insert
  unsigned int M = 16384; //number of elements to delete from the beginning
  unsigned int M2 = 16384; //number of elements to delete from the end
  int i;
  unsigned int j;
  time_t t1 = time(0);
  unsigned int seed = t1;
  double par = 2.5;
  
  for(i=1;i<argc;i++) if(argv[i][0] == '-') switch(argv[i][1]) {
	  case 'N':
	  	N = atoi(argv[i+1]);
	  	break;
	  case 'M':
	  	M = atoi(argv[i+1]);
	  	if(i+2 < argc) {
			if(isdigit(argv[i+2][0])) M2 = atoi(argv[i+2]);
			else M2 = M;
		}
		else M2 = M;
		break;
	  case 's':
	  	seed = atoi(argv[i+1]);
	  	break;
	  case 'p':
	  	par = atof(argv[i+1]);
		break;
	  default:
	  	fprintf(stderr,"unrecognized parameter: %s!\n",argv[i]);
	  	break;
  }
  
  if(M + M2 >= N) {
	  fprintf(stderr,"Error: number of elements to delete (%u + %u) is more than the total number of elements (%u)!\n",
	  	M,M2,N);
	  return 1;
  }
  
  tree=RBTreeCreate(CmpInt64,NullFunction,NullFunction,NullFunction,NullFunction,DFInt64,&par);
  array = SafeMalloc(sizeof(int64_t)*N);
  for(j=0;j<N;j++) {
	  array[j] = ((int64_t)rand())*((int64_t)rand())*((int64_t)rand());
	  RBTreeInsert(tree,(void*)(array[j]),0);
  }
  
  for(j=0;j<M;j++) {
	  newNode = RBExactQuery(tree,(void*)(array[j]));
	  if(!newNode) {
		  fprintf(stderr,"Error: node not found!\n");
		  goto rbt_end;
	  }
	  RBDelete(tree,newNode);
  }
  
  for(j=N-M2;j<N;j++) {
	  newNode = RBExactQuery(tree,(void*)(array[j]));
	  if(!newNode) {
		  fprintf(stderr,"Error: node not found!\n");
		  goto rbt_end;
	  }
	  RBDelete(tree,newNode);
  }
  
  N = N-M2-M;
  array2 = array+M;
  quicksort(array2,0,N);
  j=0;
  newNode = TreeFirst(tree);
  double cdf = 0.0;
  do {
	  int64_t v1 = (int64_t)(newNode->key);
	  if(v1 != array2[j]) {
		  fprintf(stderr,"error: %d != %d!\n",v1,array2[j]);
		  break;
	  }
	  double cdf2 = GetNodeRank(tree,newNode);
	  double diff = fabs(cdf2-cdf);
	  if(diff > EPSILON) {
		  fprintf(stderr,"wrong cdf value: %g != %g (diff: %g)!\n",cdf,cdf2,diff);
		  break;
	  }
	  j++;
	  cdf += DFInt64((void*)array2[j],&par);
	  newNode = TreeSuccessor(tree,newNode);
  } while(newNode != tree->nil && j<N);
  
  if( !(newNode == tree->nil && j == N) ) {
	  fprintf(stderr,"error: tree or array too short / long!\n");
  }

rbt_end:
  
  RBTreeDestroy(tree);
  free(array);
  
  time_t t2 = time(0);
  fprintf(stderr,"runtime: %u\n",(unsigned int)(t2-t1));
  
  return 0;
}
Exemple #14
0
int dhcp_cache_update(const dhcp_parsed_message_t * request, const dhcp_full_packet_t * response,
		uint16_t dhcp_data_len)
{
	char str_ether[STR_ETHER_ALEN + 1];
	char str_ipaddr[2][IP4_MAXSTR_ALEN + 1];

	etheraddr_bin_to_str(request->raw_dhcp_msg->cli_hwaddr, str_ether);
	iptos(response->dhcp_data.you_iaddr.s_addr, str_ipaddr[0]);

	dhcp_cache_node_t s_data;
	s_data.if_ipaddr = request->dhcp_dev->ipaddr;
	s_data.gw_ipaddr = request->raw_dhcp_msg->gw_iaddr.s_addr;
	s_data.cli_ethaddr = (typeof(s_data.cli_ethaddr))request->raw_dhcp_msg->cli_hwaddr;
	s_data.header_ethaddr = (typeof(s_data.header_ethaddr))request->from_ether;

	rb_red_blk_node *f_node;

	cache_wrlock();
	time_t now = time(NULL);

	dhcp_cache_node_t * cached_node = NULL;
	if ( ( f_node = RBExactQuery(cache, &s_data) ) ) 
	{
		cached_node = f_node->info;
		log_wr(DLOG, "Update cached data for client %s/%s.", str_ether, str_ipaddr[0]);
		cached_node->timestamp = now;
		memcpy(&cached_node->cached_response, response, sizeof(*response));
	} 
	else 
	{	/* Node not found in cache. Add. */
		cached_node = calloc(1, sizeof(dhcp_cache_node_t));
		if(!cached_node)
		{
			log_wr(CLOG, "Can't allocate memory for new DHCP cache node: '%s'", strerror(errno));
			exit(error_memory);
		}

		memcpy(&cached_node->cached_response, response, sizeof(cached_node->cached_response));
		cached_node->if_ipaddr = request->dhcp_dev->ipaddr;
		cached_node->gw_ipaddr = request->raw_dhcp_msg->gw_iaddr.s_addr;
		cached_node->cli_ethaddr = cached_node->cached_response.dhcp_data.cli_hwaddr;
		cached_node->header_ethaddr = cached_node->cached_response.eth_head.ether_dhost;
		cached_node->timestamp = now;

		f_node = RBTreeInsert(cache, cached_node, cached_node);

		log_wr(DLOG, "Added response for client %s/%s%s%s%s to DHCP cache.", str_ether, str_ipaddr[0],
					cached_node->gw_ipaddr ? " (relay: " : "",
					cached_node->gw_ipaddr ? iptos(cached_node->gw_ipaddr, str_ipaddr[1]) : "",
					cached_node->gw_ipaddr ? ")" : "");
	}

	/* Set DHCPACK message type for cached response */
	uint16_t type_len;
	uint8_t * cached_response_type = get_dhcp_option_ptr(&cached_node->cached_response.dhcp_data,
			cached_node->cached_response.udp_header.len, DHCP_OPT_MESSAGE_TYPE, &type_len);
	if(!cached_response_type)
	{
		log_wr(CLOG, "Invalid DHCP message cached (%s/%s): DHCP message type option not found.",
				str_ether, str_ipaddr);
		RBDelete(cache, f_node);
		free(cached_node);

		cache_unlock();

		return 0;
	}

	cached_node->dhcp_data_len = dhcp_data_len;

	*cached_response_type = DHCPACK;

	cache_unlock();

	return 1;
}
int main() {
  stk_stack* enumResult;
  int option=0;
  int newKey,newKey2;
  int* newInt;
  rb_red_blk_node* newNode;
  rb_red_blk_tree* tree;

  tree=RBTreeCreate(IntComp,IntDest,InfoDest,IntPrint,InfoPrint);
  while(option!=8) {
    printf("choose one of the following:\n");
    printf("(1) add to tree\n(2) delete from tree\n(3) query\n");
    printf("(4) find predecessor\n(5) find sucessor\n(6) enumerate\n");
    printf("(7) print tree\n(8) quit\n");
    do option=fgetc(stdin); while(-1 != option && isspace(option));
    option-='0';
    switch(option)
      {
      case 1:
	{
	  printf("type key for new node\n");
	  scanf("%i",&newKey);
	  newInt=(int*) malloc(sizeof(int));
	  *newInt=newKey;
	  RBTreeInsert(tree,newInt,0);
	}
	break;
	
      case 2:
	{
	  printf("type key of node to remove\n");
	  scanf("%i",&newKey);
	  if ( ( newNode=RBExactQuery(tree,&newKey ) ) ) RBDelete(tree,newNode);/*assignment*/
	  else printf("key not found in tree, no action taken\n");
	}
	break;

      case 3:
	{
	  printf("type key of node to query for\n");
	  scanf("%i",&newKey);
	  if ( ( newNode = RBExactQuery(tree,&newKey) ) ) {/*assignment*/
	    printf("data found in tree at location %i\n",(int)newNode);
	  } else {
	    printf("data not in tree\n");
	  }
	}
	break;
      case 4:
	{
	  printf("type key of node to find predecessor of\n");
	  scanf("%i",&newKey);
	  if ( ( newNode = RBExactQuery(tree,&newKey) ) ) {/*assignment*/
	    newNode=TreePredecessor(tree,newNode);
	    if(tree->nil == newNode) {
	      printf("there is no predecessor for that node (it is a minimum)\n");
	    } else {
	      printf("predecessor has key %i\n",*(int*)newNode->key);
	    }
	  } else {
	    printf("data not in tree\n");
	  }
	}
	break;
      case 5:
	{
	  printf("type key of node to find successor of\n");
	  scanf("%i",&newKey);
	  if ( (newNode = RBExactQuery(tree,&newKey) ) ) {
	    newNode=TreeSuccessor(tree,newNode);
	    if(tree->nil == newNode) {
	      printf("there is no successor for that node (it is a maximum)\n");
	    } else {
	      printf("successor has key %i\n",*(int*)newNode->key);
	    }
	  } else {
	    printf("data not in tree\n");
	  }
	}
	break;
      case 6:
	{
	  printf("type low and high keys to see all keys between them\n");
	  scanf("%i %i",&newKey,&newKey2);
	  enumResult=RBEnumerate(tree,&newKey,&newKey2);	  
	  while ( (newNode = StackPop(enumResult)) ) {
	    tree->PrintKey(newNode->key);
	    printf("\n");
	  }
	  free(enumResult);
	}
	break;
      case 7:
	{
	  RBTreePrint(tree);
	}
	break;
      case 8:
	{
	  RBTreeDestroy(tree);
	  return 0;
	}
	break;
      default:
	printf("Invalid input; Please try again.\n");
      }
  }
  return 0;
}
Exemple #16
0
void RBTreeAdd(RBTree_t *tree, PrimaryType_t num)
{
    struct RBNode_t *node = (struct RBNode_t *)malloc(sizeof(struct RBNode_t));
    node->mKey.mPrimaryVal = num;
    RBTreeInsert(tree, node);
}
static SparseMatrix get_overlap_graph(int dim, int n, real *x, real *width, int check_overlap_only){
  /* if check_overlap_only = TRUE, we only check whether there is one overlap */
  scan_point *scanpointsx, *scanpointsy;
  int i, k, neighbor;
  SparseMatrix A = NULL, B = NULL;
  rb_red_blk_node *newNode, *newNode0, *newNode2 = NULL;
  rb_red_blk_tree* treey;
  real one = 1;

  A = SparseMatrix_new(n, n, 1, MATRIX_TYPE_REAL, FORMAT_COORD);

  scanpointsx = N_GNEW(2*n,scan_point);
  for (i = 0; i < n; i++){
    scanpointsx[2*i].node = i;
    scanpointsx[2*i].x = x[i*dim] - width[i*dim];
    scanpointsx[2*i].status = INTV_OPEN;
    scanpointsx[2*i+1].node = i+n;
    scanpointsx[2*i+1].x = x[i*dim] + width[i*dim];
    scanpointsx[2*i+1].status = INTV_CLOSE;
  }
  qsort(scanpointsx, 2*n, sizeof(scan_point), comp_scan_points);

  scanpointsy = N_GNEW(2*n,scan_point);
  for (i = 0; i < n; i++){
    scanpointsy[i].node = i;
    scanpointsy[i].x = x[i*dim+1] - width[i*dim+1];
    scanpointsy[i].status = INTV_OPEN;
    scanpointsy[i+n].node = i;
    scanpointsy[i+n].x = x[i*dim+1] + width[i*dim+1];
    scanpointsy[i+n].status = INTV_CLOSE;
  }


  treey = RBTreeCreate(NodeComp,NodeDest,InfoDest,NodePrint,InfoPrint);

  for (i = 0; i < 2*n; i++){
#ifdef DEBUG_RBTREE
    fprintf(stderr," k = %d node = %d x====%f\n",(scanpointsx[i].node)%n, (scanpointsx[i].node), (scanpointsx[i].x));
#endif

    k = (scanpointsx[i].node)%n;


    if (scanpointsx[i].status == INTV_OPEN){
#ifdef DEBUG_RBTREE
      fprintf(stderr, "inserting...");
      treey->PrintKey(&(scanpointsy[k]));
#endif

      RBTreeInsert(treey, &(scanpointsy[k]), NULL); /* add both open and close int for y */

#ifdef DEBUG_RBTREE
      fprintf(stderr, "inserting2...");
      treey->PrintKey(&(scanpointsy[k+n]));
#endif

      RBTreeInsert(treey, &(scanpointsy[k+n]), NULL);
    } else {
      real bsta, bbsta, bsto, bbsto; int ii; 

      assert(scanpointsx[i].node >= n);

      newNode = newNode0 = RBExactQuery(treey, &(scanpointsy[k + n]));
      ii = ((scan_point *)newNode->key)->node;
      assert(ii < n);
      bsta = scanpointsy[ii].x; bsto = scanpointsy[ii+n].x;

#ifdef DEBUG_RBTREE
      fprintf(stderr, "poping..%d....yinterval={%f,%f}\n", scanpointsy[k + n].node, bsta, bsto);
      treey->PrintKey(newNode->key);
#endif

     assert(treey->nil != newNode);
      while ((newNode) && ((newNode = TreePredecessor(treey, newNode)) != treey->nil)){
	neighbor = (((scan_point *)newNode->key)->node)%n;
	bbsta = scanpointsy[neighbor].x; bbsto = scanpointsy[neighbor+n].x;/* the y-interval of the node that has one end of the interval lower than the top of the leaving interval (bsto) */
#ifdef DEBUG_RBTREE
	fprintf(stderr," predecessor is node %d y = %f\n", ((scan_point *)newNode->key)->node, ((scan_point *)newNode->key)->x);
#endif
	if (neighbor != k){
	  if (ABS(0.5*(bsta+bsto) - 0.5*(bbsta+bbsto)) < 0.5*(bsto-bsta) + 0.5*(bbsto-bbsta)){/* if the distance of the centers of the interval is less than sum of width, we have overlap */
	    A = SparseMatrix_coordinate_form_add_entries(A, 1, &neighbor, &k, &one);
#ifdef DEBUG_RBTREE
	    fprintf(stderr,"======================================  %d %d\n",k,neighbor);
#endif
	    if (check_overlap_only) goto check_overlap_RETURN;
	  }
	} else {
	  newNode2 = newNode;
	}

      }

#ifdef DEBUG_RBTREE
      fprintf(stderr, "deleteing...");
      treey->PrintKey(newNode0->key);
#endif

      if (newNode0) RBDelete(treey,newNode0);


     if (newNode2 && newNode2 != treey->nil && newNode2 != newNode0) {

#ifdef DEBUG_RBTREE
	fprintf(stderr, "deleteing2...");
	treey->PrintKey(newNode2->key);
#endif

	if (newNode0) RBDelete(treey,newNode2);
      }

    }
  }

check_overlap_RETURN:
   FREE(scanpointsx);
  FREE(scanpointsy);
  RBTreeDestroy(treey);

  B = SparseMatrix_from_coordinate_format(A);
  SparseMatrix_delete(A);
  A = SparseMatrix_symmetrize(B, FALSE);
  SparseMatrix_delete(B);
  if (Verbose) fprintf(stderr, "found %d clashes\n", A->nz);
  return A;
}
Exemple #18
0
static SparseMatrix get_overlap_graph(int dim, int n, real *x, real *width){
  scan_point *scanpointsx, *scanpointsy;
  int i, k, neighbor;
  SparseMatrix A = NULL, B = NULL;
  rb_red_blk_node *newNode, *newNode0;
  rb_red_blk_tree* treey;
  real one = 1;

  A = SparseMatrix_new(n, n, 1, MATRIX_TYPE_REAL, FORMAT_COORD);

  scanpointsx = N_GNEW(2*n,scan_point);
  for (i = 0; i < n; i++){
    scanpointsx[2*i].node = i;
    scanpointsx[2*i].x = x[i*dim] - width[i*dim];
    scanpointsx[2*i].status = INTV_OPEN;
    scanpointsx[2*i+1].node = i+n;
    scanpointsx[2*i+1].x = x[i*dim] + width[i*dim];
    scanpointsx[2*i+1].status = INTV_CLOSE;
  }
  qsort(scanpointsx, 2*n, sizeof(scan_point), comp_scan_points);

  scanpointsy = N_GNEW(2*n,scan_point);
  for (i = 0; i < n; i++){
    scanpointsy[i].node = i;
    scanpointsy[i].x = x[i*dim+1] - width[i*dim+1];
    scanpointsy[i].status = INTV_OPEN;
    scanpointsy[i+n].node = i;
    scanpointsy[i+n].x = x[i*dim+1] + width[i*dim+1];
    scanpointsy[i+n].status = INTV_CLOSE;
  }


  treey = RBTreeCreate(NodeComp,NodeDest,InfoDest,NodePrint,InfoPrint);

  for (i = 0; i < 2*n; i++){
#ifdef DEBUG_RBTREE
    fprintf(stderr," k = %d node = %d x====%f\n",(scanpointsx[i].node)%n, (scanpointsx[i].node), (scanpointsx[i].x));
#endif

    k = (scanpointsx[i].node)%n;


    if (scanpointsx[i].status == INTV_OPEN){
#ifdef DEBUG_RBTREE
      fprintf(stderr, "inserting...");
      treey->PrintKey(&(scanpointsy[k]));
#endif

      RBTreeInsert(treey, &(scanpointsy[k]), NULL); /* add both open and close int for y */

#ifdef DEBUG_RBTREE
      fprintf(stderr, "inserting2...");
      treey->PrintKey(&(scanpointsy[k+n]));
#endif

      RBTreeInsert(treey, &(scanpointsy[k+n]), NULL);
    } else {
      assert(scanpointsx[i].node >= n);

      newNode = newNode0 = RBExactQuery(treey, &(scanpointsy[k + n]));

#ifdef DEBUG_RBTREE
      fprintf(stderr, "poping..%d....", scanpointsy[k + n].node);
      treey->PrintKey(newNode->key);
#endif

      assert(treey->nil != newNode);
      while ((newNode) && ((newNode = TreePredecessor(treey, newNode)) != treey->nil) && ((scan_point *)newNode->key)->node != k){
	neighbor = (((scan_point *)newNode->key)->node)%n;
	A = SparseMatrix_coordinate_form_add_entries(A, 1, &neighbor, &k, &one);
#ifdef DEBUG_RBTREE
	fprintf(stderr,"%d %d\n",k,neighbor);
#endif

      }

#ifdef DEBUG_RBTREE
      fprintf(stderr, "deleteing...");
      treey->PrintKey(newNode0->key);
#endif

      if (newNode0) RBDelete(treey,newNode0);
      if (newNode != treey->nil && newNode != newNode0) {

#ifdef DEBUG_RBTREE
	fprintf(stderr, "deleting2...");
	treey->PrintKey(newNode->key)
#endif

	if (newNode0) RBDelete(treey,newNode);
      }
    }
  }
void render(PaletteRef *raster, int lineWidth, int numLines, const rb_red_blk_tree *scanLinePrimBuckets){
	static OntoProj screenPlaneData = {offsetof(Point, z), 0};
	static const Transformation screenPlane = {(TransformationF)(&snapOntoProj), &screenPlaneData};
	{
		int line;
		rb_red_blk_tree activePrimSet;
		ActiveEdgeList ael = freshAEL();
		rb_red_blk_map_tree inFlags;
		rb_red_blk_tree deFlags;
		/* This ensures that both trees are initialized and in a cleared state */
		RBTreeMapInit(&inFlags, pointerDiffF, NULL, &RBMapNodeAlloc, NULL);
		RBTreeInit(&deFlags, pointerDiffF, NULL, &RBNodeAlloc);
		RBTreeInit(&activePrimSet, pointerDiffF, NULL, &RBNodeAlloc);
		dPrintf(("Scanning line: 0\n"));
		for(line = 0; line < numLines; (++line), (raster += lineWidth)) {
			rb_red_blk_node *primIt, *p = NULL, *nextP;
			dPrintf(("\tUpdating activePrimSet\n"));
			for (primIt = activePrimSet.first; primIt != activePrimSet.sentinel; (p = primIt), (primIt = nextP)) {
				const Primitive* prim = primIt->key;
				const int top = roundOwn(topMostPoint(prim));
				nextP = TreeSuccessor(&activePrimSet, primIt);
				if(top < line){
#ifndef NDEBUG
					{
						const int bottom = roundOwn(bottomMostPoint(prim));
						dPrintf(("\t\t%d -> %d ( %s ) is not valid here: %d\n",top,bottom,fmtColor(prim->color), line));
					}
#endif
					RBDelete(&activePrimSet, primIt);
					primIt = p; /* We don't want to advance p into garbage data */
				}
			}
			{
				const rb_red_blk_tree *bucket = scanLinePrimBuckets + line;
				const rb_red_blk_node *node;
				for(node = bucket->first; node != bucket->sentinel; node = TreeSuccessor(bucket, node)) {
					Primitive * prim = node->key;
#ifndef NDEBUG
					{
						const int top = roundOwn(topMostPoint(prim)),
						bottom = roundOwn(bottomMostPoint(prim));
						dPrintf(("\t\t%d -> %d ( %s ) is added here: %d\n",top,bottom,fmtColor(prim->color), line));
					}
#endif
					RBTreeInsert(&activePrimSet, prim);
				}
			}
			stepEdges(&ael, &activePrimSet);
			{
				int curPixel = 0;
				const Primitive *curDraw = NULL;
				EdgeListEntry *nextEdge;
				LinkN* i = ael.activeEdges;
				if(i){
					nextEdge = i->data;
					while(nextEdge && curPixel < lineWidth){
						EdgeListEntry *const startEdge = nextEdge;
						Primitive *const startOwner = startEdge->owner;
						int startX = roundOwn(getSmartXForLine(startEdge, line)), nextX;
						rb_red_blk_map_node *inFlag = (rb_red_blk_map_node *)RBExactQuery((rb_red_blk_tree*)(&inFlags), startOwner);
						
						if(inFlag){
							static Point localPoints[6]; /* We don't recurse, so this is fine */
							static Edge flatHere = {localPoints, localPoints + 1},
							flatIn = {localPoints + 2, localPoints + 3},
							vert = {localPoints + 4, localPoints + 5};
							const EdgeListEntry *const edgeInEntry = inFlag->info;
							Point **const edgeHere = startEdge->edge, **edgeIn = edgeInEntry->edge;
							const Point *const s = edgeHere[START],
							*const e = edgeHere[END];
							Point here;
							bool sV, eV, v;
							float dotH, dotIn;
							transformEdge(&screenPlane, edgeHere, flatHere);
							transformEdge(&screenPlane, edgeIn, flatIn);
							INIT_POINT(here, startX, line, 0);
							sV = contains(edgeIn, s);
							eV = contains(edgeIn, e);
							v = (sV || eV) && contains(flatIn, &here) && contains(flatHere, &here) && (startOwner->arity != 1);
							vert[START] = &here;
							INIT_POINT(*(vert[END]), startX, line+1, 0);
							dotH = v ? dotEdge(vert, flatHere) : 0;
							dotIn = v ? dotEdge(vert, flatIn) : 0;
							if(!v || dotH * dotIn > 0){
								dPrintf(("\tNot *in* old %s at %f\n", fmtColor(startEdge->owner->color), getSmartXForLine(startEdge, line)));
								RBSetAdd(&deFlags, startOwner);
							} else {
								dPrintf(("\tFound horizontal vertex %s at %f. Don't delete it yet\n",fmtColor(startEdge->owner->color), getSmartXForLine(startEdge, line)));
							}
						} else {
							dPrintf(("\tNow *in* new %s at %f\n",fmtColor(startEdge->owner->color), getSmartXForLine(startEdge, line)));
							/* This might happen if a polygon is parallel to the x-axis */
							RBMapPut(&inFlags, startOwner, startEdge);
						}
						
						if(curPixel < startX){
							dPrintf(("\tcurPixel has fallen behind, dragging from %d to %d\n",curPixel, startX));
							curPixel = startX;
						}
						
						i = i->tail;
						if(i){
							nextEdge = i->data;
							nextX = roundOwn(getSmartXForLine(nextEdge, line));
							dPrintf(("\tNext edges @ x = %d from %s\n",nextX, fmtColor(nextEdge->owner->color)));
						} else {
							dPrintf(("\tNo more edges\n"));
							nextEdge = NULL;
							nextX = 0;
						}
						
						nextX = min(nextX, lineWidth);
						while ((!nextEdge && curPixel < lineWidth) || (curPixel < nextX)) {
							bool zFight = false, solitary = false;
							float bestZ = HUGE_VAL;
							const rb_red_blk_node *node;
							curDraw = NULL;
							dPrintf(("\tTesting depth:\n"));
							for(node = inFlags.tree.first; node != inFlags.tree.sentinel; node = TreeSuccessor((rb_red_blk_tree*)(&inFlags), node)) {
								const Primitive *prim = node->key;
								/* We need sub-pixel accuracy */
								const float testZ = getZForXY(prim, curPixel, line);
								if(testZ <= bestZ + PT_EPS){
									dPrintf(("\t\tHit: %f <= %f for %s\n",testZ, bestZ, fmtColor(prim->color)));
									if (CLOSE_ENOUGH(testZ, bestZ)) {
										if (prim->arity == 1) {
											zFight = curDraw && curDraw->arity == 1;
											curDraw = prim;
											solitary = RBSetContains(&deFlags, prim);
										} else {
											zFight = curDraw && curDraw->arity != 1;
										}
									} else {
										zFight = false;
										bestZ = testZ;
										curDraw = prim;
										solitary = RBSetContains(&deFlags, prim);
									}
								} else {
									dPrintf(("\t\tMiss: %f > %f for %s\n",testZ, bestZ, fmtColor(prim->color)));
								}
							}
							
							if(curDraw){
#ifndef NDEBUG
								if(nextEdge || solitary){
#endif
									const int drawWidth =  (zFight || solitary) ? 1 : ((nextEdge ? nextX : lineWidth) - curPixel),
									stopPixel = curPixel + min(lineWidth - curPixel,
															   max(0, drawWidth));
									const PaletteRef drawColor = /*(uint16_t)roundOwn(63 * bestZ / 100) << 5;*/decodeColor(curDraw->color);
									dPrintf(("Drawing %d @ (%d, %d)\n",drawWidth,curPixel,line));
									dPrintf(("Drawing %d @ (%d, %d)\n",stopPixel - curPixel,curPixel,line));
									while(curPixel < stopPixel){
										raster[curPixel++] = drawColor;
									}
#ifndef NDEBUG
								} else {
									dPrintf(("Warning: we probably shouldn't have to draw if there are no more edges to turn us off. Look for parity errors\n");
											RBTreeClear((rb_red_blk_tree*)&inFlags));
								}
#endif
							} else if(!inFlags.tree.size && nextEdge){
								/* fast forward, we aren't in any polys */
								dPrintf(("Not in any polys at the moment, fast-forwarding(1) to %d\n", nextX));
								curPixel = nextX;
							} else {
								/* Nothing left */
								dPrintf(("Nothing to draw at end of line\n"));
								curPixel = lineWidth;
							}
							
							for(node = deFlags.first; node != deFlags.sentinel; node = TreeSuccessor(&deFlags, node)){
								RBMapRemove(&inFlags, node->key);
							}
							RBTreeClear(&deFlags);
						}
						if (!inFlags.tree.size && nextEdge) {
							dPrintf(("Not in any polys at the moment, fast-forwarding(2) to %d\n", nextX));
							curPixel = nextX;
						}
					}
				}
			}
#ifndef NDEBUG
			{
				dPrintf(("Scanning line: %d\n", line+1));
				if(inFlags.tree.size){
					rb_red_blk_node *node;
					dPrintf(("\tGarbage left in inFlags:\n"));
					for (node = inFlags.tree.first; node != inFlags.tree.sentinel; node = TreeSuccessor((rb_red_blk_tree*)&inFlags, node)) {
						dPrintf(("\t\t%s\n",fmtColor(((const Primitive*)node->key)->color)));
					}
				}
			}
#endif
			RBTreeClear(&deFlags);
			RBTreeClear((rb_red_blk_tree*)(&inFlags));
		}
		RBTreeDestroy(&activePrimSet, false);
		RBTreeDestroy(&deFlags, false);
		RBTreeDestroy((rb_red_blk_tree*)(&inFlags), false);
	}
int process_command(Maintainer* maintainer, Node* node) /*1 on close*/
{
    if(ENCRYPTION_ENABLED) {
        char encrypted[BUFFER_SIZE];
        for(int i = 0 ; i < BUFFER_SIZE; ++i)
            encrypted[i] = node->read_msg.buffer[i];
        if(private_decrypt(encrypted,BUFFER_SIZE,maintainer->private_key, node->read_msg.buffer) == -1)
            logger("<Server><process_command>Decryption failed\n");
    }
    char command = node->read_msg.buffer[0];
    char* msg = node->read_msg.buffer+1;
    if(command == 'a') { /*add file*/
        logger("<Server><process_command>got add file command\n");
        rb_red_blk_node* result = RBExactQuery(maintainer->files, msg);
        if(result == NULL) {
            int i=0;
            for(; i<32; ++i)
                if(msg[i] == '\0')
                    break;
            ++i;
            char* file_name = mymalloc(i*sizeof(char));
            for(int j=0; j<i; ++j)
                file_name[j]=msg[j];
            File* new_file = mymalloc(sizeof(File));
            strcpy(new_file->name, file_name);
            new_file->num_of_owners = 0;
            new_file->owners = mymalloc(sizeof(struct Nodes_ll));
            new_file->owners->next = NULL;
            new_file->owners->node = node;
            result = RBTreeInsert(maintainer->files, file_name, new_file);
        }
        ((File*)(result->info))->num_of_owners++;
        struct Nodes_ll* owners_head = ((File*)(result->info))->owners;
        while(owners_head != NULL)
            if(owners_head->node == node)
                return 0;
            else
                owners_head = owners_head->next;
        owners_head = mymalloc(sizeof(struct Nodes_ll));
        owners_head->next=((File*)(result->info))->owners;
        ((File*)(result->info))->owners = owners_head;
        owners_head->node = node;
        return 0;
    } else if(command == 'q') {
        logger("<Server><process_command>got close connection command\n");
        close_client_connection(maintainer, node->socket_fd, node, FALSE);
        return 1;
    } else if(command == 'd') {
        logger("<Server><process_command>got delete file command\n");
        rb_red_blk_node* founded_node = RBExactQuery(maintainer->files, msg);
        File* this_file = founded_node->info;
        struct Nodes_ll* owners_head = this_file->owners;
        struct Nodes_ll* prev = this_file->owners;
        while(owners_head != NULL) {
            if(owners_head->node == node) {
                prev->next = owners_head->next;
                this_file->num_of_owners--;
                if(owners_head == this_file->owners)
                    this_file->owners = this_file->owners->next;
                myfree(owners_head);
                break;
            }
            if(prev != owners_head) {
                prev = owners_head;
                owners_head = owners_head->next;
            }
        }
        return 0;
    }
    else if(command == 'l') {
        sscanf(msg, "%d", &(node->listening_port));
        logger("<Server><process_command>got listening port as %d\n", node->listening_port);
        return 0;
    }
    else if(command == 'p') {
        for(int i=0; i<(BUFFER_SIZE-1); ++i)
            node->pubkey[i] = msg[i];
        logger("<Server><process_command>got the first part of clients pubkey\n");
        return 0;
    }
    else if(command == 'k') {
        for(int i=(BUFFER_SIZE-1); i<PUBKEY_SIZE; ++i)
            node->pubkey[i] = msg[i-BUFFER_SIZE+1];
        logger("<Server><process_command>got the second part of clients pubkey\n");
        return 0;
    }
    else if(command == 'g') {
        if(node->write_msg.offset != 0)
            return 1;
        /*get host info*/
        char* file_name = mymalloc(32);
        sscanf(msg,"%s",file_name);
        logger("<Server><process_command>get host info for file : %s\n", file_name);
        rb_red_blk_node* founded_node = RBExactQuery(maintainer->files, file_name);
        if(founded_node == NULL) {
            node->write_msg.buffer[0] = 'n';
            strcpy(node->write_msg.buffer+1, file_name);
            if(ENCRYPTION_ENABLED)
                encrypt_for_client(node->write_msg.buffer, node->pubkey);
            FD_SET(node->socket_fd, &(maintainer->fd_write_set));
            return 0;
        }
        int rand_num = myrand()%((File*)(founded_node->info))->num_of_owners;
        struct Nodes_ll* return_info = ((File*)(founded_node->info))->owners;
        int i=0;
        while(i<rand_num) {
            ++i;
            return_info = return_info->next;
        }
        char* token = mymalloc(8*sizeof(char));
        for(i=0; i<7; ++i)
            token[i] = myrand()%100+20; /*print output*/
        token[7]='\0';
        logger("<Server><process_command>generated token : %s\n", token);
        RBTreeInsert(return_info->node->requests, file_name, token);
        int write_size = sprintf(node->write_msg.buffer, "h%d:%d %s %s",
                                 return_info->node->ip, return_info->node->listening_port, file_name, token);
        node->write_msg.total_len = BUFFER_SIZE;
        if(write_size == BUFFER_SIZE) {
            node->write_msg.total_len = 0;
            return 1;
        } else if((node->pubkey[0] != '\0') && ENCRYPTION_ENABLED) {
            for(i=write_size; i<(BUFFER_SIZE); ++i)
                node->write_msg.buffer[i] = node->pubkey[i-write_size];
            node->write_msg.dual_msg = TRUE;
            node->write_msg.extended_buffer = mymalloc(BUFFER_SIZE);
            node->write_msg.extended_buffer[0]='i';
            for(i=0; i<(PUBKEY_SIZE-BUFFER_SIZE+write_size); ++i)
                node->write_msg.extended_buffer[i+1] = node->pubkey[i+BUFFER_SIZE-write_size];
            if(ENCRYPTION_ENABLED) {
                encrypt_for_client(node->write_msg.buffer, node->pubkey);
                encrypt_for_client(node->write_msg.extended_buffer, node->pubkey);
            }
        }
        FD_SET(node->socket_fd, &(maintainer->fd_write_set));
        return 0;
    } else if(command == 'c') {
        int request_from_ip;
        char request_file_name[32];
        char request_token[8];
        /*change this in client side*/
        sscanf(msg, "%s %d %s", request_file_name, &request_from_ip, request_token);
        logger("<Server><process_command>checking credentials : %s %d %s\n", request_file_name, request_from_ip, request_token);
        rb_red_blk_node* node_from = RBExactQuery(maintainer->nodes_ip, &request_from_ip);
        node->write_msg.total_len=BUFFER_SIZE;
        if(node_from == NULL) {
            sprintf(node->write_msg.buffer, "f%s", request_token);
        } else {
            rb_red_blk_node* request_rb_node = RBExactQuery(((Node*)(node_from->info))->requests, request_file_name);
            if(request_rb_node == NULL)
                sprintf(node->write_msg.buffer, "f%s", request_token);
            else {
                if(strcmp((char*)(request_rb_node->info),request_token))
                    sprintf(node->write_msg.buffer, "f%s", request_token);
                else {
                    sprintf(node->write_msg.buffer, "o%s", request_token);
                    logger("<Server><process_command>and it is ok\n");
                }
            }
        }
        if(ENCRYPTION_ENABLED)
            encrypt_for_client(node->write_msg.buffer, node->pubkey);
        FD_SET(node->socket_fd, &(maintainer->fd_write_set));
    } else {
        /*close_client_connection(maintainer, node->socket_fd, node, TRUE);*/
        logger("<Server><process_command>got invalid command from client\n");
        return 1;
    }
    return 0;
}