示例#1
0
/* code the taskname */
t_taskcode find_taskcode(const char *task_name) {
   rb_red_blk_node *newNode;
   assert(libraryStatus == initialized);      
   
   if ( ( newNode = RBExactQuery( all_tasknames, task_name) ) ) {
      /* if already present in the collection */
      TEST_PROGRESS("find_taskcode ALREADY SPECIFIED,  %s  -->  %d\n", task_name, *(t_taskcode*) newNode->info);
      return *(t_taskcode*) (newNode->info);
   } else {
      /* still not present in the collection */
      
      /* add it to the collection of tasknames */      
      t_taskcode task_code;
      task_code = get_new_taskname_code();
      add_taskname_to_tree(task_name, task_code, all_tasknames);

      /* add it to the collection of nonspecified tasknames */      
      exist_nonspecified_tasknames = True;
      add_taskname_to_tree(task_name, task_code, nonspecified_tasknames);
      
      /* now it is already present in the tree */      
      newNode = RBExactQuery( all_tasknames, task_name);
      assert(newNode);
      TEST_PROGRESS("find_taskcode NOT YET SPECIFIED,  %s  -->  %d\n", task_name, *(t_taskcode*) newNode->info);
      return *(t_taskcode*) (newNode->info);
   }
}
示例#2
0
void write_client_msg(Client* client, int write_fd)
{
    rb_red_blk_node* transfer = RBExactQuery(client->transfers, &write_fd);
    File_msg* file_msg = (File_msg*)(transfer->info);
    /*it is Encryption of a request or a transfer + or (data + Encryption)*/
    int valwrite = write(write_fd, file_msg->msg.buffer+file_msg->msg.offset, BUFFER_SIZE-file_msg->msg.offset);
    file_msg->msg.offset += valwrite;
    if(file_msg->msg.offset == BUFFER_SIZE) {
        logger("<Client><write_client_msg> got full message to write\n");
        if((file_msg->msg.total_len != 0) && (file_msg->msg.offset < file_msg->msg.total_len)) { /*fetch next part of the file*/
            if(ENCRYPTION_ENABLED) {
                char file_read_buffer[BUFFER_SIZE];
                for(int i=0; i<BUFFER_SIZE; ++i)
                    file_read_buffer[i] = file_msg->msg.buffer[i];
                file_msg->msg.offset += read(file_msg->file_fd, file_read_buffer, BUFFER_SIZE);
                AES128_ECB_encrypt(file_read_buffer, file_msg->aes_key, file_msg->msg.buffer);
                logger("<Client><write_client_msg>read full chunck from file and encrypted it\n");
            } else {
                read(file_msg->file_fd, file_msg->msg.buffer, BUFFER_SIZE);
                logger("<Client><write_client_msg>read full chunck from file and encrypted it\n");
            }
        } else if((file_msg->msg.total_len != 0)) { //write finished
            logger("<Client><write_client_msg>writing to the other end finished\n");
            FD_CLR(write_fd, &(client->fd_write_set));
            close(file_msg->file_fd);
        } else {
            logger("<Client><write_client_msg>transfer message\n");
            char file_read_buffer[BUFFER_SIZE];
            for(int i=0; i<BUFFER_SIZE; ++i)
                file_read_buffer[i] = file_msg->msg.buffer[i];
            AES128_ECB_encrypt(file_read_buffer, file_msg->aes_key, file_msg->msg.buffer);
            FD_CLR(write_fd, &(client->fd_read_set));
        }
    }
}
//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;
}
示例#4
0
dhcp_full_packet_t * dhcp_cache_find(const dhcp_parsed_message_t * request,
		dhcp_full_packet_t * response, size_t * dhcp_data_len)
{
	/* Lock cache for read */
	cache_rdlock();

	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;

	dhcp_cache_node_t * cached_node = NULL;
	if ( ( f_node = RBExactQuery(cache, &s_data) ) ) 
	{
		cached_node = f_node->info;
		*dhcp_data_len = cached_node->dhcp_data_len;
		memcpy(response, &cached_node->cached_response, *dhcp_data_len);
	} else 
	{
		response = NULL;
		*dhcp_data_len = 0;
	}

	cache_unlock();

	return response;
}
示例#5
0
void close_client_connection(Maintainer* maintainer, int current_socket, Node* node, int exception)
{
    getpeername(current_socket, (struct sockaddr*)&(maintainer->address),
                (socklen_t*)&(maintainer->addrlen));
    logger("<Server><close_client_connection>Host disconnected, ip %s, port %d \n",
           inet_ntoa(maintainer->address.sin_addr), ntohs(maintainer->address.sin_port));
    RBDelete(maintainer->nodes_ip,RBExactQuery(maintainer->nodes_ip, &(maintainer->address.sin_addr.s_addr))); /*TODO memory leak?*/
    FD_CLR(current_socket, &(maintainer->fd_read_set));
    FD_CLR(current_socket, &(maintainer->fd_exception_set));
    FD_CLR(current_socket, &(maintainer->fd_write_set));
    if(maintainer->max_sd == current_socket) {
        maintainer->max_sd = maintainer->master_socket;
        struct Nodes_ll* iterator = maintainer->clients;
        while(iterator != NULL) {
            if((iterator->node->socket_fd > maintainer->max_sd) && (iterator->node->socket_fd != current_socket))
                maintainer->max_sd = iterator->node->socket_fd;
            iterator = iterator->next;
        }
    }
    struct Files_ll* iterator= node->node_files;
    while(iterator != NULL) {
        --(iterator->file->num_of_owners);
        struct Nodes_ll* jterator = iterator->file->owners;
        struct Nodes_ll* pjterator = iterator->file->owners;
        while(jterator != NULL) {
            if(jterator->node->socket_fd == current_socket) {
                if(jterator != iterator->file->owners) {
                    pjterator->next = jterator->next;
                    myfree(jterator);
                    break;
                } else {
                    iterator->file->owners = iterator->file->owners->next;
                }
            }
            if(jterator != iterator->file->owners)
                pjterator = pjterator->next;
            jterator = jterator->next;
        }
        struct Files_ll* tmp = iterator;
        iterator = iterator->next;
        myfree(tmp);
    }
    RBTreeDestroy(node->requests); /*TODO memory leak?*/
    node->socket_fd = -1;
    close(current_socket);
}
示例#6
0
文件: rbtree984.cpp 项目: tlubin/blt
void RBTree::RBDelete(int key) {
  rb_red_blk_node* y;
  rb_red_blk_node* x;
  rb_red_blk_node* nil=tree->nil;
  rb_red_blk_node* root=tree->root;
  rb_red_blk_node* z = RBExactQuery(key);

  if (!z) {
    return;
  }

  y= ((z->left == nil) || (z->right == nil)) ? z : TreeSuccessor(z);
/* XXX: original code was :   x= (y->left == nil) ? y->right : y->left; */
  x= (y->left  >  nil) ? y->right : y->left;
  if (root == (x->parent = y->parent)) {     root->left=x;
  } else {
    if (y == y->parent->left) {
      y->parent->left=x;
    } else {
      y->parent->right=x;
    }
  }
  if (y != z) { 
    
    if (!(y->red)) RBDeleteFixUp(x);
  
    y->left=z->left;
    y->right=z->right;
    y->parent=z->parent;
    y->red=z->red;
    z->left->parent=z->right->parent=y;
    if (z == z->parent->left) {
      z->parent->left=y; 
    } else {
      z->parent->right=y;
    }
    free(z); 
  } else {
    if (!(y->red)) RBDeleteFixUp(x);
    free(y);
  }
  
}
示例#7
0
/* 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);   
   
}
示例#8
0
BOOLEAN value_exists(unsigned int set_type, OBJECT_PTR val)
{

#ifdef GC_USES_HASHTABLE

  if(set_type == WHITE)
    return(hashtable_get(white, (void *)val) != NULL);
  else if(set_type == GREY)
    return(hashtable_get(grey, (void *)val) != NULL);
  else if(set_type == BLACK)
    return(hashtable_get(black, (void *)val) != NULL);
  else
    assert(false);

#else

  rb_red_blk_tree *tree;

  if(set_type == WHITE)
    tree = white;
  else if(set_type == GREY)
    tree = grey;
  else if(set_type == BLACK)
    tree = black;
  else
    assert(false);

  if(!tree)
    return false;

  rb_red_blk_node* newNode;
  if((newNode=RBExactQuery(tree,&val)))
    return true;
  else
    return false;

#endif
}
示例#9
0
void remove_node(unsigned int set_type, OBJECT_PTR val)
{

#ifdef GC_USES_HASHTABLE

  if(set_type == WHITE)
    hashtable_remove(white, (void *)val);
  else if(set_type == GREY)
    hashtable_remove(grey, (void *)val);
  else if(set_type == BLACK)
    hashtable_remove(black, (void *)val);
  else
    assert(false);

#else

  rb_red_blk_tree *tree;

  if(set_type == WHITE)
    tree = white;
  else if(set_type == GREY)
    tree = grey;
  else if(set_type == BLACK)
    tree = black;
  else
    assert(false);

  if(!tree)
    return;

  rb_red_blk_node* newNode;
  if((newNode=RBExactQuery(tree,&val))) 
    RBDelete(tree,newNode);  

#endif
}
示例#10
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);
      }
    }
  }
示例#11
0
文件: rbtree984.cpp 项目: tlubin/blt
bool RBTree::RBMember(int key) {
  return RBExactQuery(key) != NULL;
}
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;
}
示例#13
0
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);
            }
        }
    }
}
示例#14
0
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");
    }
}
示例#15
0
文件: ranktest.c 项目: dkondor/rbtree
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;
}
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;
}
示例#17
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;
}
示例#18
0
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;
}
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);
	}