示例#1
0
文件: adns.c 项目: Estella/wraith
void dns_send_query(dns_query_t *q)
{
  char buf[512] = "";
  int len;

  if (!q->ip) {
    /* Send the ipv4 query. */
    q->remaining = 1;
    len = make_header(buf, q->id);
    len += cut_host(q->query, buf + len);
    buf[len] = 0; len++; buf[len] = DNS_A; len++;
    buf[len] = 0; len++; buf[len] = 1; len++;

    egg_dns_send(buf, len);

#ifdef USE_IPV6
    /* Now send the ipv6 query. */
    q->remaining++;
    len = make_header(buf, q->id);
    len += cut_host(q->query, buf + len);
    buf[len] = 0; len++; buf[len] = DNS_AAAA; len++;
    buf[len] = 0; len++; buf[len] = 1; len++;

    egg_dns_send(buf, len);
#endif
  } else if (q->ip) {
    q->remaining = 1;
    len = make_header(buf, q->id);
    len += cut_host(q->ip, buf + len);
    buf[len] = 0; len++; buf[len] = DNS_PTR; len++;
    buf[len] = 0; len++; buf[len] = 1; len++;

    egg_dns_send(buf, len);
  }
}
示例#2
0
grub_err_t
grub_initrd_load (struct grub_linux_initrd_context *initrd_ctx,
		  char *argv[], void *target)
{
  grub_uint8_t *ptr = target;
  int i;
  int newc = 0;
  struct dir *root = 0;
  grub_ssize_t cursize = 0;

  for (i = 0; i < initrd_ctx->nfiles; i++)
    {
      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
      ptr += ALIGN_UP_OVERHEAD (cursize, 4);

      if (initrd_ctx->components[i].newc_name)
	{
	  ptr += insert_dir (initrd_ctx->components[i].newc_name,
			     &root, ptr);
	  ptr = make_header (ptr, initrd_ctx->components[i].newc_name,
			     grub_strlen (initrd_ctx->components[i].newc_name),
			     0100777,
			     initrd_ctx->components[i].size);
	  newc = 1;
	}
      else if (newc)
	{
	  ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1,
			     0, 0);
	  free_dir (root);
	  root = 0;
	  newc = 0;
	}

      cursize = initrd_ctx->components[i].size;
      if (grub_file_read (initrd_ctx->components[i].file, ptr, cursize)
	  != cursize)
	{
	  if (!grub_errno)
	    grub_error (GRUB_ERR_FILE_READ_ERROR, N_("premature end of file %s"),
			argv[i]);
	  grub_initrd_close (initrd_ctx);
	  return grub_errno;
	}
      ptr += cursize;
    }
  if (newc)
    ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1, 0, 0);
  free_dir (root);
  root = 0;
  return GRUB_ERR_NONE;
}
示例#3
0
//send the static file to client
int serv_static(int cli_fd,char* filename)
{
    const char* file_type;
    char* dot_pos = rindex(filename,'.');
    file_type = get_filetype(dot_pos);


    //open the file,construct the head,send
    FILE* ind = fopen(filename,"r");
    if(ind == NULL)
    {
        //debug_info
        printf("cannot open the file");
        //404 not found
        not_found(cli_fd);
        return -1;
    }
    else
    {
        //construct the http response header
        make_header(cli_fd,filename);
        //than send the file
        char buff[1024];
        memset(buff,0,sizeof(buff));
        while(!feof(ind))
        {
            fgets(buff,sizeof(buff),ind);
            send(cli_fd,buff,strlen(buff),0);
        }

    }
    return 0;
}
示例#4
0
value_t wrap_string(const std::string& str) {
    double_storage_t* storage = alloc_double_storage();
    storage->header = make_header(true, STRING_TYPE_MASK, MARK_POLICY_NONE);
    storage->first_slot = (uint64_t) new std::string(str);

    return wrap_pointer(storage);
}
示例#5
0
文件: main.c 项目: gmpetrov/ft_select
int		main(int ac, char **av)
{
	struct termios	term;
	t_data			d;
	t_list			*list;

	if (ac <= 1)
		return (0);
	list = NULL;
	d.max_row = --ac;
	d.pos_init = d.max_row;
	d.pos = d.pos_init;
	list = ft_make_list(av, &d);
	if (ft_set_stage(ac, &term))
	ft_get_size(&d);
	make_header(&d);
	get_col_nb(&d);
	ft_signals();
	print_multi_tab(list, &d);
	tputs(tgetstr("vi", NULL), 1, tputs_putchar);
	d.us = 1;
	ft_while(&d, &term, list);
	tputs(tgetstr("ve", NULL), 1, tputs_putchar);
	return (0);
}
示例#6
0
文件: cal.c 项目: makotosiraisi/kadai
main(){
    int cal[CAL_V][CAL_H];
    char header[HEADER_LEN];
    int i, j;
    int year, month;
    time_t tt_now;
    struct tm st_now;

    tt_now = time(NULL);
    st_now = *localtime(&tt_now);
    month = st_now.tm_mon + 1;
    year = st_now.tm_year + 1900;


    make_header(month, year, header);
    printf("%s\n", header);
    printf("Su Mo Tu We Th Fr Sa\n");

    make_cal(month, year, cal);

    for(i=0;i<CAL_V;i++){
        for(j=0;j<CAL_H;j++){
            if(cal[i][j] != 0){
                printf("%2d ", cal[i][j]);
            }else{
                printf("   ");
            }
        }
        printf("\n");
    }
}
示例#7
0
/**
 * Builds and returns the next packet info, or NULL
 * if no more data is available.
 * max on data_len is 254, size of header is 8
 */
packet_info *get_next_packet_info(int sequence) {
  char *data = malloc(DATA_SIZE);
  int data_len = get_next_data(data, DATA_SIZE);

  if (data_len == 0) {
    free(data);
    return NULL;
  }

  header *myheader = make_header(sequence, data_len, 0, 0);
  void *packet = malloc(sizeof(header) + data_len);
  memcpy(packet, myheader, sizeof(header));
  memcpy(((char *) packet) +sizeof(header), data, data_len);

  free(data);
  free(myheader);

  packet_info *info = (packet_info *) malloc(sizeof(packet_info));
  info->packet    = packet;
  info->retrieved = time(0);
  info->data_len  = data_len;
  info->sequence  = sequence;

  return info;
}
示例#8
0
文件: heap.c 项目: orodley/studix
Heap *create_heap(uintptr_t start, uintptr_t end, uintptr_t max,
		bool supervisor, bool readonly)
{
	Heap *heap  = (Heap*)kmalloc(sizeof(Heap));

	// Make sure start and end are page-aligned
	ASSERT(aligned(start));
	ASSERT(aligned(end));

	heap->index = place_ordered_array((void*)start, HEAP_INDEX_SIZE,
			header_comparer);
	start      += sizeof(void*) * HEAP_INDEX_SIZE;

	align_up(start);

	heap->start_addr = start;
	heap->end_addr   = end;
	heap->max_addr   = max;
	heap->supervisor = supervisor;
	heap->readonly   = readonly;

	// At the start, the whole thing is a hole
	Header *hole = make_header(start, end - start, true);
	ordered_array_insert(&heap->index, (void*)hole);

	return heap;
}
示例#9
0
/*!
 * \brief Envia header pro cliente conectado.
 * \param[in] socket_id Descritor do socket da conexao.
 * \param[in] head Ponteiro para o primeiro item da lista de requisicoes.
 * \return Retorna 0 caso tenha recebido o fim da requisicao ou -1 caso nao.
 */
static int send_header_to_client(struct request_file **r, long speed_limit)
{
  const int bufin_size = calc_buf_size(speed_limit);
  int send_size = 0, nbytes = 0;
  struct request_file *request = *r;

  if (request->header == NULL)
    request->header = make_header(request);

  if ((unsigned)request->header_size_sended >= strlen(request->header))
    return SUCCESS;

  send_size = strlen(request->header) - request->header_size_sended;

  send_size = (send_size > bufin_size) ? bufin_size : send_size;

  if (check_speed_limit(request, speed_limit))
    return ERROR;

  nbytes = send(request->socket_id,
                request->header + request->header_size_sended,
                send_size,
                MSG_NOSIGNAL);

  if (nbytes > 0)
    request->header_size_sended += nbytes;

  return SUCCESS;
}
示例#10
0
void	is_spc_2(t_list *list, t_data *d)
{
	tputs(tgetstr("do", NULL), 1, tputs_putchar);
	d->pos += 1;
	tputs(tgetstr("cl", NULL), 1, tputs_putchar);
	make_header(d);
	print_multi_tab(list, d);
}
示例#11
0
void	is_spc_1(t_list *list, t_data *d)
{
	tputs(tgoto(tgetstr("cm", NULL), 0, 0), 1, tputs_putchar);
	d->pos = (d->pos + 1) - d->pos_init;
	tputs(tgetstr("cl", NULL), 1, tputs_putchar);
	make_header(d);
	print_multi_tab(list, d);
}
示例#12
0
void send_final_packet(int sock, struct sockaddr_in out) {
  header *myheader = make_header(sequence+1, 0, 1, 0);
  mylog("[send eof]\n");

  if (sendto(sock, myheader, sizeof(header), 0, (struct sockaddr *) &out, (socklen_t) sizeof(out)) < 0) {
    mylog("final packet errored out!\n");
    perror("sendto");
    exit(1);
  }
}
示例#13
0
 void gen()
 {
     timespec sleep_timer_;
     while(running_)
     {
         pool_.addHeader(make_header());
         get_sleep_time(&sleep_timer_);
         nanosleep(&sleep_timer_,NULL);
     }
 }
示例#14
0
std::vector<char> response_serializer::operator()(const http::response &response) noexcept {
    auto header = make_header(response);
    auto body = make_body(response);
    auto ending = make_ending(response);

    std::vector<char> buffer;
    buffer.reserve(getpagesize());
    buffer.insert(buffer.end(), std::make_move_iterator(header.begin()), std::make_move_iterator(header.end()));
    buffer.insert(buffer.end(), std::make_move_iterator(body.begin()), std::make_move_iterator(body.end()));
    buffer.insert(buffer.end(), std::make_move_iterator(ending.begin()), std::make_move_iterator(ending.end()));
    return buffer;
}
示例#15
0
void draw_box(HDC _hDC, const RECT& _rBox, int _EdgeRoundness, float _Alpha)
{
	if (equal(_Alpha, 1.0f))
	{
		if (_EdgeRoundness)
			oVB(RoundRect(_hDC, _rBox.left, _rBox.top, _rBox.right, _rBox.bottom, _EdgeRoundness, _EdgeRoundness));
		else
			oVB(Rectangle(_hDC, _rBox.left, _rBox.top, _rBox.right, _rBox.bottom));
		return;
	}

	// Copy the contents out (is there no way to access things directly?)
	BITMAPINFO bmi = {0};
	surface::info_t si;
	si.dimensions = int3(oWinRectW(_rBox), oWinRectH(_rBox), 1);
	si.format = surface::format::b8g8r8a8_unorm;

	bmi.bmiHeader = make_header(si);
	if (!bmi.bmiHeader.biWidth || !bmi.bmiHeader.biHeight)
		return;
	
	HDC hDCBitmap = CreateCompatibleDC(_hDC);
	scoped_bitmap hBmp(CreateDIBSection(hDCBitmap, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, nullptr, nullptr, 0));

	scoped_select ScopedSelectBmp(hDCBitmap, hBmp);
	scoped_select ScopedSelectPen(hDCBitmap, current_pen(_hDC));
	scoped_select ScopedSelectBrush(hDCBitmap, current_brush(_hDC));

	// Resolve areas around the curved corners so we can to the blend directly
	// later on. But just do the minimum necessary, don't copy the interior that
	// we're going to re-draw with a RECT.
	if (_EdgeRoundness)
	{
		// Minimize rects...
		int dist = _EdgeRoundness;
		RECT TL = { _rBox.left, _rBox.top, _rBox.left + dist, _rBox.top + dist };
		RECT RT = { _rBox.right - dist, _rBox.top, _rBox.right, _rBox.top + dist };
		RECT BL = { _rBox.left, _rBox.bottom - dist, _rBox.left + dist, _rBox.bottom };
		RECT BR = { _rBox.right - dist, _rBox.bottom - dist, _rBox.right, _rBox.bottom };
		BitBlt(hDCBitmap, 0, 0, dist, dist, _hDC, _rBox.left, _rBox.top, SRCCOPY);
		BitBlt(hDCBitmap, bmi.bmiHeader.biWidth - dist, 0, dist, dist, _hDC, _rBox.right - dist, _rBox.top, SRCCOPY);
		BitBlt(hDCBitmap, 0, bmi.bmiHeader.biHeight - dist, dist, dist, _hDC, _rBox.left, _rBox.bottom - dist, SRCCOPY);
		BitBlt(hDCBitmap, bmi.bmiHeader.biWidth - dist, bmi.bmiHeader.biHeight - dist, dist, dist, _hDC, _rBox.right - dist, _rBox.bottom - dist, SRCCOPY);
		oVB(RoundRect(hDCBitmap, 0, 0, bmi.bmiHeader.biWidth, bmi.bmiHeader.biHeight, _EdgeRoundness, _EdgeRoundness));
	}

	else
		oVB(Rectangle(hDCBitmap, 0, 0, bmi.bmiHeader.biWidth, bmi.bmiHeader.biHeight));

	BLENDFUNCTION blend = { AC_SRC_OVER, 0, (BYTE)(static_cast<int>(_Alpha * 255.0f) & 0xff), 0 };
	oVB(AlphaBlend(_hDC, _rBox.left, _rBox.top, bmi.bmiHeader.biWidth, bmi.bmiHeader.biHeight, hDCBitmap, 0, 0, bmi.bmiHeader.biWidth, bmi.bmiHeader.biHeight, blend));
}
示例#16
0
void connection::process()
{
	read_request();
	parse_request();
	make_body();
	make_header();
	send_header();
	if (is_get())
	{
		send_body();
	}
	m_socket.close();
}
示例#17
0
/**
* Builds and returns the next packet, or NULL
* if no more data is available.
*/
void *get_next_packet(int sequence, int *len) {
    //store sent packets in buffer
    if (wind_cache[sequence % WIND_SIZE])
    {
        void* cached_pkt = wind_cache[sequence % WIND_SIZE];
        int cached_header_seq = read_hseq(cached_pkt);
        if (cached_header_seq == sequence ) { 
            //packets are only sent from the buffer if packet loss or a timeout occured
            debug_time = SEND_TIMEOUT; 
            mylog( "[From Cache] %i\n", cached_header_seq);
            *len = sizeof(header) + read_hlength(cached_pkt);
            return cached_pkt;
        }
    }
    //increase timeout
    debug_time += SHORT_TIMEOUT; 
    char *data = malloc(DATA_SIZE);
    int data_length = get_next_data(data, DATA_SIZE);
    if (data_length == 0) {
        free(data);
        return NULL;
    }
    
    //create header for packet
    header *myheader = make_header(sequence, data_length, 0, 0);
    
    //create the packet
    void *pkt = malloc(sizeof(header) + data_length + sizeof(checksum_t));
    memcpy(pkt, myheader, sizeof(header));
    memcpy(((char *) pkt) + sizeof(header), data, data_length);
    
    //calculate the checksum for the packet and attach
    checksum_t chksm = chksum(data, data_length); 
    memcpy(((char *) pkt) + sizeof(header) + data_length, &chksm, sizeof(checksum_t)); 
    free(data);
    free(myheader);
    
    //len = packet size in bytes
    *len = sizeof(header) + data_length + sizeof(checksum_t);
    mylog("Checksum %d\n", get_chksum(pkt, data_length + sizeof(header)));
    
    
    if (wind_cache[sequence % WIND_SIZE])
    {
        free(wind_cache[sequence % WIND_SIZE]);
    }
    wind_cache[sequence % WIND_SIZE] = (void*)malloc(sizeof(header) + data_length + sizeof(checksum_t));
    memcpy(wind_cache[sequence % WIND_SIZE], pkt, sizeof(header) + data_length + sizeof(checksum_t));

    return pkt;
}
示例#18
0
文件: getvar.c 项目: krzul/dia
/*--------------------------------------------------------*/
void writevar2fits(char *fname, int nx, int ny, float *data)
{
        char  **header;
        int   hsize, i;

  hsize=make_header(&header, nx, ny);

  write_FITS_2D1file(fname, hsize, header, nx*ny, sizeof(float), data);

  for (i=0; i<hsize; i++) free(header[i]);
  free(header);
  
  return;
}
示例#19
0
/*
	 * toggle displayed fields
	 */
void change_fields(void)
{
    int i, changed = 0;
    int row, col;
    char c, *p;
    char tmp[2] = " ";

    show_fields();
    for (;;) {
	PUTP(tgoto(cm, 0, 0));
	PUTP(top_clrtoeol);
	PUTP(tgoto(cm, 3, 0));
	PUTP(mr);
	printf("Current Field Order: %s", Fields);
	PUTP(me);
	putchar('\n');
	PUTP(tgoto(cm, 0, 1));
	printf("Toggle fields with a-x, any other key to return: ");
	fflush(stdout);
	if (!Batch) { /* should always be true, but... */
	    tcsetattr(0, TCSAFLUSH, &Rawtty);
	    read(0, &c, 1);
	    tcsetattr(0, TCSAFLUSH, &Savetty);
	}
	i = toupper(c) - 'A';
	if (i >= 0 && i < sizeof headers / sizeof headers[0]) {
	    row = i % (Lines - 3) + 3;
	    col = i / (Lines - 3) * 40;
	    PUTP(tgoto(cm, col, row));
	    if ((p = strchr(Fields, i + 'A')) != NULL) {	/* deselect Field */
		*p = i + 'a';
		putchar(' ');
	    } else if ((p = strchr(Fields, i + 'a')) != NULL) {		/* select previously */
		*p = i + 'A';	/* deselected field */
		putchar('*');
	    } else {		/* select new field */
		tmp[0] = i + 'A';
		strcat(Fields, tmp);
		putchar('*');
	    }
	    changed = 1;
	    fflush(stdout);
	} else
	    break;
    }
    if (changed)
	Numfields = make_header();
}
示例#20
0
int main(int argc, char *argv[])
{
       	TGA *in, *out;
	TGAData *data;
	int encode;

	if(argc < 3) {
		printf("Not enough arguments supplied!\n");
		return 0;
	}
	
	data = (TGAData*)malloc(sizeof(TGAData));
	if(!data) {
		TGA_ERROR((TGA*)NULL, TGA_OOM);
		return 0;
	}

        in = TGAOpen(argv[1], "r");
	printf("[open] name=%s, mode=%s\n", argv[1], "r");

	out = TGAOpen(argv[2], "w");
        printf("[open] name=%s, mode=%s\n", argv[2], "w");
	

	data->flags = TGA_IMAGE_ID | TGA_IMAGE_DATA | TGA_RGB;
	TGAReadImage(in, data);
	if (in->last != TGA_OK) {
		TGA_ERROR(in, in->last);
		return 0;
	}

	make_header(in, out);

	TGAWriteImage(out, data);
	if (out->last != TGA_OK) {
		TGA_ERROR(out, out->last);
		return 0;
	}

	printf("[close]\n[close]\n");
        TGAClose(in);
	TGAClose(out);

        printf("[exit] main\n");

	return EXIT_SUCCESS;
}
示例#21
0
/*
	 * change order of displayed fields
	 */
void change_order(void)
{
    char c, ch, *p;
    int i;

    show_fields();
    for (;;) {
	PUTP(tgoto(cm, 0, 0));
	PUTP(top_clrtoeol);
	PUTP(tgoto(cm, 3, 0));
	PUTP(mr);
	printf("Current Field Order: %s", Fields);
	PUTP(me);
	putchar('\n');
	PUTP(tgoto(cm, 0, 1));
	printf("Upper case characters move a field to the left, lower case to the right");
	fflush(stdout);
	if (!Batch) { /* should always be true, but... */
	    tcsetattr(0, TCSAFLUSH, &Rawtty);
	    read(0, &c, 1);
	    tcsetattr(0, TCSAFLUSH, &Savetty);
	}
	i = toupper(c) - 'A';
	if ((p = strchr(Fields, i + 'A')) != NULL) {
	    if (isupper(c))
		p--;
	    if ((p[1] != '\0') && (p >= Fields)) {
		ch = p[0];
		p[0] = p[1];
		p[1] = ch;
	    }
	} else if ((p = strchr(Fields, i + 'a')) != NULL) {
	    if (isupper(c))
		p--;
	    if ((p[1] != '\0') && (p >= Fields)) {
		ch = p[0];
		p[0] = p[1];
		p[1] = ch;
	    }
	} else {
	    break;
	}
    }
    Numfields = make_header();
}
示例#22
0
box
pager_rep::pages_make_page (pagelet pg) {
  box sb= pages_format (pg);
  box lb= move_box (ip, sb, 0, 0);
  int nr= N(pages) + 1 + page_offset;
  SI  left= (nr&1)==0? even: odd;
  env->write (PAGE_NR, as_string (nr));
  env->write (PAGE_THE_PAGE, style[PAGE_THE_PAGE]);
  tree page_t= env->exec (compound (PAGE_THE_PAGE));
  bool empty= N (pg->ins) == 0;
  box header= make_header (empty);
  box footer= make_footer (empty);
  brush bgc = make_background (empty);
  adjust_margins (empty);
  return page_box (ip, lb, page_t, nr, bgc, width, height,
                   left, top + dtop, top + dtop + text_height,
		   header, footer, head_sep, foot_sep);
}
示例#23
0
/*
       * Reads the window size and clear the window.  This is called on setup,
       * and also catches SIGWINCHs, and adjusts Maxlines.  Basically, this is
       * the central place for window size stuff.
       */
void window_size(int signo)
{
    struct winsize ws;

    if((ioctl(1, TIOCGWINSZ, &ws) != -1) && (ws.ws_col>73) && (ws.ws_row>7)){
	Cols = ws.ws_col;
	Lines = ws.ws_row;
    }else{
	Cols = tgetnum("co");
	Lines = tgetnum("li");
    }
    if (!Batch)
        clear_screen();
    /*
     * calculate header size, length of cmdline field ...
     */
     Numfields = make_header();
}
示例#24
0
static grub_size_t
insert_dir (const char *name, struct dir **root,
	    grub_uint8_t *ptr)
{
  struct dir *cur, **head = root;
  const char *cb, *ce = name;
  grub_size_t size = 0;
  while (1)
    {
      for (cb = ce; *cb == '/'; cb++);
      for (ce = cb; *ce && *ce != '/'; ce++);
      if (!*ce)
	break;

      for (cur = *root; cur; cur = cur->next)
	if (grub_memcmp (cur->name, cb, ce - cb)
	    && cur->name[ce - cb] == 0)
	  break;
      if (!cur)
	{
	  struct dir *n;
	  n = grub_zalloc (sizeof (*n));
	  if (!n)
	    return 0;
	  n->next = *head;
	  n->name = grub_strndup (cb, ce - cb);
	  if (ptr)
	    {
	      grub_dprintf ("linux", "Creating directory %s, %s\n", name, ce);
	      ptr = make_header (ptr, name, ce - name,
				 040777, 0);
	    }
	  size += ALIGN_UP ((ce - (char *) name)
			    + sizeof (struct newc_head), 4);
	  *head = n;
	  cur = n;
	}
      root = &cur->next;
    }
  return size;
}
示例#25
0
int		is_spc(char *buf, t_list *list, t_data *d)
{
	int		i;

	i = d->pos_init;
	if (buf[0] == 32 && buf[1] == 0 && buf[2] == 0)
	{
		ft_putnbr(d->pos_init);
		tputs(tgetstr("cl", NULL), 1, tputs_putchar);
		make_header(d);
		print_list_if(list, d);
		if (d->pos == d->pos_init)
			is_spc_1(list, d);
		else
			is_spc_2(list, d);
		while (i-- >= d->pos)
			tputs(tgetstr("up", NULL), 1, tputs_putchar);
		return (0);
	}
	else
		return (-1);
}
示例#26
0
simMetaData ()
{
    fpConfig_t fp;
    mdConfig_t md;
    int i, nkeyw = 256;


    /* Get a Page for the metadata.  */
    page = smcGetPage (smc, TY_META, (80*nkeyw), TRUE, TRUE);
    if (page == (smcPage_t *) NULL) {
	fprintf (stderr, "Error getting metadata page.\n");
	return;
    }

    md.metaType = 1;			/* Set the mdConfig struct.	*/
    md.numFields = nkeyw;
    smcSetMDConfig (page, &md);

    fp.xSize = im_nx;			/* Set the fpConfig struct.	*/
    fp.ySize = im_ny;
    fp.xStart = 0;
    fp.yStart = 0;
    fp.dataType = 1;
    smcSetFPConfig (page, &fp);

    smcSetWho (page, 2);		/* Set the 'who' field		*/
    smcSetExpID (page, 3.141592654);	/* Set the 'expid' field	*/
    smcSetObsetID (page, "3.14159");	/* Set the 'obsetid' field	*/

    /* Create a dummy header in the shared area 
     */
    make_header ((char *)smcGetPageData(page), nkeyw);

    /* Unlock and Detach from the page. 
     */
    smcUnlock (page);
    smcDetach (smc, page, FALSE);
}
示例#27
0
uint8_t *
build_disk(const struct disk_descriptor *desc, uint64_t *disk_size)
{
	struct vmdk_marker marker = { 0 };
	struct vmdk_grain_marker gmarker = { 0 };
	struct vmdk_sparse_extent_header *header;
	uint8_t *descriptor;
	uint8_t *rawdisk, *diskp;
	uint32_t *gd, *gt;
	uint64_t extent, gcoverage, gtcoverage, gtsize, gdsize, gtbase;
	uint32_t block_index;

	header = make_header(desc->capacity);
	if (header == NULL) {
		return NULL;
	}

	descriptor = make_descriptor(desc->capacity);
	if (descriptor == NULL) {
		free(header);
		return NULL;
	}

	gcoverage = header->grain_size * BYTES_PER_SECTOR;
	gtcoverage = header->num_gtes_per_gt * gcoverage;
	gtsize = header->num_gtes_per_gt * sizeof(uint32_t);
	gdsize = ((header->capacity * BYTES_PER_SECTOR + gtcoverage - 1) /
		  gtcoverage) * sizeof(uint32_t);

	#define ROUND(x) ((((x) + BYTES_PER_SECTOR - 1) / \
			  BYTES_PER_SECTOR) * BYTES_PER_SECTOR)

	/* Compute how much space we need */
	extent = 2 * BYTES_PER_SECTOR; /* header + descriptor */
	for (block_index = 0, gtbase = 0;
	     block_index < desc->nblocks;
	     block_index++) {
		if (desc->blocks[block_index].lba >= gtbase) {
			/* New grain table needed */
			extent += ROUND(gtsize) + sizeof(struct vmdk_marker);

			/* Skip empty grain tables */
			while (gtbase <= desc->blocks[block_index].lba) {
				gtbase += gtcoverage;
			}
		}

		/* Add on size of block */
		extent += ROUND(sizeof(struct vmdk_grain_marker) + 
				desc->blocks[block_index].size);
	}
	/* Add on size of grain directory */
	extent += ROUND(gdsize) + sizeof(struct vmdk_marker);
	extent += 3 * BYTES_PER_SECTOR; /* footer marker, footer, EOS */

	gt = calloc(1, gtsize);
	if (gt == NULL) {
		free(descriptor);
		free(header);
		return NULL;
	}

	gd = calloc(1, gdsize);
	if (gd == NULL) {
		free(gt);
		free(descriptor);
		free(header);
		return NULL;
	}

	/* Build the disk */
	diskp = rawdisk = calloc(1, extent);
	if (rawdisk == NULL) {
		free(gd);
		free(gt);
		free(descriptor);
		free(header);
		return NULL;
	}

	/* Emit header and descriptor */
	memcpy(diskp, header, sizeof(struct vmdk_sparse_extent_header));
	diskp += sizeof(struct vmdk_sparse_extent_header);
	memcpy(diskp, descriptor, BYTES_PER_SECTOR);
	diskp += BYTES_PER_SECTOR;

	marker.num_sectors = ROUND(gtsize) / BYTES_PER_SECTOR;
	marker.size = 0;
	marker.type = 1; /* Grain table */

	/* Emit blocks */
	for (block_index = 0, gtbase = 0;
	     block_index < desc->nblocks;
	     block_index++) {
		if (desc->blocks[block_index].lba >= gtbase) {
			/* New grain table needed */
			if (block_index > 0) {
				/* Record location in grain directory */
				gd[desc->blocks[block_index - 1].lba /
				   gtcoverage] = (diskp +
						  sizeof(struct vmdk_marker) -
						  rawdisk) /
						 BYTES_PER_SECTOR;

				/* Emit current grain table */
				memcpy(diskp, &marker,
				       sizeof(struct vmdk_marker));
				diskp += sizeof(struct vmdk_marker);
				memcpy(diskp, gt, gtsize);
				diskp += ROUND(gtsize);

				memset(gt, 0, gtsize);
			}

			/* Skip empty grain tables */
			while (gtbase <= desc->blocks[block_index].lba) {
				gtbase += gtcoverage;
			}
		}

		/* Record block location in grain table */
		gt[(desc->blocks[block_index].lba % gtcoverage) /
		   gcoverage] = (diskp - rawdisk) / BYTES_PER_SECTOR;

		/* Emit block */
		gmarker.lba = desc->blocks[block_index].lba / BYTES_PER_SECTOR;
		gmarker.size = desc->blocks[block_index].size;
		memcpy(diskp, &gmarker, sizeof(struct vmdk_grain_marker));
		memset(diskp + sizeof(struct vmdk_grain_marker), 
		       desc->blocks[block_index].fill,
		       desc->blocks[block_index].size);
		diskp += ROUND(sizeof(struct vmdk_grain_marker) + 
				desc->blocks[block_index].size);
	}

	if (block_index > 0) {
		/* Record final grain table location in grain directory */
		gd[desc->blocks[block_index - 1].lba / gtcoverage] = 
				(diskp + sizeof(struct vmdk_marker) - rawdisk) /
				BYTES_PER_SECTOR;

		/* Emit final grain table */
		memcpy(diskp, &marker, sizeof(struct vmdk_marker));
		diskp += sizeof(struct vmdk_marker);
		memcpy(diskp, gt, gtsize);
		diskp += ROUND(gtsize);
	}

	/* Emit grain directory marker */
	marker.num_sectors = ROUND(gdsize) / BYTES_PER_SECTOR;
	marker.size = 0;
	marker.type = 2; /* Grain directory */
	memcpy(diskp, &marker, sizeof(struct vmdk_marker));
	diskp += sizeof(struct vmdk_marker);

	/* Record grain directory location in footer */
	header->gd_offset = (diskp - rawdisk) / BYTES_PER_SECTOR;

	/* Emit grain directory */
	memcpy(diskp, gd, gdsize);
	diskp += ROUND(gdsize);

	/* Emit footer marker */
	marker.num_sectors = 1;
	marker.size = 0;
	marker.type = 3; /* Footer */
	memcpy(diskp, &marker, sizeof(struct vmdk_marker));
	diskp += sizeof(struct vmdk_marker);

	/* Emit footer */
	memcpy(diskp, header, sizeof(struct vmdk_sparse_extent_header));
	diskp += sizeof(struct vmdk_sparse_extent_header);

	/* Emit EOS marker */
	marker.num_sectors = 0;
	marker.size = 0;
	marker.type = 0;
	memcpy(diskp, &marker, sizeof(struct vmdk_marker));
	diskp += sizeof(struct vmdk_marker);

	assert(diskp - rawdisk == extent);

	/* Clean up */
	free(gd);
	free(gt);
	free(descriptor);
	free(header);

	*disk_size = extent;
	return rawdisk;
}
示例#28
0
文件: 3600recv.c 项目: mrodrig/cs3600
int main() {
  // first, open a UDP socket
  int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  // next, construct the local port
  struct sockaddr_in out;
  out.sin_family = AF_INET;
  out.sin_port = htons(0);
  out.sin_addr.s_addr = htonl(INADDR_ANY);

  if (bind(sock, (struct sockaddr *) &out, sizeof(out))) {
    perror("bind");
    exit(1);
  }

  struct sockaddr_in tmp;
  int len = sizeof(tmp);
  if (getsockname(sock, (struct sockaddr *) &tmp, (socklen_t *) &len)) {
    perror("getsockname");
    exit(1);
  }

  mylog("[bound] %d\n", ntohs(tmp.sin_port));

  // wait for incoming packets
  struct sockaddr_in in;
  socklen_t in_len = sizeof(in);

  // construct the socket set
  fd_set socks;

  // construct the timeout
  struct timeval t;
  t.tv_sec = 30;
  t.tv_usec = 0;

  // our receive buffer
  int buf_len = PACKET_SIZE;
  void *buf = calloc(1, buf_len);
  unsigned int buf_data_len = 0;

  // data buffer for received packets
  char *data_buffer = calloc(WINDOW_SIZE * buf_len, sizeof(char));
  // array of lengths of received packets
  unsigned int *data_len = calloc(WINDOW_SIZE, sizeof(unsigned int));

  // sequence number that the receiver acknowledges receiving
  unsigned int acknowledged_packet = 0;

  unsigned int indx;

  // wait to receive, or for a timeout
  while ( TRUE ) {
    FD_ZERO(&socks);
    FD_SET(sock, &socks);

    if (select(sock + 1, &socks, NULL, NULL, &t)) {
      if ((recvfrom(sock, buf, buf_len, 0, (struct sockaddr *) &in, (socklen_t *) &in_len)) < 0) {
        perror("recvfrom");
        exit(1);
      }

      // retrieve the length of the received data in the buffer
      buf_data_len = ntohs(((header *) buf)->length);

      // get the header of the data in buf
      header *myheader = get_header(buf);

      // compute the checksum of the data in the buffer
      unsigned char expected_checksum = compute_chksm((char *)buf, get_data(buf), buf_data_len);

      // get the data section of the data in the buf
      char *data = get_data(buf);

      // retrieve checksum value from the packet
      unsigned int recvd_chksum = (unsigned char) *(data - 1);

      // if this packet was sent by our sender
      if (myheader->magic == MAGIC) {

        if (expected_checksum != recvd_chksum) {
          mylog("[recv corrupted packet]");
          continue;
        }

        // if this is the next packet
        if (myheader->sequence == (acknowledged_packet + 1)) {
          mylog("[recv data] %d (%d) %s\n", myheader->sequence, myheader->length, "ACCEPTED (in order)");

          // write the data to the buffer
          write(1, data, myheader->length);

          // calculate the index of the next packet into data_buffer[]
          // increment acknowledged packet before use
          indx = (++acknowledged_packet + 1) % WINDOW_SIZE;

          // while there is data in the subsequent entries
          while(data_len[indx] > 0) {
            // write the data for that packet into the buffer
            write(1, &data_buffer[indx * buf_len], data_len[indx]);

            // decrement the length to prevent wrap arounds
            data_len[indx] = -1;

            // calculate the index of the next packet into data_buffer[]
            // increment acknowledged packet before use
            indx = (++acknowledged_packet + 1) % WINDOW_SIZE;
          }
        } // if already received this packet
        else if (myheader->sequence < (acknowledged_packet + 1)) {
          // do nothing, already have data
          mylog("IGNORED\n");
        } // this packet was received out of order and is not the next packet
        else {
          // calculate the index of the next packet into data_buffer[]
          indx = myheader->sequence % WINDOW_SIZE;

          // if there's no data stored at that index
          if (data_len[indx] <= 0) {
            // store the actual length
            data_len[indx] = myheader->length;
            // copy the data over to the buffer in case the data was
            //   received out of order
            memcpy(&data_buffer[indx * buf_len], data, myheader->length);
          }
        }

        mylog("[recv data] %d (%d) %s\n", myheader->sequence, myheader->length, "ACCEPTED (out of order)");
        mylog("[send ack] %d\n", acknowledged_packet);

        // allocate space for the packet
        void *packet = calloc(1, PACKET_OVERHEAD);

        // generate the header and copy it to the packet
        header *responseheader = make_header((short)acknowledged_packet, 0, myheader->eof, TRUE, ntohl(myheader->time));
        memcpy(packet, responseheader, sizeof(header));

        // compute the checksum and copy it to the packet
        unsigned char checksum = compute_chksm((char *)responseheader, NULL, 0);
        memcpy(((char *) packet) + sizeof(header), (char *)&checksum, sizeof(unsigned char));

        // send the ack packet
        if (sendto(sock, packet, sizeof(header) + sizeof(char), 0, (struct sockaddr *) &in, (socklen_t) sizeof(in)) < 0) {
          perror("sendto");
          exit(1);
        }

        // if that packet was EOF, exit
        if (myheader->eof) {
          mylog("[recv eof]\n");
          mylog("[completed]\n");
          exit(0);
        }
      } else { // if the packet had a bad MAGIC number
        mylog("[recv invalid packet]\n");
      }
    } else { // receiver timed out
      mylog("[error] timeout occurred\n");
      exit(1);
    }
  }


  return 0;
}
示例#29
0
int
main(
	int argc,
	char **argv
)
try
{
	if(
		argc != 2
	)
	{
		fcppt::io::cerr()
			<< FCPPT_TEXT("Usage: ")
			<< argv[0]
			<< FCPPT_TEXT(" <dir1>\n");

		return EXIT_FAILURE;
	}

	boost::filesystem::path const dir(
		fcppt::from_std_string(
			argv[1]
		)
	);

	for(
		boost::filesystem::recursive_directory_iterator dir_it(
			dir
		),
		dir_end;
		dir_it != dir_end;
		++dir_it
	)
	{
		if(
			!needs_header(
				dir_it->path()
			)
		)
			continue;

		boost::filesystem::path const header(
			make_header(
				dir_it->path()
			)
		);

		fcppt::filesystem::ofstream file(
			header,
			std::ios_base::trunc
		);

		string_vector filenames;

		if(
			!file.is_open()
		)
		{
			fcppt::io::cerr()
				<< FCPPT_TEXT("Failed to open ")
				<< header
				<< FCPPT_TEXT('\n');

			return EXIT_FAILURE;
		}

		for(
			boost::filesystem::directory_iterator file_it(
				dir_it->path()
			),
			file_end;
			file_it != file_end;
			++file_it
		)
		{
			if(
				file_it->path()
				== header
			)
				continue;

			if(
				needs_header(
					file_it->path()
				)
			)
				filenames.push_back(
					fcppt::filesystem::path_to_string(
						make_header(
							file_it->path()
						)
					)
				);
			else if(
				!boost::filesystem::is_directory(
					file_it->path()
				)
			)
				filenames.push_back(
					fcppt::filesystem::path_to_string(
						file_it->path()
					)
				);
		}

		std::sort(
			filenames.begin(),
			filenames.end()
		);

		fcppt::string const include_guard_name(
			make_include_guard(
				header
			)
		);

		file
			<< FCPPT_TEXT("#ifndef ")
			<< include_guard_name
			<< FCPPT_TEXT("\n#define ")
			<< include_guard_name
			<< FCPPT_TEXT("\n\n");

		for(
			string_vector::const_iterator cur_name(
				filenames.begin()
			);
			cur_name != filenames.end();
			++cur_name
		)
			file
				<< FCPPT_TEXT("#include <")
				<< *cur_name
				<< FCPPT_TEXT(">\n");

		file
			<< FCPPT_TEXT("\n#endif\n");
	}
}
catch(
	fcppt::exception const &_error
)
{
	fcppt::io::cerr()
		<< _error.string()
		<< FCPPT_TEXT('\n');

	return EXIT_FAILURE;
}
catch(
	std::exception const &_error
)
{
	std::cerr
		<< _error.what()
		<< '\n';

	return EXIT_FAILURE;
}
示例#30
0
/*
 * Process keyboard input during the main loop
 */
void do_key(char c)
{
    int numinput, i;
    char rcfile[MAXNAMELEN];
    FILE *fp;

    /*
     * First the commands which don't require a terminal mode switch.
     */
    if (c == 'q')
	sig_end(0);
    else if (c == ' ')
        return;
    else if (c == 12) {
	clear_screen();
	return;
    } else if (c == 'I') {
	Irixmode=(Irixmode) ? 0 : 1;
	return;
    }

    /*
     * Switch the terminal to normal mode.  (Will the original
     * attributes always be normal?  Does it matter?  I suppose the
     * shell will be set up the way the user wants it.)
     */
    if (!Batch) tcsetattr(0, TCSANOW, &Savetty);

    /*
     * Handle the rest of the commands.
     */
    switch (c) {
      case '?':
      case 'h':
	PUTP(cl); PUTP(ho); putchar('\n'); PUTP(mr);
	printf("Proc-Top Revision 1.2");
	PUTP(me); putchar('\n');
	printf("Secure mode ");
	PUTP(md);
	fputs(Secure ? "on" : "off", stdout);
	PUTP(me);
	fputs("; cumulative mode ", stdout);
	PUTP(md);
	fputs(Cumulative ? "on" : "off", stdout);
	PUTP(me);
	fputs("; noidle mode ", stdout);
	PUTP(md);
	fputs(Noidle ? "on" : "off", stdout);
	PUTP(me);
	fputs("\n\n", stdout);
	printf("%s\n\nPress any key to continue", Secure ? SECURE_HELP_SCREEN : HELP_SCREEN);
	if (!Batch) tcsetattr(0, TCSANOW, &Rawtty);
	(void) getchar();
	break;
      case 'i':
	Noidle = !Noidle;
	SHOWMESSAGE(("No-idle mode %s", Noidle ? "on" : "off"));
	break;
      case 'u':
	SHOWMESSAGE(("Which User (Blank for All): "));
	strcpy(CurrUser,getstr());
	break;
      case 'k':
	if (Secure)
	    SHOWMESSAGE(("\aCan't kill in secure mode"));
	else {
	    int pid, signal;
	    PUTP(md);
	    SHOWMESSAGE(("PID to kill: "));
	    pid = getint();
	    if (pid == BAD_INPUT)
		break;
	    PUTP(top_clrtoeol);
	    SHOWMESSAGE(("Kill PID %d with signal [15]: ", pid));
	    PUTP(me);
	    signal = getsig();
	    if (signal == -1)
		signal = SIGTERM;
	    if (kill(pid, signal))
		SHOWMESSAGE(("\aKill of PID %d with %d failed: %s",
			     pid, signal, strerror(errno)));
	}
	break;
      case 'l':
	SHOWMESSAGE(("Display load average %s", !show_loadav ? "on" : "off"));
	if (show_loadav) {
	    show_loadav = 0;
	    header_lines--;
	} else {
	    show_loadav = 1;
	    header_lines++;
	}
	Numfields = make_header();
	break;
      case 'm':
	SHOWMESSAGE(("Display memory information %s", !show_memory ? "on" : "off"));
	if (show_memory) {
	    show_memory = 0;
	    header_lines -= 2;
	} else {
	    show_memory = 1;
	    header_lines += 2;
	}
	Numfields = make_header();
	break;
      case 'M':
        SHOWMESSAGE(("Sort by memory usage"));
	sort_type = S_MEM;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)mem_sort);
	break;
      case 'n':
      case '#':
	printf("Processes to display (0 for unlimited): ");
	numinput = getint();
	if (numinput != BAD_INPUT) {
	    Display_procs = numinput;
	    window_size(0);
	}
	break;
      case 'r':
	if (Secure)
	    SHOWMESSAGE(("\aCan't renice in secure mode"));
	else {
	    int pid, val;

	    printf("PID to renice: ");
	    pid = getint();
	    if (pid == BAD_INPUT)
		break;
	    PUTP(tgoto(cm, 0, header_lines - 2));
	    PUTP(top_clrtoeol);
	    printf("Renice PID %d to value: ", pid);
	    val = getint();
	    if (val == BAD_INPUT)
		val = 10;
	    if (setpriority(PRIO_PROCESS, pid, val))
		SHOWMESSAGE(("\aRenice of PID %d to %d failed: %s",
			     pid, val, strerror(errno)));
	}
	break;
      case 'P':
        SHOWMESSAGE(("Sort by CPU usage"));
	sort_type = S_PCPU;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)pcpu_sort);
	break;
      case 'A':
	SHOWMESSAGE(("Sort by age"));
	sort_type = S_AGE;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)age_sort);
	break;
      case 'N':
	SHOWMESSAGE(("Sort numerically by pid"));
	sort_type = S_NONE;
	reset_sort_options();
	break;
    case 'c':
        show_cmd = !show_cmd;
	SHOWMESSAGE(("Show %s", show_cmd ? "command names" : "command line"));
	break;
      case 'S':
	Cumulative = !Cumulative;
	SHOWMESSAGE(("Cumulative mode %s", Cumulative ? "on" : "off"));
	if (Cumulative)
	    headers[22][1] = 'C';
	else
	    headers[22][1] = ' ';
	Numfields = make_header();
	break;
      case 's':
	if (Secure)
	    SHOWMESSAGE(("\aCan't change delay in secure mode"));
	else {
	    double tmp;
	    printf("Delay between updates: ");
	    tmp = getfloat();
	    if (!(tmp < 0))
		Sleeptime = tmp;
	}
	break;
      case 't':
	SHOWMESSAGE(("Display summary information %s", !show_stats ? "on" : "off"));
	if (show_stats) {
	    show_stats = 0;
	    header_lines -= 2;
	} else {
	    show_stats = 1;
	    header_lines += 2;
	}
	Numfields = make_header();
	break;
      case 'T':
	SHOWMESSAGE(("Sort by %stime", Cumulative ? "cumulative " : ""));
	sort_type = S_TIME;
	reset_sort_options();
	register_sort_function( -1, (cmp_t)time_sort);	
	break;
      case 'f':
      case 'F':
	change_fields();
	break;
      case 'o':
      case 'O':
	change_order();
	break;
      case 'W':
	if (getenv("HOME")) {
	    strcpy(rcfile, getenv("HOME"));
	    strcat(rcfile, "/");
	    strcat(rcfile, RCFILE);
	    fp = fopen(rcfile, "w");
	    if (fp != NULL) {
		fprintf(fp, "%s\n", Fields);
		i = (int) Sleeptime;
		if (i < 2)
		    i = 2;
		if (i > 9)
		    i = 9;
		fprintf(fp, "%d", i);
		if (Secure)
		    fprintf(fp, "%c", 's');
		if (Cumulative)
		    fprintf(fp, "%c", 'S');
		if (!show_cmd)
		    fprintf(fp, "%c", 'c');
		if (Noidle)
		    fprintf(fp, "%c", 'i');
		if (!show_memory)
		    fprintf(fp, "%c", 'm');
		if (!show_loadav)
		    fprintf(fp, "%c", 'l');
		if (!show_stats)
		    fprintf(fp, "%c", 't');
		if (!Irixmode)
		    fprintf(fp, "%c", 'I');
		fprintf(fp, "\n");
		fclose(fp);
		SHOWMESSAGE(("Wrote configuration to %s", rcfile));
	    } else {
		SHOWMESSAGE(("Couldn't open %s", rcfile));
	    }
	} else {
	    SHOWMESSAGE(("Couldn't get $HOME -- not saving"));
	}
	break;
      default:
	SHOWMESSAGE(("\aUnknown command `%c' -- hit `h' for help", c));
    }

    /*
     * Return to raw mode.
     */
    if (!Batch) tcsetattr(0, TCSANOW, &Rawtty);
    return;
}