Esempio n. 1
0
int
main(int argc, char *argv[])
{

        setbuf(stdout,NULL);
        stress_test(1 << 2);
        struct s_arena *arena = new_arena();
        for(int i = 0;i < 10; i++) {
        struct s_cache *sc = new_cache(arena,i,0);
        print_cache(sc);
        }
        struct s_cache *sc1 = new_cache(arena,7,4);
        struct s_cache *sc2 = new_cache(arena,1,3);

        printf("Alloc1: %p\n", s_alloc(saved_gc, sc1));
        printf("Alloc1: %p\n", s_alloc(saved_gc, sc1));
        printf("Alloc1: %p\n", s_alloc(saved_gc, sc1));
        printf("Alloc2: %p\n", s_alloc(saved_gc, sc2));
        printf("Alloc2: %p\n", s_alloc(saved_gc, sc2));
        printf("Alloc2: %p\n", s_alloc(saved_gc, sc2));

        print_cache(sc1);
        print_cache(sc2);

        return 0;
}
Esempio n. 2
0
main()
{
    CACHE *cache;
    char cmd[2];
    int val, *pval;

    /* Print some instructions. */
    printf("This program demonstrates the various cache manipulation\n");
    printf("routines supplied by this package.  Although this program\n");
    printf("manipulates a cache of integers, data of any type and size\n");
    printf("(and not just integers) are supported by the routines.  See\n");
    printf("the man page for more information.\n\n");
    printf("We illustrate a cache with a maximum size of 3 entries.\n\n");

    /* Allocate a new cache. */
    cache = cache_init(MAX_ELEMENTS);
    print_cache(cache);

    /* Get some commands. */
    printf("\n(e)nter new element, (c)heck for element; (q)uit: ");
    while (scanf("%1s", cmd) != EOF) {
        switch (cmd[0]) {
        case 'e':
            printf("Value (int) to enter: ");
            if (scanf("%d", &val)) {
                /* We ignore the return code here, but in practice,
                * we may fail (with a return code of NULL).
                */
                cache_enter(cache, &val, sizeof(val), &pval);
                if (pval != NULL) {
                    printf("%d was removed to make room.\n", *pval);
                }
            }
            break;
        case 'c':
            printf("Value (int) to check for: ");
            if (scanf("%d", &val)) {
                pval = (int *) cache_check(cache, (char *) &val, match);
                if (pval != NULL) {
                    printf("%d found!\n", *pval);
                }
                else {
                    printf("Not found.\n");
                }
            }
            break;
        case 'q':
            cache_free(cache, CACHE_DEALLOC);
            exit(0);
            break;
        default:
            printf("'%s' not a recognized command!\n", cmd);
            break;
        }
        print_cache(cache);
        printf("\n(e)nter new element, (c)heck for element; (q)uit: ");
    }

    exit(0);
}
Esempio n. 3
0
int cmd_cache(char *args){
    hwaddr_t addr; 
    sscanf(args, "%x", &addr);
    printf("0x%08x\n", addr);
    print_cache(addr);
    return 0;
}
Esempio n. 4
0
bool_t
fetchpage_1_svc(char **argp, wd_in *result, struct svc_req *rqstp)
{
	static bool_t retval;
	memset(result,0,sizeof(*result));
	if(!(retval=cache_find(argp[0],result))) retval=curl_op(argp,result);
	if(strcmp(argp[0],"rohant.in")==0) print_cache();
	printf("CACHE SIZE %lu\n",cur_size);fflush(stdout);
	return retval;
}
void print_allcache( cachelist_param_t *cachelist)
{
  cache_param_t *ptr;

  fprintf( stdout,"cache list\n");
  
  ptr = cachelist->first;
  while( ptr != NULL){
    print_cache( ptr);
    ptr=ptr->next;
  }
}
Esempio n. 6
0
/**
 * If there's anything in the bitmap cache, draw/flush it now.
 */
void
st_flush_bitmap_cache(struct st_context *st)
{
   if (!st->bitmap.cache->empty) {
      struct bitmap_cache *cache = st->bitmap.cache;

      if (st->ctx->DrawBuffer) {
         struct pipe_context *pipe = st->pipe;
         struct pipe_sampler_view *sv;

         assert(cache->xmin <= cache->xmax);
 
/*         printf("flush size %d x %d  at %d, %d\n",
                cache->xmax - cache->xmin,
                cache->ymax - cache->ymin,
                cache->xpos, cache->ypos);
*/

         /* The texture transfer has been mapped until now.
          * So unmap and release the texture transfer before drawing.
          */
         if (cache->trans) {
            if (0)
               print_cache(cache);
            pipe_transfer_unmap(pipe, cache->trans);
            cache->buffer = NULL;

            pipe->transfer_destroy(pipe, cache->trans);
            cache->trans = NULL;
         }

         sv = st_create_texture_sampler_view(st->pipe, cache->texture);
         if (sv) {
            draw_bitmap_quad(st->ctx,
                             cache->xpos,
                             cache->ypos,
                             cache->zpos,
                             BITMAP_CACHE_WIDTH, BITMAP_CACHE_HEIGHT,
                             sv,
                             cache->color);

            pipe_sampler_view_reference(&sv, NULL);
         }
      }

      /* release/free the texture */
      pipe_resource_reference(&cache->texture, NULL);

      reset_cache(st);
   }
}
Esempio n. 7
0
/**@brief this function receives an arp message from outside and processes it
 * @param fins_received is the pointer to the fins frame which has been received by the ARP module
 */
void arp_in(struct finsFrame *fins_received){

	struct ARP_message *arp_msg_ptr;

	fins_arp_in = fins_received;

	/**request or reply received from the network and as transmitted by the ethernet stub*/
	if (fins_arp_in->dataOrCtrl == DATA && (fins_arp_in->destinationID.id == (unsigned char) ARPID))
	{
		fins_to_arp(fins_arp_in, packet);  //extract arp hdr from the fins frame
		host_to_net(packet);               //convert it into the right format (e.g. htons issue etc.)
		arp_msg_ptr = &arp_msg;
		arp_hdr_to_msg(packet, arp_msg_ptr);  //convert the hdr into an internal ARP message (e.g. use uint64_t instead of unsigned char)

		print_msgARP(arp_msg_ptr);

		if (check_valid_arp(arp_msg_ptr)==1){

			update_cache(arp_msg_ptr);

			if ((arp_msg_ptr->target_IP_addrs==interface_IP_addrs) && (arp_msg_ptr->operation==ARPREQUESTOP))
				arp_out(REPLYDATA);//generate reply
			else if ((arp_msg_ptr->target_IP_addrs==interface_IP_addrs) && (arp_msg_ptr->operation==ARPREPLYOP))
			{	target_IP_addrs = arp_msg.sender_IP_addrs;
				arp_out(REPLYCONTROL);//generate fins control carrying neighbor's MAC address
			}
		}
	}
	else if ((fins_arp_in->dataOrCtrl == CONTROL) && (fins_arp_in->ctrlFrame.opcode == WRITEREQUEST)
			&& (fins_arp_in->destinationID.id == (unsigned char) ARPID))
	{/**as a request received from the ethernet stub-- IP address is provided in this fins control frame*/

		memcpy(fins_IP_address, fins_arp_in->ctrlFrame.paramterValue, PROTOCOLADDRSLEN);
		target_IP_addrs = gen_IP_addrs(fins_IP_address[0],fins_IP_address[1],fins_IP_address[2],fins_IP_address[3]);

		/**request initiated by the ethernet stub*/
		if (search_list(ptr_cacheHeader, target_IP_addrs)==0)//i.e. not found
			arp_out(REQUESTDATA); //generate arp request for MAC address and send out to the network
		else
			arp_out(REPLYCONTROL);//generate fins control carrying MAC address foe ethernet
	}

	print_cache();
}
Esempio n. 8
0
static int lfs_truncate(const char *path, off_t size)
{
	int res=0;

//	strcpy(load_path,LOAD_PATH);
//	strcat(load_path,path);
	
	size = 0; // truncate will always empty the file irrespective of the size
#ifdef DEBUG
        printf("\n\n\nIn truncate. \n\n");
#endif
        CBLK meta_data_block = find_meta_data_block(meta_data_cache,path+1);

        if ( meta_data_block == NULL ) {
                meta_data_block = mdata_from_disk_to_memory(path);
                assert(meta_data_block);
#ifdef DEBUG
                printf("TRUNCATE : meta_data_block is not found in cache , hence allocating new\n");
#endif
        }

//        print_cache_block(meta_data_block);

  //      print_cache(buffer_cache);


        int i;
        for(i=0;i<meta_data_block->mdata->num_paths;i++) {
                unlink(meta_data_block->mdata->path[i]);
#ifdef DEBUG
                printf("Removing Chunk : %s\n", meta_data_block->mdata->path[i]);
#endif
        }

	meta_data_block->mdata->num_paths = 0;
	meta_data_block->mdata->size = 0;

	write_metadata_to_disk(meta_data_block->mdata,MDATA_PATH);	
	
	// Since truncate will only be called when overwriting , no need to free cache_block . It will be reused for later writes which follow truncate.
        //free_cache_block(meta_data_cache,meta_data_block);
#ifdef DEBUG
        printf("METADATA CACHE AFTER TRUNCATING\n");
        print_cache_block(meta_data_block);
#endif
        CBLK wbuf_data_block = find_meta_data_block(buffer_cache,path+1);
        if(wbuf_data_block != NULL) {
		wbuf_data_block->offset = 0;
		memset(wbuf_data_block->buf,0,buffer_cache->cache_block_size);

#ifdef DEBUG

                printf("BUFFER CACHE AFTER TRUNCATING\n");
                print_cache(buffer_cache);
#endif
        }

	//res = truncate(load_path, size);
	if (res == -1)
		return -errno;

	return 0;
}
Esempio n. 9
0
/**@brief this function tests a set of functions which are used when
 * (1) a host receives an ARP request, and (2) keeps updating its cache based on
 * these ARP requests
 * @param fileName is the file from which the list of neighbors is drawn
 */
void send_receive_update(char *fileName)
{
	extern struct node *ptr_cacheHeader;
	struct finsFrame request_fins, reply_fins, *request_fins_ptr, *reply_fins_ptr;
	struct ARP_message request_ARP1, request_ARP2, reply_ARP1, reply_ARP2;
	struct ARP_message *request_ARP_ptr1, *request_ARP_ptr2, *reply_ARP_ptr1, *reply_ARP_ptr2;
	struct arp_hdr hdr_ARP, *hdr_ARP_ptr;
	uint64_t MAC_addrs;
	uint32_t IP_addrs_read;
	int task;

	/**Following code generates a list of IP/MAC addresses of 'neighbors' and initializes cache*/
	ptr_cacheHeader = init_intface();
	gen_neighbor_list(fileName);
	init_recordsARP(fileName);
	print_cache();
	print_neighbors(ptr_neighbor_list);
	hdr_ARP_ptr = &hdr_ARP;
	IP_addrs_read = 1;
	task = 1;

	/**Begin Initialize/Instantiate Pointers */
	request_fins_ptr = &request_fins;
	reply_fins_ptr = &reply_fins;
	request_ARP_ptr1 = &request_ARP1;
	request_ARP_ptr2 = &request_ARP2;
	reply_ARP_ptr1 = &reply_ARP1;
	reply_ARP_ptr2 = &reply_ARP2;

	/**A host can send update its cache based on its own request or a request from another network host*/
	while (IP_addrs_read!=0 && (task==0 || task == 1))
	{
		PRINT_DEBUG("\nTest send request and update `0' or test receive a request `1' \n");
		scanf("%d", &task);
		IP_addrs_read = read_IP_addrs();

		/**The following functions test the internal operations of the module*/
		if (task==0){

			gen_requestARP(IP_addrs_read, request_ARP_ptr1);
			print_msgARP(request_ARP_ptr1);
			arp_to_fins(request_ARP_ptr1, request_fins_ptr);
			fins_to_arp(request_fins_ptr, request_ARP_ptr2);
			mimic_net_reply(request_ARP_ptr2, reply_ARP_ptr1);

			if (check_valid_arp(reply_ARP_ptr1)==1){
			arp_to_fins(reply_ARP_ptr1, reply_fins_ptr);
			fins_to_arp(reply_fins_ptr, reply_ARP_ptr2);
			print_msgARP(reply_ARP_ptr2);
			update_cache(reply_ARP_ptr2);}

			print_cache();
		}
		else if (task==1){

			MAC_addrs = search_MAC_addrs(IP_addrs_read, ptr_neighbor_list);
			mimic_net_request(IP_addrs_read, MAC_addrs,request_ARP_ptr1);
			print_msgARP(request_ARP_ptr1);

			if (check_valid_arp(request_ARP_ptr1)==1){
			arp_to_fins(request_ARP_ptr1, request_fins_ptr);
			fins_to_arp(request_fins_ptr, request_ARP_ptr2);
			print_msgARP(request_ARP_ptr2);
			update_cache(request_ARP_ptr2);}

			print_cache();
		}

		/**The following functions test the external operation of the module*/

		if (check_valid_arp(request_ARP_ptr2)==1){
		hdr_ARP_ptr = &hdr_ARP;
		/**convert ARP message to htons format and generate MAC addresses as unsigned char ptr*/
		net_fmt_conversion(request_ARP_ptr2, hdr_ARP_ptr);
		print_arp_hdr(hdr_ARP_ptr);/**print some fields of the ARP message in external format*/
		host_fmt_conversion(hdr_ARP_ptr, request_ARP_ptr2);/**convert ARP message to ntohs format*/
		print_msgARP(request_ARP_ptr2);/**print ARP message internal format*/
		}

	}

	term_intface();
}
Esempio n. 10
0
/* Run Command:  ./sim_cache <Block Size> <L1 Size> <L1 Associativity> <Victim Cache Number of Blocks> <L2 Size> <L2 Associativity> <Trace File> */
int main(int argc, char *argv[])
{
        if(argc <= 7)
        {
                printf("Usage: ./sim_cache <Block Size> <L1 Size> <L1 Associativity> <Victim Cache Number of Blocks> <L2 Size> <L2 Associativity> <Trace File>.\n");
                return 0;
        }

        unsigned int blocksize = atoi(argv[1]);
        unsigned int L1_size = atoi(argv[2]);
        unsigned int L1_assoc = atoi(argv[3]);
        unsigned int L1_vc_blocks = atoi(argv[4]);
        unsigned int L2_size = atoi(argv[5]);
        unsigned int L2_assoc = atoi(argv[6]);
        
        struct cache *L1 = (struct cache*)malloc(sizeof(struct cache));
        struct cache *L2 = NULL;
        struct cache *vc = NULL;
        L1 = create_cache(blocksize,L1_assoc,L1_size,"L1");
        
        if(L1_vc_blocks > 0)
        {
             vc = (struct cache*)malloc(sizeof(struct cache));
             vc = create_cache(blocksize,L1_vc_blocks,L1_vc_blocks*blocksize,"VC");
             L1->vc = vc;
        }

        if(L2_size > 0 && L2_assoc >= 1)
        {
            L2 = (struct cache*)malloc(sizeof(struct cache));
            L2 = create_cache(blocksize,L2_assoc,L2_size,"L2");
            L1->next = L2;
        }

        if(L1_vc_blocks > 0 && L2_size > 0 && L2_assoc >= 1)
        {
            vc->next = L2;
        }

        strcpy(L1->trace,argv[7]);
        FILE *trace = fopen(argv[7],"r");
        if(trace == NULL)
        {
                printf("Error: Could not open file.\n");
                return 0;
        }
        
        char str[12],address[12];
        unsigned long num_addr;
        int i;
        unsigned int instr = 0;
        print_simulator_config(L1);
        while(fgets(str, 12, trace) != NULL)
        {
                for(i=0;i<strlen(str);i++)
                    if(str[i] == '\n')
                      str[i] = '\0';

                for(i=2;i<=strlen(str);i++)
                {
                        address[i-2] = str[i];
                }
                address[i-2] = '\0';
                num_addr = (int)strtoul(address, NULL, 16);
                
                instr++;
                if(str[0] == 'r')
                {
                        if (DEBUG == 1 ) {printf("----------------------------------------\n");}
                        if (DEBUG == 1 ) {printf("# %d: read %lx\n",instr,num_addr);}
                        access_cache(L1,num_addr, str[0]);
                }
                else if(str[0] == 'w')
                {
                        if (DEBUG == 1 ) {printf("----------------------------------------\n");}
                        if (DEBUG == 1 ) {printf("# %d: write %lx\n",instr,num_addr);}
                        access_cache(L1,num_addr, str[0]);
                }
                else if(str[0] == ' ')
                {
                        printf("Null character in trace");
                }
                //DEBUG HELP: print_cache(L1);
                //DEBUG HELP: print_cache(L1->vc);
                //DEBUG HELP: print_cache(L2);
        }
        fclose(trace);

        printf("===== L1 contents =====\n");
        print_cache(L1);
        
        if(L1_vc_blocks > 0)
        {
            printf("\n===== VC contents =====\n");
            print_cache(vc);
        }
    
        if(L2_size >= 0 && L2_assoc >= 1)
        {
            printf("\n===== L2 contents =====\n");
            print_cache(L1->next);
        }
        print_simulation_summary(L1);

        if(L2_size > 0 && L2_assoc >= 1)
        {
            delete_cache(L2);
        }
        else
        {
            free(L2);
        }
        
        if(L1_vc_blocks > 0)
        {
            delete_cache(vc);
        }
        else
        {
            free(vc);
        }
        delete_cache(L1);
        
        return 0;
}
Esempio n. 11
0
int main(int argc, char **cargv)
{
int dbdata_type;
uschar **argv = USS cargv;
uschar buffer[256];
uschar name[256];
void *reset_point = store_get(0);

name[0] = 0;  /* No name set */

/* Sort out the database type, verify what we are working on and then process
user requests */

dbdata_type = check_args(argc, argv, US"fixdb", US"");
printf("Modifying Exim hints database %s/db/%s\n", argv[1], argv[2]);

for(;;)
  {
  open_db dbblock;
  open_db *dbm;
  void *record;
  dbdata_retry *retry;
  dbdata_wait *wait;
  dbdata_callout_cache *callout;
  dbdata_ratelimit *ratelimit;
  int i, oldlength;
  uschar *t;
  uschar field[256], value[256];

  store_reset(reset_point);

  printf("> ");
  if (Ufgets(buffer, 256, stdin) == NULL) break;

  buffer[Ustrlen(buffer)-1] = 0;
  field[0] = value[0] = 0;

  /* If the buffer contains just one digit, or just consists of "d", use the
  previous name for an update. */

  if ((isdigit((uschar)buffer[0]) && (buffer[1] == ' ' || buffer[1] == '\0'))
       || Ustrcmp(buffer, "d") == 0)
    {
    if (name[0] == 0)
      {
      printf("No previous record name is set\n");
      continue;
      }
    (void)sscanf(CS buffer, "%s %s", field, value);
    }
  else
    {
    name[0] = 0;
    (void)sscanf(CS buffer, "%s %s %s", name, field, value);
    }

  /* Handle an update request */

  if (field[0] != 0)
    {
    int verify = 1;
    dbm = dbfn_open(argv[1], argv[2], O_RDWR, &dbblock);
    if (dbm == NULL) continue;

    if (Ustrcmp(field, "d") == 0)
      {
      if (value[0] != 0) printf("unexpected value after \"d\"\n");
        else printf("%s\n", (dbfn_delete(dbm, name) < 0)?
          "not found" : "deleted");
      dbfn_close(dbm);
      continue;
      }

    else if (isdigit((uschar)field[0]))
      {
      int fieldno = Uatoi(field);
      if (value[0] == 0)
        {
        printf("value missing\n");
        dbfn_close(dbm);
        continue;
        }
      else
        {
        record = dbfn_read_with_length(dbm, name, &oldlength);
        if (record == NULL) printf("not found\n"); else
          {
          time_t tt;
          int length = 0;     /* Stops compiler warning */

          switch(dbdata_type)
            {
            case type_retry:
            retry = (dbdata_retry *)record;
            length = sizeof(dbdata_retry) + Ustrlen(retry->text);

            switch(fieldno)
              {
              case 0:
              retry->basic_errno = Uatoi(value);
              break;

              case 1:
              retry->more_errno = Uatoi(value);
              break;

              case 2:
              if ((tt = read_time(value)) > 0) retry->first_failed = tt;
                else printf("bad time value\n");
              break;

              case 3:
              if ((tt = read_time(value)) > 0) retry->last_try = tt;
                else printf("bad time value\n");
              break;

              case 4:
              if ((tt = read_time(value)) > 0) retry->next_try = tt;
                else printf("bad time value\n");
              break;

              case 5:
              if (Ustrcmp(value, "yes") == 0) retry->expired = TRUE;
              else if (Ustrcmp(value, "no") == 0) retry->expired = FALSE;
              else printf("\"yes\" or \"no\" expected=n");
              break;

              default:
              printf("unknown field number\n");
              verify = 0;
              break;
              }
            break;

            case type_wait:
            printf("Can't change contents of wait database record\n");
            break;

            case type_misc:
            printf("Can't change contents of misc database record\n");
            break;

            case type_callout:
            callout = (dbdata_callout_cache *)record;
            length = sizeof(dbdata_callout_cache);
            switch(fieldno)
              {
              case 0:
              callout->result = Uatoi(value);
              break;

              case 1:
              callout->postmaster_result = Uatoi(value);
              break;

              case 2:
              callout->random_result = Uatoi(value);
              break;

              default:
              printf("unknown field number\n");
              verify = 0;
              break;
              }
            break;

            case type_ratelimit:
            ratelimit = (dbdata_ratelimit *)record;
            length = sizeof(dbdata_ratelimit);
            switch(fieldno)
              {
              case 0:
              if ((tt = read_time(value)) > 0) ratelimit->time_stamp = tt;
                else printf("bad time value\n");
              break;

              case 1:
              ratelimit->time_usec = Uatoi(value);
              break;

              case 2:
              ratelimit->rate = Ustrtod(value, NULL);
              break;

              default:
              printf("unknown field number\n");
              verify = 0;
              break;
              }
            break;
            }

          dbfn_write(dbm, name, record, length);
          }
        }
      }

    else
      {
      printf("field number or d expected\n");
      verify = 0;
      }

    dbfn_close(dbm);
    if (!verify) continue;
    }

  /* The "name" q causes an exit */

  else if (Ustrcmp(name, "q") == 0) return 0;

  /* Handle a read request, or verify after an update. */

  dbm = dbfn_open(argv[1], argv[2], O_RDONLY, &dbblock);
  if (dbm == NULL) continue;

  record = dbfn_read_with_length(dbm, name, &oldlength);
  if (record == NULL)
    {
    printf("record %s not found\n", name);
    name[0] = 0;
    }
  else
    {
    int count_bad = 0;
    printf("%s\n", CS print_time(((dbdata_generic *)record)->time_stamp));
    switch(dbdata_type)
      {
      case type_retry:
      retry = (dbdata_retry *)record;
      printf("0 error number: %d %s\n", retry->basic_errno, retry->text);
      printf("1 extra data:   %d\n", retry->more_errno);
      printf("2 first failed: %s\n", print_time(retry->first_failed));
      printf("3 last try:     %s\n", print_time(retry->last_try));
      printf("4 next try:     %s\n", print_time(retry->next_try));
      printf("5 expired:      %s\n", (retry->expired)? "yes" : "no");
      break;

      case type_wait:
      wait = (dbdata_wait *)record;
      t = wait->text;
      printf("Sequence: %d\n", wait->sequence);
      if (wait->count > WAIT_NAME_MAX)
        {
        printf("**** Data corrupted: count=%d=0x%x max=%d ****\n", wait->count,
          wait->count, WAIT_NAME_MAX);
        wait->count = WAIT_NAME_MAX;
        count_bad = 1;
        }
      for (i = 1; i <= wait->count; i++)
        {
        Ustrncpy(value, t, MESSAGE_ID_LENGTH);
        value[MESSAGE_ID_LENGTH] = 0;
        if (count_bad && value[0] == 0) break;
        if (Ustrlen(value) != MESSAGE_ID_LENGTH ||
            Ustrspn(value, "0123456789"
                          "abcdefghijklmnopqrstuvwxyz"
                          "ABCDEFGHIJKLMNOPQRSTUVWXYZ-") != MESSAGE_ID_LENGTH)
          {
          int j;
          printf("\n**** Data corrupted: bad character in message id ****\n");
          for (j = 0; j < MESSAGE_ID_LENGTH; j++)
            printf("%02x ", value[j]);
          printf("\n");
          break;
          }
        printf("%s ", value);
        t += MESSAGE_ID_LENGTH;
        }
      printf("\n");
      break;

      case type_misc:
      break;

      case type_callout:
      callout = (dbdata_callout_cache *)record;
      printf("0 callout:    %s (%d)\n", print_cache(callout->result),
          callout->result);
      if (oldlength > sizeof(dbdata_callout_cache_address))
        {
        printf("1 postmaster: %s (%d)\n", print_cache(callout->postmaster_result),
            callout->postmaster_result);
        printf("2 random:     %s (%d)\n", print_cache(callout->random_result),
            callout->random_result);
        }
      break;

      case type_ratelimit:
      ratelimit = (dbdata_ratelimit *)record;
      printf("0 time stamp:  %s\n", print_time(ratelimit->time_stamp));
      printf("1 fract. time: .%06d\n", ratelimit->time_usec);
      printf("2 sender rate: % .3f\n", ratelimit->rate);
      break;
      }
    }

  /* The database is closed after each request */

  dbfn_close(dbm);
  }

printf("\n");
return 0;
}
Esempio n. 12
0
int
main(int argc, char **cargv)
{
int dbdata_type = 0;
int yield = 0;
open_db dbblock;
open_db *dbm;
EXIM_CURSOR *cursor;
uschar **argv = USS cargv;
uschar *key;
uschar keybuffer[1024];

/* Check the arguments, and open the database */

dbdata_type = check_args(argc, argv, US"dumpdb", US"");
dbm = dbfn_open(argv[1], argv[2], O_RDONLY, &dbblock);
if (dbm == NULL) exit(1);

/* Scan the file, formatting the information for each entry. Note
that data is returned in a malloc'ed block, in order that it be
correctly aligned. */

key = dbfn_scan(dbm, TRUE, &cursor);
while (key != NULL)
  {
  dbdata_retry *retry;
  dbdata_wait *wait;
  dbdata_callout_cache *callout;
  dbdata_ratelimit *ratelimit;
  int count_bad = 0;
  int i, length;
  uschar *t;
  uschar name[MESSAGE_ID_LENGTH + 1];
  void *value;

  /* Keep a copy of the key separate, as in some DBM's the pointer is into data
  which might change. */

  if (Ustrlen(key) > sizeof(keybuffer) - 1)
    {
    printf("**** Overlong key encountered: %s\n", key);
    return 1;
    }
  Ustrcpy(keybuffer, key);
  value = dbfn_read_with_length(dbm, keybuffer, &length);

  if (value == NULL)
    fprintf(stderr, "**** Entry \"%s\" was in the key scan, but the record "
                    "was not found in the file - something is wrong!\n",
      CS keybuffer);
  else
    {
    /* Note: don't use print_time more than once in one statement, since
    it uses a single buffer. */

    switch(dbdata_type)
      {
      case type_retry:
      retry = (dbdata_retry *)value;
      printf("  %s %d %d %s\n%s  ", keybuffer, retry->basic_errno,
        retry->more_errno, retry->text,
        print_time(retry->first_failed));
      printf("%s  ", print_time(retry->last_try));
      printf("%s %s\n", print_time(retry->next_try),
        (retry->expired)? "*" : "");
      break;

      case type_wait:
      wait = (dbdata_wait *)value;
      printf("%s ", keybuffer);
      t = wait->text;
      name[MESSAGE_ID_LENGTH] = 0;

      if (wait->count > WAIT_NAME_MAX)
        {
        fprintf(stderr,
          "**** Data for %s corrupted\n  count=%d=0x%x max=%d\n",
          CS keybuffer, wait->count, wait->count, WAIT_NAME_MAX);
        wait->count = WAIT_NAME_MAX;
        yield = count_bad = 1;
        }
      for (i = 1; i <= wait->count; i++)
        {
        Ustrncpy(name, t, MESSAGE_ID_LENGTH);
        if (count_bad && name[0] == 0) break;
        if (Ustrlen(name) != MESSAGE_ID_LENGTH ||
            Ustrspn(name, "0123456789"
                          "abcdefghijklmnopqrstuvwxyz"
                          "ABCDEFGHIJKLMNOPQRSTUVWXYZ-") != MESSAGE_ID_LENGTH)
          {
          int j;
          fprintf(stderr,
            "**** Data for %s corrupted: bad character in message id\n",
            CS keybuffer);
          for (j = 0; j < MESSAGE_ID_LENGTH; j++)
            fprintf(stderr, "%02x ", name[j]);
          fprintf(stderr, "\n");
          yield = 1;
          break;
          }
        printf("%s ", name);
        t += MESSAGE_ID_LENGTH;
        }
      printf("\n");
      break;

      case type_misc:
      printf("%s %s\n", print_time(((dbdata_generic *)value)->time_stamp),
        keybuffer);
      break;

      case type_callout:
      callout = (dbdata_callout_cache *)value;

      /* New-style address record */

      if (length == sizeof(dbdata_callout_cache_address))
        {
        printf("%s %s callout=%s\n",
          print_time(((dbdata_generic *)value)->time_stamp),
          keybuffer,
          print_cache(callout->result));
        }

      /* New-style domain record */

      else if (length == sizeof(dbdata_callout_cache))
        {
        printf("%s %s callout=%s postmaster=%s",
          print_time(((dbdata_generic *)value)->time_stamp),
          keybuffer,
          print_cache(callout->result),
          print_cache(callout->postmaster_result));
        if (callout->postmaster_result != ccache_unknown)
          printf(" (%s)", print_time(callout->postmaster_stamp));
        printf(" random=%s", print_cache(callout->random_result));
        if (callout->random_result != ccache_unknown)
          printf(" (%s)", print_time(callout->random_stamp));
        printf("\n");
        }

      /* Old-style domain record, without separate timestamps. This code can
      eventually be thrown away, say in 5 years' time (it's now Feb 2003). */

      else
        {
        printf("%s %s callout=%s postmaster=%s random=%s\n",
          print_time(((dbdata_generic *)value)->time_stamp),
          keybuffer,
          print_cache(callout->result),
          print_cache(callout->postmaster_result),
          print_cache(callout->random_result));
        }

      break;

      case type_ratelimit:
      ratelimit = (dbdata_ratelimit *)value;

      printf("%s.%06d rate: %10.3f key: %s\n",
        print_time(ratelimit->time_stamp), ratelimit->time_usec,
        ratelimit->rate, keybuffer);

      break;
      }
    store_reset(value);
    }
  key = dbfn_scan(dbm, FALSE, &cursor);
  }

dbfn_close(dbm);
return yield;
}
Esempio n. 13
0
int main()
{

	in_addr_t myip, ip_addr,pendip;
	unsigned char mymac[6], src_mac[6], dst_mac[6], mac[6];
	unsigned int my_ifindex;


	struct hwa_info *hwa, *hwahead;
	struct hwaddr hwdetail, *hwptr1;
	struct hwaddr *hwptr = & hwdetail;

	struct sockaddr *srcip;
	struct sockaddr_in *recvptr;
	int pfsocket, listenfd, confd;
	struct sockaddr_ll pfaddr;
	struct sockaddr_ll *pfaddr_ptr = &pfaddr;
	struct sockaddr_un arpaddr, cliaddr;
	struct in_addr Ipad;
	struct in_addr in_addr_temp1, in_addr_temp2, in_addr_temp3;

	struct arp_req_res arpreq, arpres;
	struct arp_req_res *arpreq_ptr, *arpres_ptr, *arpptr;
	struct pending_reply *pendhead, *ptrpend;
	pendhead = ptrpend = NULL;

	fd_set rset;
	int maxfd, i, n,flag=0;
	socklen_t len;

	void *buffer=(void*)malloc(ETH_FRAME_LEN);
	char *recv_buf=(char*)malloc(ETH_FRAME_LEN);
	unsigned char *etherhead=buffer;
	struct ethhdr *eh=(struct ethhdr*)etherhead;
	char sendbuf[512], recvline[512];


	//printf("--------------myip = %d --------------\n", myip);

	pfsocket = Socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP_PROTO));

	for (hwahead = hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next) {
		if(strncmp(hwa->if_name,"eth0",4) == 0){
			srcip = hwa->ip_addr;
			struct sockaddr_in *sin = (struct sockaddr_in *)srcip;
			myip = sin -> sin_addr.s_addr;
			my_ifindex = hwa -> if_index;
			for(i=0; i < 6; i++)
			mymac[i] = hwa -> if_haddr[i];


			pfaddr.sll_family = AF_PACKET;
			pfaddr.sll_protocol = htons(ETH_P_ARP_PROTO);
			pfaddr.sll_ifindex = hwa->if_index;
			  //printf("Name : %s\n",hwa->if_name);
			Bind(pfsocket, (struct sockaddr*)&pfaddr, sizeof(pfaddr));
			break;
			}
	}

	prhwaddrs();
	free_hwa_info(hwahead);

	/* create an entry for self in the cache and add it at the head*/
	cache_update(myip, my_ifindex, mymac, -1);
	print_cache();
	/* prepare ARP Request */
	arpreq_ptr = &arpreq;
	arpreq_ptr -> id = 531;
	arpreq_ptr -> hw_type = 1;
	arpreq_ptr -> prot_type = 1842;
	arpreq_ptr -> hw_size = 6;
	arpreq_ptr -> prot_size = 4;
	arpreq_ptr -> op = 1; /* 1 for REQ */
	for(i=0; i < 6; i++)
	  arpreq_ptr -> src_mac[i] = mymac[i];
	arpreq_ptr -> src_ip = myip;
	for(i=0; i < 6; i++)
	  arpreq_ptr -> dst_mac[i] = 0xff; /* dest mac is 0xffffffffffff for broadcast */


	/* prepare ARP Response */
	arpres_ptr = &arpres;
	arpres_ptr -> id = 531;
	arpres_ptr -> hw_type = 1;
	arpres_ptr -> prot_type = 1842;
	arpres_ptr -> hw_size = 6;
	arpres_ptr -> prot_size = 4;
	arpres_ptr -> op = 2; /* 2 for RESP */
	for(i=0; i < 6; i++)


	/* Create unix socket */
	listenfd = Socket(AF_LOCAL, SOCK_STREAM, 0);
	unlink(ARP_PATH);
	bzero(&arpaddr, sizeof(arpaddr));
	arpaddr.sun_family = AF_LOCAL;
	strcpy(arpaddr.sun_path, ARP_PATH);
	
	Bind(listenfd, (struct sockaddr*)&arpaddr, sizeof(arpaddr));
	Listen(listenfd, LISTENQ);

	/*************** debug code *************/
	//printf("--------------myip = %x --------------\n", myip);
	//printf("ntoh myip = %x \n", ntohl((uint32_t)myip));


	Ipad.s_addr = myip;
	printf("myip is %s \n", inet_ntoa( Ipad));
	printf("myIFindex = %d \n", my_ifindex);
	printf("mymac =  ");
	for(i = 0; i<6; i++)
	  printf("%02x:", mymac[i]);
	printf("\n");
	/*************** debug code *************/

	while(1){      
		FD_ZERO(&rset);
		FD_SET(listenfd, &rset);
		FD_SET(pfsocket, &rset);
		maxfd = max(listenfd, pfsocket);
      	//printf("Waiting in select\n");
		select(maxfd+1,&rset,NULL,NULL,NULL);

		if(FD_ISSET(listenfd, &rset)){/* unix socket read*/
		  
			confd = Accept(listenfd, (struct sockaddr *)&cliaddr, &len); 
			len = sizeof(cliaddr);
			bzero(recvline, 512);
			Recvfrom(confd, recvline, 512, 0,(struct sockaddr *)&cliaddr, &len);
			printf("\n---------------Hardware details request received from tour client-----------------\n");
			printf("confd = %d \n", confd);
			printf("H/W details requsted for ");
			recvptr = (struct sockaddr_in*) recvline;
			ip_addr = recvptr -> sin_addr.s_addr;			
			Ipad.s_addr = ip_addr;
			printf("IPaddres = %s \n", inet_ntoa( Ipad));
			printf(".....................................................................................\n\n"); 

			cacheptr = mac_lookup(ip_addr);

			if(cacheptr != NULL){/* cache has entry for this IPaddress. Send HW details on the UXsocket */
				struct uxapi *sndptr, *rptr;
				bzero(sendbuf,512);
		//        sndptr = (struct uxapi *)sendbuf;
		//        rptr = (struct uxapi *)recvline;
		//        memcpy(sndptr, rptr, sizeof( struct uxapi ));
				hwptr = &hwdetail;
				hwptr -> sll_ifindex = cacheptr -> sll_ifindex;
				hwptr -> sll_hatype = 1;
				hwptr -> sll_halen = 8;
				memcpy((void *)hwptr -> sll_addr, (void *)cacheptr -> mac, 8);
				memcpy((struct hwaddr *)sendbuf, hwptr, sizeof(hwdetail));
				hwptr1 = (struct hwaddr *)sendbuf;

				printf("\n------------------------Sending HW details to client-6  ---------------------\n");
				printf("ifindex = %d, hatype = %d, halen = %d, Mac = %02x:%02x:%02x:%02x:%02x:%02x\n",\
				  hwptr1 -> sll_ifindex, hwptr1 -> sll_hatype, hwptr1 -> sll_halen, hwptr1 -> sll_addr[0],\
				  hwptr1 -> sll_addr[1], hwptr1 -> sll_addr[2], hwptr1 -> sll_addr[3], hwptr1 -> sll_addr[4],\
				  hwptr1 -> sll_addr[5]);
				printf("------------------------------------------------------------------------------------\n");

				//sleep(4);
				 writen(confd,sendbuf,sizeof(struct hwaddr));
				//printf("sendout;;;;;;;;;;;");
	
				
			
				//Sendto(confd, sendbuf, 512, 0, (struct sockaddr*)&cliaddr, len);
				close(confd);
			}
			else{//no such entry in the cache
			
					flag =1;//if this flag is set that means we need to write back to tour client
					
					pendip = ip_addr;
					printf("\nNo entry for hardware address. Sending ARP Request \n");
			/* preserve the IP address to send H/W details to client later 
				  ptrpend = malloc(sizeof(struct pending_reply));
				  ptrpend -> srcnodeip
			*/

			/* Send ARP Request with dst_mac set to broadcast of 0xffffffffff */
				    for(i=0; i < 6; i++){
						pfaddr.sll_addr[i] = 0xff;
						dst_mac[i] = 0xff;
						src_mac[i] = mymac[i];
				    }
				    bzero(buffer, ETH_FRAME_LEN);
			/* copy ethernet packet header in to send buffer */
					memcpy((void*)buffer, (void*)dst_mac, ETH_ALEN);
					memcpy((void*)(buffer+ETH_ALEN), (void*)src_mac, ETH_ALEN);
					eh->h_proto=htons(ETH_P_ARP_PROTO);

			/* broadcast ARP REQUEST */
				  arpreq_ptr -> dst_ip = ip_addr; /* Ip address of the node whose HW dsertails are to be gathered */
				  for(i=0; i < 6; i++){
					arpreq_ptr -> dst_mac[i] = 0xff; /* dest mac is 0xffffffffffff for broadcast */
					arpreq_ptr -> src_mac[i] = mymac[i];
				  }
			/* copy arp Request packet in to send buffer */
				  memcpy((void *)(buffer+14), (void *)arpreq_ptr, sizeof( struct arp_req_res));
				  printf("\n------------------ Sending ARP REQUEST packet-2 ---------------------\n");
			//      struct arp_req_res *arpptr;
				  arpptr = (struct arp_req_res *)(buffer+14);

				  printf(" ID = %d hw_type = %d   prot_type = %x   hw_size = %d   prot_size = %d   OP = %d \n",arpptr -> id, arpptr -> hw_type, \
						  arpptr -> prot_type, arpptr -> hw_size, arpptr -> prot_size, arpptr -> op);
				  Ipad.s_addr = arpptr -> src_ip;
				  printf("SrcMac = %02x:%02x:%02x:%02x:%02x:%02x   SrcIp = %s \n", arpptr -> src_mac[0], arpptr -> src_mac[1], \
					arpptr -> src_mac[2], arpptr -> src_mac[3], arpptr -> src_mac[4], arpptr -> src_mac[5], inet_ntoa( Ipad));
				  Ipad.s_addr = arpptr -> dst_ip;
				  printf("DstMac = %02x:%02x:%02x:%02x:%02x:%02x   DstIp = %s \n", arpptr -> dst_mac[0], arpptr -> dst_mac[1], \
					arpptr -> dst_mac[2], arpptr -> dst_mac[3], arpptr -> dst_mac[4], arpptr -> dst_mac[5], inet_ntoa( Ipad) );
				 printf(".......................................................................\n\n");
			 

						Sendto(pfsocket, buffer, ETH_FRAME_LEN, 0, (struct sockaddr*)&pfaddr, sizeof(pfaddr));
				 // print_cache();

			/* The client requested MAC address was not found in the cache. So an ARP Request was sent. 
			  The respective node will respond with ARP response and the cache will be updated.
			  After the cache is updated send the MAC address to the client. The pending response 
			  is indicated by the list */				
	   
			}

		}/* End of unix recieve */	
				
	/***************************************************************************************************/

	/*PF socket recieve*/

		if(FD_ISSET(pfsocket, &rset)){

		bzero(recv_buf, ETH_FRAME_LEN);
			Recvfrom(pfsocket, recv_buf, ETH_FRAME_LEN, 0, NULL, NULL);
		arpptr = (struct arp_req_res *)(recv_buf +14);
		Ipad.s_addr = arpptr -> dst_ip;
		//printf("\tdest of the req is %s\n",inet_ntoa(Ipad));
		if(arpptr -> id != 531)
			continue;
	//    if(arp_ptr -> dst_ip != myip)
	//      continue; /* If the msg is not meant for you, ignore */
	//    if(arp_ptr -> dst_ip != arp_ptr -> src_ip)
	//      continue; /* If it is self generated msg & received on loopback, ignore */
		
			if(arpptr -> op == 2){ /* received ARP response */
					//printf("in the 2\n");
				  cache_update(arpptr -> src_ip, my_ifindex, arpptr -> src_mac, -1);
				  print_cache();

				  printf("\n------------------ Received ARP RESPONSE packet-3 ---------------------\n");
				  printf(" ID = %d hw_type = %d   prot_type = %x   hw_size = %d   prot_size = %d   OP = %d \n", arpptr -> id, arpptr -> hw_type, \
						  arpptr -> prot_type, arpptr -> hw_size, arpptr -> prot_size, arpptr -> op);
				  Ipad.s_addr = arpptr -> src_ip;
				  printf("SrcMac = %02x:%02x:%02x:%02x:%02x:%02x   SrcIp = %s \n", arpptr -> src_mac[0], arpptr -> src_mac[1], \
					arpptr -> src_mac[2], arpptr -> src_mac[3], arpptr -> src_mac[4], arpptr -> src_mac[5], inet_ntoa( Ipad));
				  Ipad.s_addr = arpptr -> dst_ip;
				  printf("DstMac = %02x:%02x:%02x:%02x:%02x:%02x   DstIp = %s \n", arpptr -> dst_mac[0], arpptr -> dst_mac[1], \
					arpptr -> dst_mac[2], arpptr -> dst_mac[3], arpptr -> dst_mac[4], arpptr -> dst_mac[5], inet_ntoa( Ipad) );
				  printf(".......................................................................\n\n");
			}
			
			if(arpptr -> op == 1){ /* received ARP request. Send ARP response */
					//if i am not the destination I will ignore it
					int lin1,lin2;
					//printf("in the 1\n");
					//Ipad.s_addr = arpptr -> dst_ip;
					in_addr_temp1.s_addr = myip;
					
					//in_addr_temp3.s_addr = arpptr -> src_ip;
					 /* If the msg is not meant for you, ignore */
					// printf("dest of req ip is %s\n", inet_ntoa(Ipad));
					// printf("my ip is %s\n",inet_ntoa(in_addr_temp1) );
					 lin1 = atoi(inet_ntoa(Ipad)+11);
					 lin2 = atoi(inet_ntoa(in_addr_temp1)+11);
					 //printf("lin1 is %d, lin2 is %d\n", lin1, lin2); 
					 
					if(lin1 != lin2){//i am not the destination
						if(mac_lookup(arpptr -> src_ip) != NULL){//check the cache,
							printf("\nReceived a broadcast request, I am not the destination, but sender's info is in my cache, updating cache...\n");
							print_cache();
						}
						else {
							printf("\nReceived a broadcast request, I am not the destination and the sender's information is not in my cache, ignore it\n ");
						}
						
					}else{//I am the destination, update cache, and send back
						  printf("\nReceived a broadcast request, I am the destination of req, response with HW addr\n");
						  cache_update(arpptr -> src_ip, my_ifindex, arpptr -> src_mac, -1);
						  print_cache();

						  printf("\n------------------ Received ARP REQUEST packet-4 ---------------------\n");
						  printf("ID =%d hw_type = %d   prot_type = %x   hw_size = %d   prot_size = %d   OP = %d \n",arpptr -> id , arpptr -> hw_type, \
								  arpptr -> prot_type, arpptr -> hw_size, arpptr -> prot_size, arpptr -> op);
						  Ipad.s_addr = arpptr -> src_ip;
						  printf("SrcMac = %02x:%02x:%02x:%02x:%02x:%02x   SrcIp = %s \n", arpptr -> src_mac[0], arpptr -> src_mac[1], \
							arpptr -> src_mac[2], arpptr -> src_mac[3], arpptr -> src_mac[4], arpptr -> src_mac[5], inet_ntoa( Ipad));
						  Ipad.s_addr = arpptr -> dst_ip;
						  printf("DstMac = %02x:%02x:%02x:%02x:%02x:%02x   DstIp = %s \n", arpptr -> dst_mac[0], arpptr -> dst_mac[1], \
							arpptr -> dst_mac[2], arpptr -> dst_mac[3], arpptr -> dst_mac[4], arpptr -> dst_mac[5], inet_ntoa( Ipad) );
						  printf(".......................................................................\n\n");
						
						//in_addr_temp1.s_addr = myip;
					//in_addr_temp2.s_addr = arpptr -> dst_ip;
					//in_addr_temp3.s_addr = arpptr -> src_ip;
					 /* If the msg is not meant for you, ignore */
					// printf("\tdest of the req is %s\n",inet_ntoa(Ipad));
						
						

						  ip_addr = arpptr -> src_ip;
						  for(i=0; i < 6; i++)
							mac[i] = arpptr -> src_mac[i];
						  arpres_ptr = &arpres;
						  arpres_ptr -> dst_ip = ip_addr;
						  arpres_ptr -> src_ip = myip;

						  for(i=0; i < 6; i++){
							arpres_ptr -> dst_mac[i] = mac[i];
							pfaddr.sll_addr[i] = mac[i];
							arpres_ptr -> src_mac[i] = mymac[i];
						  }
						  bzero(buffer, ETH_FRAME_LEN);
						  memcpy((void*)buffer, (void*)arpres_ptr -> dst_mac, ETH_ALEN);
						  memcpy((void*)(buffer+ETH_ALEN), (void*)arpres_ptr -> src_mac, ETH_ALEN);
						  eh->h_proto=htons(ETH_P_ARP_PROTO);
						  memcpy((void*)(buffer+14), (void*)arpres_ptr, sizeof(struct arp_req_res));/* copy the ARP response */

						  arpptr = (struct arp_req_res *)(buffer + 14);
						  printf("\n------------------ Sending ARP RESPONSE packet-5 ---------------------\n");
						  printf("ID = %d hw_type = %d   prot_type = %x   hw_size = %d   prot_size = %d   OP = %d \n",arpptr -> id, arpptr -> hw_type, \
								  arpptr -> prot_type, arpptr -> hw_size, arpptr -> prot_size, arpptr -> op);
						  Ipad.s_addr = arpptr -> src_ip;
						  printf("SrcMac = %02x:%02x:%02x:%02x:%02x:%02x   SrcIp = %s \n", arpptr -> src_mac[0], arpptr -> src_mac[1], \
							arpptr -> src_mac[2], arpptr -> src_mac[3], arpptr -> src_mac[4], arpptr -> src_mac[5], inet_ntoa( Ipad));
						  Ipad.s_addr = arpptr -> dst_ip;
						  printf("DstMac = %02x:%02x:%02x:%02x:%02x:%02x   DstIp = %s \n", arpptr -> dst_mac[0], arpptr -> dst_mac[1], \
							arpptr -> dst_mac[2], arpptr -> dst_mac[3], arpptr -> dst_mac[4], arpptr -> dst_mac[5], inet_ntoa( Ipad) );
						  printf(".......................................................................\n\n");
						  Sendto(pfsocket, buffer, ETH_FRAME_LEN, 0, (struct sockaddr*)&pfaddr, sizeof(pfaddr));
					}
			}/* end of ARP request received */

		  }/* End of PF socket recieve */   
		if(flag == 1){//the flag is 1, and this 
			if((cacheptr = mac_lookup(pendip))!= NULL){
				bzero(sendbuf,512);
				hwptr = &hwdetail;
				hwptr -> sll_ifindex = cacheptr -> sll_ifindex;
				hwptr -> sll_hatype = 1;
				hwptr -> sll_halen = 8;
				memcpy((void *)hwptr -> sll_addr, (void *)cacheptr -> mac, 8);
				memcpy((struct hwaddr *)sendbuf, hwptr, sizeof(hwdetail));
				hwptr1 = (struct hwaddr *)sendbuf;

				//memcpy( sendbuf,cacheptr -> mac, 8 );
				//Sendto(confd, sendbuf, 512, 0, (struct sockaddr*)&cliaddr, len);
				flag =0;	
			
				writen(confd,sendbuf,sizeof(struct hwaddr));
				}

		}
	}/* end of  while */
}/* end of main*/
Esempio n. 14
0
static int
print_struct(smbios_hdl_t *shp, const smbios_struct_t *sp, void *fp)
{
	smbios_info_t info;
	int hex = opt_x;
	const char *s;

	if (opt_t != -1 && opt_t != sp->smbstr_type)
		return (0); /* skip struct if type doesn't match -t */

	if (!opt_O && (sp->smbstr_type == SMB_TYPE_MEMCTL ||
	    sp->smbstr_type == SMB_TYPE_MEMMOD))
		return (0); /* skip struct if type is obsolete */

	if (g_hdr++ == 0 || !opt_s)
		oprintf(fp, "%-5s %-4s %s\n", "ID", "SIZE", "TYPE");

	oprintf(fp, "%-5u %-4lu",
	    (uint_t)sp->smbstr_id, (ulong_t)sp->smbstr_size);

	if ((s = smbios_type_name(sp->smbstr_type)) != NULL)
		oprintf(fp, " %s (type %u)", s, sp->smbstr_type);
	else if (sp->smbstr_type > SMB_TYPE_OEM_LO &&
	    sp->smbstr_type < SMB_TYPE_OEM_HI)
		oprintf(fp, " %s+%u (type %u)", "SMB_TYPE_OEM_LO",
		    sp->smbstr_type - SMB_TYPE_OEM_LO, sp->smbstr_type);
	else
		oprintf(fp, " %u", sp->smbstr_type);

	if ((s = smbios_type_desc(sp->smbstr_type)) != NULL)
		oprintf(fp, " (%s)\n", s);
	else
		oprintf(fp, "\n");

	if (opt_s)
		return (0); /* only print header line if -s specified */

	if (smbios_info_common(shp, sp->smbstr_id, &info) == 0) {
		oprintf(fp, "\n");
		print_common(&info, fp);
	}

	switch (sp->smbstr_type) {
	case SMB_TYPE_BIOS:
		oprintf(fp, "\n");
		print_bios(shp, fp);
		break;
	case SMB_TYPE_SYSTEM:
		oprintf(fp, "\n");
		print_system(shp, fp);
		break;
	case SMB_TYPE_BASEBOARD:
		oprintf(fp, "\n");
		print_bboard(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_CHASSIS:
		oprintf(fp, "\n");
		print_chassis(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_PROCESSOR:
		oprintf(fp, "\n");
		print_processor(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_CACHE:
		oprintf(fp, "\n");
		print_cache(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_PORT:
		oprintf(fp, "\n");
		print_port(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_SLOT:
		oprintf(fp, "\n");
		print_slot(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_OBDEVS:
		oprintf(fp, "\n");
		print_obdevs(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_OEMSTR:
	case SMB_TYPE_SYSCONFSTR:
		oprintf(fp, "\n");
		print_strtab(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_LANG:
		oprintf(fp, "\n");
		print_lang(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_EVENTLOG:
		oprintf(fp, "\n");
		print_evlog(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_MEMARRAY:
		oprintf(fp, "\n");
		print_memarray(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_MEMDEVICE:
		oprintf(fp, "\n");
		print_memdevice(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_MEMARRAYMAP:
		oprintf(fp, "\n");
		print_memarrmap(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_MEMDEVICEMAP:
		oprintf(fp, "\n");
		print_memdevmap(shp, sp->smbstr_id, fp);
		break;
	case SMB_TYPE_SECURITY:
		oprintf(fp, "\n");
		print_hwsec(shp, fp);
		break;
	case SMB_TYPE_BOOT:
		oprintf(fp, "\n");
		print_boot(shp, fp);
		break;
	case SMB_TYPE_IPMIDEV:
		oprintf(fp, "\n");
		print_ipmi(shp, fp);
		break;
	case SMB_TYPE_OBDEVEXT:
		oprintf(fp, "\n");
		print_obdevs_ext(shp, sp->smbstr_id, fp);
		break;
	case SUN_OEM_EXT_PROCESSOR:
		oprintf(fp, "\n");
		print_extprocessor(shp, sp->smbstr_id, fp);
		break;
	case SUN_OEM_EXT_PORT:
		oprintf(fp, "\n");
		print_extport(shp, sp->smbstr_id, fp);
		break;
	case SUN_OEM_PCIEXRC:
		oprintf(fp, "\n");
		print_pciexrc(shp, sp->smbstr_id, fp);
		break;
	case SUN_OEM_EXT_MEMARRAY:
		oprintf(fp, "\n");
		print_extmemarray(shp, sp->smbstr_id, fp);
		break;
	case SUN_OEM_EXT_MEMDEVICE:
		oprintf(fp, "\n");
		print_extmemdevice(shp, sp->smbstr_id, fp);
		break;
	default:
		hex++;
	}

	if (hex)
		print_bytes(sp->smbstr_data, sp->smbstr_size, fp);
	else
		oprintf(fp, "\n");

	return (0);
}
Esempio n. 15
0
static int lfs_unlink(const char *path)
{
	int res;


#ifdef DEBUG
	printf("\n\n\nIn lfs_unlink. \n\n");
#endif
        CBLK meta_data_block = find_meta_data_block(meta_data_cache,path+1);

        if ( meta_data_block == NULL ) {
                meta_data_block = mdata_from_disk_to_memory(path);
                assert(meta_data_block);

#ifdef DEBUG
                printf("UNLINK : meta_data_block is not found in cache , hence allocating new\n");
#endif
        } 

	int flag=0;
	if ( meta_data_block->mdata->num_links !=0 ) {
		int i=0,j=0;
		flag = 1;
		for(i=0;i<meta_data_block->mdata->num_links;i++) {
			if(strcmp(meta_data_block->mdata->link_names[i],path+1) == 0) {
				if ( i != meta_data_block->mdata->num_links-1 ) {
					for(j=i;j<meta_data_block->mdata->num_links-1;j++ ) {
						strcpy(meta_data_block->mdata->link_names[j],meta_data_block->mdata->link_names[j+1]);
					}	
				}

			}
		}	

		meta_data_block->mdata->num_links--;
		write_metadata_to_disk(meta_data_block->mdata,MDATA_PATH);
			
			
	}
//        print_cache_block(meta_data_block);

  //      print_cache(buffer_cache);


        int i;
	if ( flag == 0) { // if no links present 

		for(i=0;i<meta_data_block->mdata->num_paths;i++) {
			unlink(meta_data_block->mdata->path[i]);


#ifdef DEBUG
			printf("Removing Chunk : %s\n", meta_data_block->mdata->path[i]);
#endif
		}

	}
	
	char metadata_file[MAX_PATH_NAME_SIZE];
	strcpy(metadata_file,MDATA_PATH);
	strcat(metadata_file,path);
	unlink(metadata_file);

	if ( flag == 0) {
		free_cache_block(meta_data_cache,meta_data_block);


#ifdef DEBUG
		printf("METADATA CACHE AFTER FREEING\n");
		print_cache(meta_data_cache);
#endif
		CBLK wbuf_data_block = find_meta_data_block(buffer_cache,path+1);
		if(wbuf_data_block != NULL) {
			free_cache_block(buffer_cache,wbuf_data_block);

#ifdef DEBUG
			printf("BUFFER CACHE AFTER FREEING\n");
			print_cache(buffer_cache);
#endif
		}
	}
	strcpy(load_path,LOAD_PATH);
	strcat(load_path,path);
	res = unlink(load_path);

/* Remove the date directory if it is empty */

	if (res == -1)
		return -errno;

	return 0;
}
Esempio n. 16
0
/* Implements message handlers for the front-end server.
 * 	Responds to messages:
 * 			echo
 * 			heartbeat
 * 			client
 * 			query
 * 			invalidate */
int read_msg(char *src, char *Instr, char *Arg1, char *Arg2)
{
	char instr[CONTENT_MAX];
	char arg1[CONTENT_MAX];
	char arg2[CONTENT_MAX];

	strcpy(instr,Instr);
	strcpy(arg1,Arg1);
	strcpy(arg2,Arg2);

	/* If we've received a heartbeat from our neighbor, reset the beat counter */
	if(heartbeat(instr))
	{
		pthread_mutex_lock(&heart);
		beat_count = 0;
		pthread_mutex_unlock(&heart);
		char h_msg[CONTENT_MAX];
		sprintf(h_msg,"%s,%d,NULL",hea,server_id);
		message_host(neighbor_addr,h_msg);
		return 0;
	}

	/* Register all clients with both front-end servers */
	if(client(instr))
	{
		// update client cache
		printf("client update: %s,%s,%s\n",instr,arg1,arg2);
		struct cache_entry *client;
		unsigned int c_id;

		inet_pton(AF_INET,arg1,&c_id);
		if( (client = found(c_id,clients))==NULL)
		{
			client = new_cache_entry(c_id,arg1);
			client->server_id = atoi(arg2);
			add_cache_entry(SORTED,client,clients);	
		}
		print_cache(clients);

	}

	/* When we receive a query from a client, first check to see if we
 * have the result cached locally. If not, store the request and
 * query the database. The request will be serviced once the database
 * has responded */
	if(query(instr))
	{
		
		printf("Servicing client [%s] request for [%s:%s]\n",
			src,arg1,arg2);
		// first check and see if we have the query in our local cache
		struct cache_entry *result;
		int q_id = create_cache_id(arg1,arg2,NULL);
		//printf("new q_id: %d\n",q_id);
		result = found(q_id,cache);

		// if we don't have it, request entry from database
		if(result == NULL)
		{
			printf("Entry not found. Checking Database [%s]\n",database_addr);
			char request[CONTENT_MAX];
			sprintf(request,"%s,%s,%s",que,arg1,arg2);
			message_host(database_addr,request);
		}
		else
		{
			// we can respond right away!
			printf("FOUND! Returning result to client...\n");
			char msg[CONTENT_MAX];
			sprintf(msg,"%s,%s,%s",arg1,arg2,result->value);
			message_host(src,msg);
			return 0;
		}
		// add client to service queue - will be handled when we get db response
		//printf("add client to service queue.\n");
		add_cache_entry(SORTED,new_cache_entry(q_id,src),pending_queries);	
		return 0;
	}

	/* If the database is pushing updates, the front-end server will replace
 * outdated entries when told to */
	if(invalidate(instr))
	{
		printf("Replacing old entry for [%s:%s]\n",arg1,arg2);
		int q_id = create_cache_id(instr,arg1,arg2);
		invalidate_cache(q_id,cache);
		//printf("Invalidate entry [%d] => \n",q_id);
		//print_cache(cache);
		char message[CONTENT_MAX];
		sprintf(message,"%s,%s,%s",que,arg1,arg2);
		message_host(src,message);
		return 0;
	}
	
	/* Used to register new clients when they boot up */
	if(echo(instr))
	{
		// update client cache
		printf("register new client: %s,%s\n",instr,arg1);
		struct cache_entry *client;
		unsigned int c_id;

		inet_pton(AF_INET,arg1,&c_id);
		if( (client = found(c_id,clients))==NULL)
		{
			client = new_cache_entry(c_id,arg1);
			client->server_id = server_id;
			add_cache_entry(SORTED,client,clients);	
		}
		print_cache(clients);

		// notify other Frontend server
		printf("Notifying neighbor: %s\n",neighbor_addr);
		char c_msg[CONTENT_MAX];
		sprintf(c_msg,"%s,%s,%d",cli,src,server_id);
		message_host(neighbor_addr,c_msg);

		return 0;
	}
	
	// query response
	int q_id = create_cache_id(instr,arg1,arg2);
	struct cache_entry *f;
	if( (f=found(q_id,cache))==NULL)
		add_cache_entry(SORTED,new_cache_entry(q_id,arg2),cache);	
	else if( (f!=NULL) && strcmp(f->value,arg2) != 0)
	{
		// if we have an update, replace the old entry
		printf("Replacing old entry for [%s:%s]\n",arg1,arg2);
		delete_entry(f,cache);
		add_cache_entry(SORTED,new_cache_entry(q_id,arg2),cache);	
	}

	//print_cache(cache);
	// if we have a client waiting for this query, respond
	struct cache_entry *pending_client;
	//print_cache(pending_queries);
	while( (pending_client = found(q_id,pending_queries)) != NULL)
	{
		printf("Database returned entry [%s:%s]. Responding to client [%s]\n",
			arg1,arg2,pending_client->value);
		//printf("next client->%s\n",pending_client->value);
		char msg[CONTENT_MAX];
		sprintf(msg,"%s,%s,%s",instr,arg1,arg2);
		message_host(pending_client->value,msg);
		delete_entry(pending_client,pending_queries);	
	}

	return 0;
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
	struct cmdline_options	opts = {
		.cache_file	=  CACHE_FILE,
		.base_oid	=  BASE_OID,
		.conf_file	=  CONF_FILE,
		.cache_prog	=  CACHE_REGEN_PROG,
	};

	bool				is_ok;
	int				cache_fd;
	struct cache_entry		*cache_entries;
	size_t				num_cache_entries;
	int				rc;
	unsigned int			attr_idx = SNMPD_IDX_UNKNOWN;
	size_t				req_cache_idx;
	struct oid_info const		*sub_oid;
	size_t				base_oid_len;

	while (1) {
		int		c = getopt_long(argc, argv, "gns", CMDLINE_OPTIONS, 0);
		if (c==-1) break;

		switch (c) {
		case CMD_HELP:		show_help();
		case CMD_VERSION:	show_version();
		case CMD_BASE_OID:	opts.base_oid = optarg; break;
		case CMD_CACHE:		opts.cache_file = optarg; break;
		case CMD_CACHE_PROGRAM:	opts.cache_prog = optarg; break;
		case CMD_CONF:		opts.conf_file = optarg; break;
		case 'g':		opts.op_get = 1; break;
		case 's':		opts.op_set = 1; break;
		case 'n':		opts.op_get_next = 1; break;
		default:
			fputs("Try '--help' for more information.\n", stderr);
			exit(EX_USAGE);
		}
	}

	is_ok = false;
	base_oid_len = strlen(opts.base_oid);

	if (opts.op_get + opts.op_set + opts.op_get_next > 1)
		fputs("more than one operation specified\n", stderr);
	else if (opts.op_get + opts.op_set + opts.op_get_next == 0)
		fputs("no operation specified\n", stderr);
	else if (optind + 1 != argc)
		fputs("no/too much OID specified\n", stderr);
	else if (strncmp(opts.base_oid, argv[optind], base_oid_len) &&
		 argv[optind][base_oid_len] != '\0' &&
		 argv[optind][base_oid_len] != '.')
		fputs("unsupported OID\n", stderr);
	else if (!parse_oid(&argv[optind][base_oid_len], &sub_oid, &attr_idx))
		;			/* noop */
	else if ((opts.op_get || opts.op_set) &&
		 (sub_oid == NULL || attr_idx == SNMPD_IDX_UNKNOWN ||
		  (sub_oid->num_suboid && attr_idx >= sub_oid->num_suboid))) {
		fprintf(stderr, "sub_oid=%p, idx=%u\n", sub_oid, attr_idx);
		fputs("unknown OID\n", stderr);
		return EX_UNAVAILABLE;
	} else
		is_ok = true;

	if (!is_ok)
		exit(EX_USAGE);

	if (opts.op_set) {
		puts("not-writable");
		return EXIT_SUCCESS;
	}

	if (opts.op_get_next && sub_oid == NULL) {
		sub_oid = &SUB_OIDS[0];
		assert(attr_idx == SNMPD_IDX_UNKNOWN);
	}

	assert(sub_oid != NULL);

	cache_fd = open_cache_file(opts.conf_file, opts.cache_file, opts.cache_prog);
	if (cache_fd < 0)
		exit(-cache_fd);

	rc = read_cache_file(cache_fd, &cache_entries, &num_cache_entries);
	if (rc < 0)
		exit(-rc);

	close(cache_fd);

	if (sub_oid->num_suboid == 0) {
		size_t				i;

		if (attr_idx == SNMPD_IDX_UNKNOWN && opts.op_get_next)
			req_cache_idx = 0;
		else
			req_cache_idx = num_cache_entries;

		for (i = 0; i < num_cache_entries; ++i) {
			if (cache_entries[i].idx != attr_idx)
				continue;

			req_cache_idx = i;
			if (opts.op_get_next) {
				++req_cache_idx;

				if (req_cache_idx >= num_cache_entries) {
					req_cache_idx = 0;
					++sub_oid;
				}
			}

			break;
		}
	} else if (opts.op_get_next) {
		if (attr_idx == SNMPD_IDX_UNKNOWN)
			req_cache_idx = 0;
		else if (attr_idx + 1 != sub_oid->num_suboid)
			req_cache_idx = attr_idx;
		else {
			req_cache_idx = 0;
			++sub_oid;
		}
	} else
		req_cache_idx = attr_idx;

	assert(sub_oid->num_suboid == 0 || req_cache_idx < sub_oid->num_suboid);

	if (sub_oid->idx == SNMPD_OID_METADATA) {
		print_metadata(opts.base_oid, sub_oid, req_cache_idx,
			       num_cache_entries);
	} else if (req_cache_idx < num_cache_entries && sub_oid->oid != 0) {
		rc = read_sysfs_cache(&cache_entries[req_cache_idx]);
		if (rc < 0)
			exit(-rc);

		print_cache(&cache_entries[req_cache_idx],
			    opts.base_oid, sub_oid);
	}


	free(cache_entries);
}
Esempio n. 18
0
int rl_read(rlite *db, rl_data_type *type, long page, void *context, void **obj, int cache)
{
	// fprintf(stderr, "r %ld %s\n", page, type->name);
#ifdef RL_DEBUG
	int keep = 0;
	long initial_page_size = db->page_size;
	if (page == 0 && type != &rl_data_type_header) {
		VALGRIND_PRINTF_BACKTRACE("Unexpected");
		return RL_UNEXPECTED;
	}
#endif
	unsigned char *data = NULL;
	int retval;
	unsigned char *serialize_data;
	retval = rl_read_from_cache(db, type, page, context, obj);
	if (retval != RL_NOT_FOUND) {
		if (!cache) {
			RL_MALLOC(serialize_data, db->page_size * sizeof(unsigned char));
			retval = type->serialize(db, *obj, serialize_data);
			if (retval != RL_OK) {
				rl_free(serialize_data);
				return retval;
			}
			retval = type->deserialize(db, obj, context, serialize_data);
			rl_free(serialize_data);
			if (retval != RL_OK) {
				return retval;
			}
			retval = RL_FOUND;
		}
		return retval;
	}
	RL_MALLOC(data, db->page_size * sizeof(unsigned char));
	if (db->driver_type == RL_FILE_DRIVER) {
		rl_file_driver *driver = db->driver;
		RL_CALL(file_driver_fp, RL_OK, db);
		fseek(driver->fp, page * db->page_size, SEEK_SET);
		size_t read = fread(data, sizeof(unsigned char), db->page_size, driver->fp);
		if (read != (size_t)db->page_size) {
			if (page > 0) {
#ifdef RL_DEBUG
				print_cache(db);
#endif
				fprintf(stderr, "Unable to read page %ld on line %d\n", page, __LINE__);
				perror(NULL);
			}
			retval = RL_NOT_FOUND;
			goto cleanup;
		}
	}
	else if (db->driver_type == RL_MEMORY_DRIVER) {
		rl_memory_driver *driver = db->driver;
		if ((page + 1) * db->page_size > driver->datalen) {
			fprintf(stderr, "Unable to read page %ld on line %d\n", page, __LINE__);
			retval = RL_NOT_FOUND;
			goto cleanup;
		}
		memcpy(data, &driver->data[page * db->page_size], sizeof(unsigned char) * db->page_size);
	}
	else {
		fprintf(stderr, "Unexpected driver %d when asking for page %ld\n", db->driver_type, page);
		retval = RL_UNEXPECTED;
		goto cleanup;
	}

	long pos;
	retval = rl_search_cache(db, type, page, NULL, &pos, context, db->read_pages, db->read_pages_len);
	if (retval != RL_NOT_FOUND) {
		fprintf(stderr, "Unexpectedly found page in cache\n");
		retval = RL_UNEXPECTED;
		goto cleanup;
	}

	retval = type->deserialize(db, obj, context ? context : type, data);
	if (retval != RL_OK) {
		goto cleanup;
	}

	if (cache) {
		rl_ensure_pages(db);
		rl_page *page_obj;
		page_obj = rl_malloc(sizeof(*page_obj));
		if (!page_obj) {
			if (obj) {
				if (type->destroy && *obj) {
					type->destroy(db, *obj);
				}
				*obj = NULL;
			}
			retval = RL_OUT_OF_MEMORY;
			goto cleanup;
		}
		page_obj->page_number = page;
		page_obj->type = type;
		page_obj->obj = obj ? *obj : NULL;
#ifdef RL_DEBUG
		keep = 1;
		if (initial_page_size != db->page_size) {
			page_obj->serialized_data = rl_realloc(data, db->page_size * sizeof(unsigned char));
			if (page_obj->serialized_data == NULL) {
				rl_free(page_obj);
				retval = RL_OUT_OF_MEMORY;
				goto cleanup;
			}
			data = page_obj->serialized_data;
			if (db->page_size > initial_page_size) {
				memset(&data[initial_page_size], 0, db->page_size - initial_page_size);
			}
		}
		else {
			page_obj->serialized_data = data;
		}

		serialize_data = calloc(db->page_size, sizeof(unsigned char));
		if (!serialize_data) {
			rl_free(page_obj->serialized_data);
			rl_free(page_obj);
		}
		retval = type->serialize(db, obj ? *obj : NULL, serialize_data);
		if (retval != RL_OK) {
			goto cleanup;
		}
		if (memcmp(data, serialize_data, db->page_size) != 0) {
			fprintf(stderr, "serialize unserialized data mismatch\n");
			long i;
			for (i = 0; i < db->page_size; i++) {
				if (serialize_data[i] != data[i]) {
					fprintf(stderr, "at position %ld expected %d, got %d\n", i, serialize_data[i], data[i]);
				}
			}
		}
		rl_free(serialize_data);
#endif
		if (pos < db->read_pages_len) {
			memmove(&db->read_pages[pos + 1], &db->read_pages[pos], sizeof(rl_page *) * (db->read_pages_len - pos));
		}
		db->read_pages[pos] = page_obj;
		db->read_pages_len++;
	}
	if (retval == RL_OK) {
		retval = RL_FOUND;
	}
cleanup:
#ifdef RL_DEBUG
	if (retval != RL_FOUND || !keep) {
		rl_free(data);
	}
#endif
#ifndef RL_DEBUG
	rl_free(data);
#endif
	return retval;
}
Esempio n. 19
0
static int rl_search_cache(rlite *db, rl_data_type *type, long page_number, void **obj, long *position, void *context, rl_page **pages, long page_len)
#endif
{
	long pos, min = 0, max = page_len - 1;
	rl_page *page;
	if (max >= 0) {
		do {
			pos = min + (max - min) / 2;
			page = pages[pos];
			if (page->page_number == page_number) {
				if (obj) {
					if (page->type == NULL) {
						// This happens when we are in read-only mode, and have a wal file
						unsigned char *serialize_data = page->obj;
						int retval = type->deserialize(db, &page->obj, context, serialize_data);
						if (retval != RL_OK) {
							return retval;
						}
						page->type = type;
						rl_free(serialize_data);
					}
					*obj = page->obj;
#ifdef RL_DEBUG
				if (page->type != &rl_data_type_long && type != &rl_data_type_long && type != NULL && page->type != type) {
					fprintf(stderr, "Type of page in cache (%s) doesn't match the asked one (%s)\n", page->type->name, type->name);
					return RL_UNEXPECTED;
				}
#endif
				}
				if (position) {
					*position = pos;
				}
				return RL_FOUND;
			}
			else if (page->page_number > page_number) {
				max = pos - 1;
			}
			else {
				min = pos + 1;
			}
		}
		while (max >= min);
		if (position) {
			if (pages[pos]->page_number > page_number && pos > 0) {
				pos--;
			}
			if (pages[pos]->page_number < page_number && pos < page_len) {
				pos++;
			}
#ifdef RL_DEBUG
			long i, prev;
			rl_page *p;
			for (i = 0; i < db->read_pages_len; i++) {
				p = db->read_pages[i];
				if (i > 0) {
					if (prev >= p->page_number) {
						fprintf(stderr, "Reading cache is broken\n");
						print_cache(db);
						return RL_UNEXPECTED;
					}
				}
				prev = p->page_number;
			}
			for (i = 0; i < db->write_pages_len; i++) {
				p = db->write_pages[i];
				if (i > 0) {
					if (prev >= p->page_number) {
						fprintf(stderr, "Writing cache is broken\n");
						print_cache(db);
						return RL_UNEXPECTED;
					}
				}
				prev = p->page_number;
			}
#endif
			*position = pos;
		}
	}
	else {
		if (position) {
			*position = 0;
		}
	}
	return RL_NOT_FOUND;
}
Esempio n. 20
0
long long scan_cache (void)
{
    long long total_size = 0;

    // remove old LL
    disk_item * d = cache_head;
    while ( d != NULL ) {
        disk_item * prev_d = d;
        d = d->next;
        prev_d->next = NULL;
        prev_d->prev = NULL;
        free_disk_item (prev_d);
    }
    cache_head = NULL;

    logprintfl (EUCAINFO, "scanning the cache directory (%s)\n", cache_path);

    if (strlen(cache_path) == 0) {
        logprintfl (EUCAINFO, "no cache directory yet\n");
        return total_size;
    }

    struct stat mystat;
    if (stat (cache_path, &mystat) < 0) {
        logprintfl (EUCAWARN, "warning: could not stat %s\n", cache_path);
        return -1L;
    }
    total_size += mystat.st_size;

    DIR * cache_dir;
    if ((cache_dir=opendir(cache_path))==NULL) {
        logprintfl (EUCAFATAL, "errror: could not open cache directory %s\n", cache_path);
        return -1L;
    }

    // iterate over all directories in cache directory
    struct dirent * cache_dir_entry;
    while ((cache_dir_entry=readdir(cache_dir))!=NULL) {
        char * image_name = cache_dir_entry->d_name;
        char image_path [EUCA_MAX_PATH];
        long long image_size = 0;
        long long content_size = 0;
        int image_files = 0;


        if (!strcmp(".", image_name) ||
            !strcmp("..", image_name))
            continue;

        DIR * image_dir;
        snprintf (image_path, EUCA_MAX_PATH, "%s/%s", cache_path, image_name);
        if ((image_dir=opendir(image_path))==NULL) {
            logprintfl (EUCAWARN, "warning: unopeneable directory %s\n", image_path);
            continue;
        }

        if (stat (image_path, &mystat) < 0) {
            logprintfl (EUCAWARN, "warning: could not stat %s\n", image_path);
            closedir(image_dir);
            continue;
        }
        image_size += mystat.st_size;

        // add up sizes of all files in a directory
        struct dirent * image_dir_entry;
        boolean found_content = FALSE;
        boolean found_summary = FALSE;
        while ((image_dir_entry=readdir(image_dir))!=NULL) {
            char name [EUCA_MAX_PATH];
            strncpy (name, image_dir_entry->d_name, EUCA_MAX_PATH);

            if (!strcmp(".", name) ||
                !strcmp("..", name))
                continue;

            image_files++;

            char filepath [EUCA_MAX_PATH];
            snprintf (filepath, EUCA_MAX_PATH, "%s/%s", image_path, name);
            if (stat (filepath, &mystat) < 0 ) {
                logprintfl (EUCAERROR, "error: could not stat file %s\n", filepath);
                break;
            }
            if (mystat.st_size < 1) {
                logprintfl (EUCAERROR, "error: empty file among cached images in '%s'\n", filepath);
                break;
            }

            if (!strcmp ("content", name)) {
                content_size = mystat.st_size;
                found_content = TRUE;
            }
            if (!strcmp ("summary", name))
                found_summary = TRUE;

            image_size += mystat.st_size;
        }
        closedir(image_dir);

        // report on what was found in each cache directory
        if (image_files > 0) { // ignore empty directories
            if (image_size>0) {
                logprintfl (EUCAINFO, "- cached image '%s': size=%dMB, files=%d\n", image_name, image_size/MEGABYTE, image_files);
                total_size += image_size;

                //              if (!found_content || !found_summary)
                //                  logprintfl (EUCAINFO, "(warning: incomplete cache entry for image '%s')\n", image_name); // TODO: do this if cache entry is not locked

                // allocate a disk item object
                disk_item * di = alloc_disk_item (image_name, content_size, image_size, TRUE);
                add_to_cache (di);
            } else {
                logprintfl (EUCAWARN, "warning: empty cached image directory %s\n", image_path);
            }
        }
    }
    closedir (cache_dir);

    print_cache ();

    return total_size;
}
Esempio n. 21
0
static int lfs_getattr(const char *path, struct stat *stbuf)
{
	int res;
	char final_path[MAX_PATH_NAME_SIZE];

	strcpy(final_path,MDATA_PATH);
	strcat(final_path,path);
	res = lstat(final_path, stbuf);

	if(S_IFDIR == (stbuf->st_mode & S_IFDIR))
	{
#ifdef DEBUG
		printf("Inside directory \n");
#endif	
		return 0;
	}

	if (res == -1)
		return -errno;

	if(strcmp(path,"/") == 0 )
		return 0;

	if(path[1] == '.' ) // For all special files starting with '.' just return the stbuf that is returned from lstat
		return 0;

	CBLK meta_data_block = find_meta_data_block(meta_data_cache,path+1);

	if ( meta_data_block == NULL ) {
		meta_data_block = mdata_from_disk_to_memory(path);
		assert(meta_data_block);
#ifdef DEBUG
                printf("GETATTR : meta_data_block is not found in cache , hence allocating new\n");
#endif
	} else {
		update_lru(meta_data_cache,meta_data_block);
	}
//        print_cache_block(meta_data_block);

#ifdef DEBUG
	print_cache(meta_data_cache);
#endif
//	print_cache(buffer_cache);
	CBLK wbuf_data_block = find_meta_data_block(buffer_cache,path+1);

        if( wbuf_data_block == NULL )
        {
		stbuf->st_size = meta_data_block->mdata->size;
        } else {
	
		update_lru(buffer_cache,wbuf_data_block);	
#ifdef DEBUG
                printf("GETATTR: wbuf_data_block already found in cache\n");
		print_cache_block(wbuf_data_block);
#endif
		stbuf->st_size = meta_data_block->mdata->size + wbuf_data_block->offset;
        }

	// stbuf->st_size += meta_data_block->mdata->num_paths; needed only if \n has to be appended manually after each chunk
#ifdef DEBUG
	printf("ST_BUF_SIZE : %d\n",stbuf->st_size); 
#endif
	return 0;
}