Exemplo n.º 1
0
void Http::set_data(const char *_data) {
    data = _data;
    std::string content_length = std::to_string(strlen(data));
    set_header("Content-Length", content_length);
}
Exemplo n.º 2
0
void sniffer_list_view::clear()
{
    model->clear();
    item_cnt = 0;
    set_header();
}
int main(int argc, char **argv)
{
	int opt;
	int font_fd;
	struct stat fd_stat;
	uint32_t bits_per_pix = 16;
	uint8_t *addr_fd_in;
	uint8_t gb2312buf[MAX_LINE * 2];
	uint32_t offset;
	bmp_file_t bmp;
	bmp_file_t bmp2;
	bmp_file_t bmp_all;
	uint32_t image_size;
	int ret;
	char *pret;

	while ((opt = getopt(argc, argv, "d:")) != -1) {
		switch (opt) {
		case 'd':
			bits_per_pix = atoi(optarg);
			break;
		default: /* '?' */
			fprintf(stderr, 
				"Usage: %s [-d bitdepth(16 or 24)]\n", 
				argv[0]);
			exit(1);
		}
	}
	pret = fgets((char *)gb2312buf, sizeof(gb2312buf) - 1, stdin);

	font_fd = open(GB2312_HZK, O_RDONLY);
	if (font_fd < 0) {
		perror("open");
		exit(1);
	}
	ret = fstat(font_fd, &fd_stat);
	if (ret == -1) {
		perror("fstat");
		exit(1);
	}
	addr_fd_in = mmap(NULL, (size_t) fd_stat.st_size,
			  PROT_READ, MAP_PRIVATE, font_fd, (off_t) 0);
	if (addr_fd_in == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}

	/* debug_print("gb2312buf[0] = %#x", ((uint16_t *)gb2312buf)[0]); */
	offset = gb2312code_to_fontoffset(((uint16_t *)gb2312buf)[0]);
	/* debug_print("offset = %#x", offset); */
	memset(&bmp, 0, sizeof(bmp));
	set_header(&bmp, 16, 16, bits_per_pix);
	image_size = bmp.dib_h.image_size;
	bmp.pdata = malloc(image_size);
	memset(bmp.pdata, 0, image_size);
	fontdata2bmp(addr_fd_in + offset, 16, 16, &bmp, bits_per_pix, 0);

	/* debug_print("gb2312buf[0] = %#x", ((uint16_t *)gb2312buf)[1]); */
	offset = gb2312code_to_fontoffset(((uint16_t *)gb2312buf)[1]);
	/* debug_print("offset = %#x", offset); */
	memset(&bmp2, 0, sizeof(bmp2));
	set_header(&bmp2, 16, 16, bits_per_pix);
	image_size = bmp2.dib_h.image_size;
	bmp2.pdata = malloc(image_size);
	memset(bmp2.pdata, 0, image_size);
	fontdata2bmp(addr_fd_in + offset, 16, 16, &bmp2, bits_per_pix, 0);

	/* debug_print("will memset bmp_all"); */

	memset(&bmp_all, 0, sizeof(bmp_all));
	set_header(&bmp_all, 
		   bmp.dib_h.width + bmp2.dib_h.width,
		   bmp.dib_h.height,
		   bmp.dib_h.bits_per_pix);
	bmp_all.pdata = malloc(bmp_all.dib_h.image_size);
	/* debug_print("bmp_all.dib_h.image_size is %d", bmp_all.dib_h.image_size); */
	/* debug_print("bmp_all.pdata is %#x", bmp_all.pdata); */
	bmp_h_combin(&bmp, &bmp2, &bmp_all);

	ret = fwrite(&bmp.bmp_h, sizeof(bmp_file_header_t), 1, stdout);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(&bmp.dib_h, sizeof(dib_header_t), 1, stdout);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(bmp.pdata, sizeof(uint8_t), image_size, stdout);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}

	if (bmp.pdata) {
		free(bmp.pdata);
		bmp.pdata = NULL;
	}


#if 0
	ret = fwrite(&bmp2.bmp_h, sizeof(bmp_file_header_t), 1, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(&bmp2.dib_h, sizeof(dib_header_t), 1, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(bmp2.pdata, sizeof(uint8_t), image_size, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
#else
	ret = fwrite(&bmp_all.bmp_h, sizeof(bmp_file_header_t), 1, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(&bmp_all.dib_h, sizeof(dib_header_t), 1, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
	ret = fwrite(bmp_all.pdata, sizeof(uint8_t), bmp_all.dib_h.image_size, stderr);
	if (ret < 0) {
		perror("fwrite");
		exit(1);
	}
#endif

	if (bmp2.pdata) {
		free(bmp2.pdata);
		bmp2.pdata = NULL;
	}


	ret = munmap(addr_fd_in, (size_t) fd_stat.st_size);
	if (ret == -1) {
		perror("munmap");
		exit(1);
	}
	close(font_fd);
	return 0;
}
Exemplo n.º 4
0
void TFileSel::compute_nb_items() {
  DIR *dir = opendir(path);
  int nb_menu = 10;
  char cwd[1024];
  char tmp_path[1024];
  int found_cue = 0, found_iso = 0;
  char *oldsel = strrchr(res_file,SLASH[0]);
  if (oldsel) oldsel++;
  if (menu)
    free(menu);
  menu = (menu_item_t *)malloc(sizeof(menu_item_t)*(nb_menu+1));
  memset(menu,0,sizeof(menu_item_t)*(nb_menu+1));

  menu[0].label = "..";
  menu[0].menu_func = &exec_dir;
  if (!dir) {
    perror(path);
  } else {
    getcwd(cwd,1024);
    nb_files = 1;
    struct dirent *dent;
    while ((dent = readdir(dir))) {
      if (!strcmp(dent->d_name,".") || !strcmp(dent->d_name,".."))
	continue;
      menu[nb_files].label = strdup(dent->d_name);
      sprintf(tmp_path,"%s%s%s",path,SLASH,dent->d_name);
      /* The big stupidity of readdir is that it doesn't set d_type (posix
       * compliant !!!).  */
      struct stat buf;
      if (!stat(tmp_path,&buf) && S_ISDIR(buf.st_mode)) {
	menu[nb_files].menu_func = &exec_dir;
	nb_files++;
      } else if (!(options & ONLY_DIRS)) {
	menu[nb_files].menu_func = &exec_file;
	int found = 0,idx;
	char *s = dent->d_name;
	if (strlen(s) > 3) {
	    if (!stricmp(&s[strlen(s)-3],"iso") ||
		    (strlen(s) > 6 && !stricmp(&s[strlen(s)-6],"iso.gz")))
		found_iso++;
	    else if (!stricmp(&s[strlen(s)-3],"cue"))
		found_cue++;
	}
	if (ext) {
	    for (s=ext[0], idx=1; s; s=ext[idx++]) {
		int l = strlen(s);
		if (strchr(s,'*') || strchr(s,'?')) { // pattern search
		    if (!fnmatch(s,dent->d_name,FNM_CASEFOLD)) {
			found = 1;
			break;
		    }
		} else if (!stricmp(&dent->d_name[strlen(dent->d_name)-(l)],s)) {
		    // extension only
		    found = 1;
		    break;
		}
	    }
	} else
	    found = 1;
	if (!found) {
	  // doesn't match the extension given
	  free((void*)menu[nb_files].label);
	} else
	  nb_files++;
      }

      if (nb_files == nb_menu) {
	nb_menu += 10;
	menu = (menu_item_t *)realloc(menu,sizeof(menu_item_t)*(nb_menu+1));
	memset(&menu[nb_files],0,sizeof(menu_item_t)*11);
	if (!menu) {
	  fprintf(stderr,"failed to realloc files buffer (%d entries)\n",nb_menu);
	  exit(1);
	}
      }
    }
    menu[nb_files].label = NULL;
    closedir(dir);
    qsort(&menu[1],nb_files-1,sizeof(menu_item_t),&sort_menu);
    if (oldsel)
	for (int n=1; n<nb_files; n++)
	    if (!strcmp(menu[n].label,oldsel))
		sel = n;
    chdir(cwd);
  }
  strcpy(res_file,path);
  if (path[strlen(path)-1] != SLASH[0])
    strcat(res_file,SLASH);
  if (options & SAVE)
      set_header(myheader_save);
  else
      set_header(myheader);
  int tmpsel = sel;
  if (found_iso && !found_cue && strcmp(ext[0],".iso")) {
      char *myexts[] = { ".iso", "iso.gz", "zip", "7z", NULL };
      char **old = ext;
      ext = myexts;
      compute_nb_items();
      ext = old;
  } else
      TMenu::compute_nb_items();
  if (tmpsel > -1)
      sel = tmpsel; // blocks find_new_sel from compute_nb_items
}
Exemplo n.º 5
0
int
msg_read_rom (const char *filename, unsigned short parport)
{
  FILE *file;
  unsigned char *buffer, blocksleft, emu_mode_select;
  int size, bytesreceived = 0;
  time_t starttime;
  unsigned short blocksdone = 0;

  ffe_init_io (parport);

  if ((file = fopen (filename, "wb")) == NULL)
    {
      fprintf (stderr, ucon64_msg[OPEN_WRITE_ERROR], filename);
      exit (1);
    }
  if ((buffer = (unsigned char *) malloc (BUFFERSIZE)) == NULL)
    {
      fprintf (stderr, ucon64_msg[FILE_BUFFER_ERROR], BUFFERSIZE);
      exit (1);
    }

  set_header (buffer);
  if (buffer[0] == 0)
    {
      fprintf (stderr, "ERROR: There is no cartridge present in the Magic Super Griffin\n");
      fclose (file);
      remove (filename);
      exit (1);
    }
  blocksleft = buffer[0];
  size = buffer[0] * 8192;
  printf ("Receive: %d Bytes (%.4f Mb)\n", size, (float) size / MBIT);

  fwrite (buffer, 1, MSG_HEADER_LEN, file);     // write header
  emu_mode_select = buffer[1];

  ffe_send_command (5, 0, 0);
  ffe_send_command0 (0xbff0, 0);

  printf ("Press q to abort\n\n");

  starttime = time (NULL);
  while (blocksleft > 0)
    {
      ffe_send_command (5, blocksdone, 0);
      if (emu_mode_select && blocksdone >= 32)
        ffe_send_command (5, blocksdone + 32, 0);
      ffe_receive_block (0xa000, buffer, BUFFERSIZE);
      // vgs aborts if the checksum doesn't match the data, we let the user decide
      blocksleft--;
      blocksdone++;
      fwrite (buffer, 1, BUFFERSIZE, file);

      bytesreceived += BUFFERSIZE;
      ucon64_gauge (starttime, bytesreceived, size);
      ffe_checkabort (2);
    }

  free (buffer);
  fclose (file);

  return 0;
}
Exemplo n.º 6
0
int main(int argc, char **argv)
{
	int opt;
	struct text_style style;
	uint32_t bits_per_pix = 16;
	color_setting_t color = {0x0, 0xffffffff};
	FILE *in = stdin;
	int gb2312_num;
	uint16_t *mem_addr;
	uint8_t linebuf[MAX_LINE];
	uint8_t gb2312buf[MAX_LINE * 2];
	uint8_t *ptr;
	uint8_t *ptr_gb2312;
	uint8_t unicode[2] = {0};
	uint16_t gb2312_code;
	uint8_t *addr_fd_in;
	struct stat fd_stat;
	int font_fd;
	int ascii_fd;
	struct stat ascii_fd_stat;
	uint8_t *addr_ascii_fd_in;
	int once_read;
	int i;
	uint32_t offset;
	bmp_file_t bmp_char;
	bmp_file_t bmp_line;
	bmp_file_t bmp_all;
	bmp_file_t bmp_blank;
	int encoding_type = UTF8_NO_BOM;
	int ret;

	memset(&style, 0, sizeof(struct text_style));
	while ((opt = getopt(argc, argv, "l:r:u:d:i:c:m:b:f:g:h?")) != -1) {
		switch (opt) {
		case 'l': /* 左边距 */
			style.left_margin = strtol(optarg, NULL, 0);
			break;
		case 'r': /* 右边距 */
			style.right_margin = strtol(optarg, NULL, 0);
			break;
		case 'u': /* 上边距 */
			style.up_margin = strtol(optarg, NULL, 0);
			break;
		case 'd': /* 下边距 */
			style.down_margin = strtol(optarg, NULL, 0);
			break;
		case 'i': /* 行间距 */
			style.line_spacing = strtol(optarg, NULL, 0);
			break;
		case 'c': /* 字符间距 */
			style.character_spacing = strtol(optarg, NULL, 0);
			break;
		case 'm': /* 每行最大长度 */
			style.max_line_length = strtol(optarg, NULL, 0);
			break;
		case 'b': /* 位深 */
			bits_per_pix = strtol(optarg, NULL, 0);
			break;
		case 'g': /* 背景色 */
			color.bg_color = strtol(optarg, NULL, 0);
			break;
		case 'f': /* 前景色 */
			color.fg_color = strtol(optarg, NULL, 0);
			break;
		default:
			show_usage(argv[0]);
			exit(1);
		}
	} /* while ((opt = getopt(argc, argv, "l:r:u:d:i:c:m:b:o:")) != -1) */
	if (argc > optind) {
		in = fopen(argv[optind], "r");
		if (!in) {
			fprintf(stderr,
				"Unable to open input file \"%s\": %s\n",
				argv[optind], strerror(errno));
			return 1;
		}
		encoding_type = detect_file_encoding(in);
	}

	mem_addr = mem_gb2312(GB2312, &gb2312_num);
	if (!mem_addr)
		mem_addr = mem_gb2312("./GB2312", &gb2312_num);
	if (!mem_addr) {
		debug_print("mem_gb2312 failed");
		exit(1);
	}
	font_fd = open(GB2312_HZK, O_RDONLY);
	if (font_fd < 0)
		font_fd = open("./gb2312.hzk", O_RDONLY);
	if (font_fd < 0) {
		debug_print("open failed");
		perror("open");
		exit(1);
	}
	ret = fstat(font_fd, &fd_stat);
	if (ret == -1) {
		perror("fstat");
		exit(1);
	}
	addr_fd_in = mmap(NULL, (size_t) fd_stat.st_size,
			  PROT_READ, MAP_PRIVATE, font_fd, (off_t) 0);
	if (addr_fd_in == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}

	ascii_fd = open(ASCII_HZK, O_RDONLY);
	if (ascii_fd < 0)
		ascii_fd = open("./ASC16", O_RDONLY);
	if (ascii_fd < 0) {
		debug_print("open failed");
		perror("open");
		exit(1);
	}
	ret = fstat(ascii_fd, &ascii_fd_stat);
	if (ret == -1) {
		perror("fstat");
		exit(1);
	}
	addr_ascii_fd_in = mmap(NULL, (size_t) ascii_fd_stat.st_size,
			  PROT_READ, MAP_PRIVATE, ascii_fd, (off_t) 0);
	if (addr_ascii_fd_in == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}

	memset(&bmp_char, 0, sizeof(bmp_char));
	bmp_char.pdata = malloc(FONT_BMP_SIZE);
	memset(&bmp_line, 0, sizeof(bmp_line));
	memset(&bmp_all, 0, sizeof(bmp_all));
	memset(&bmp_blank, 0, sizeof(bmp_blank));
	bmp_blank.pdata = malloc(FONT_BMP_SIZE);

	once_read = (style.max_line_length > 0)
			? (style.max_line_length + 1) : (sizeof(linebuf) - 1);
	if (encoding_type == UTF8_WITH_BOM) {
		if (fseek(in, 3, SEEK_SET)) {
			debug_print("fseek failed: %s", strerror(errno));
			exit(1);
		}
	}
	for(;;) {
		if (encoding_type == UTF8_NO_BOM ||
		    encoding_type == UTF8_WITH_BOM) {
			if (fgets_utf8((char *)linebuf, once_read, in) == NULL)
				break;
			ptr_gb2312 = gb2312buf;
			ptr = linebuf;
			if (*ptr == '\n')
				*ptr = ' ';
			while (*ptr) {
				ret = utf8tounicode(ptr, unicode);
				if (ret < 0) {
					debug_print("utf8tounicode return %d\n",
						    ret);
					exit(1);
				}
				ptr += ret;
				gb2312_code = unicode_to_gb2312(
						unicode[0] + unicode[1] * 0x100,
						mem_addr,
						gb2312_num);
				ptr_gb2312[0] = gb2312_code % 0x100;
				if (gb2312_code / 0x100 > 0) {
					ptr_gb2312[1] = gb2312_code / 0x100;
					ptr_gb2312 += 2;
				} else
					ptr_gb2312 += 1;
			}
			ptr_gb2312[0] = '\0';
		} else if (encoding_type == GBK) {
			if (fgets_gbk((char *)gb2312buf, once_read, in) == NULL)
				break;
			if (*gb2312buf == '\n')
				*gb2312buf = ' ';
		}

		/*
		 * gb2312tobmps
		 */
		i = 0;
		for (;;) {
			if (gb2312buf[i] > 0xA0 && gb2312buf[i]  < 0xff) {
				offset = gb2312code_to_fontoffset(gb2312buf[i] +
						0x100 * gb2312buf[i + 1]);
				i += 2;
				set_header(&bmp_char, CHAR_HEIGHT, CHAR_HEIGHT,
						bits_per_pix);
				memset(bmp_char.pdata, 0,
					bmp_char.dib_h.image_size);
				fontdata2bmp(addr_fd_in + offset, CHAR_HEIGHT,
						CHAR_HEIGHT, &bmp_char,
						bits_per_pix, &color);

			} else if (gb2312buf[i] > 0x1f && gb2312buf[i] < 0x80) {
				offset = ascii_to_fontoffset(gb2312buf[i]);
				i++;
				set_header(&bmp_char, 8, CHAR_HEIGHT,
					   bits_per_pix);
				memset(bmp_char.pdata, 0,
					bmp_char.dib_h.image_size);
				fontdata2bmp(addr_ascii_fd_in + offset, 8,
						CHAR_HEIGHT, &bmp_char,
						bits_per_pix, &color);
			} else if (gb2312buf[i] == '\t') {
				i++;
				create_blank_bmp(&bmp_char,
						 8 * 8,
						 1,
						 bits_per_pix,
						 color.bg_color);
			} else
				break;

			bmp_h_combin_3(&bmp_line, &bmp_char, color.bg_color);
			if (style.character_spacing > 0) {
				create_blank_bmp(&bmp_blank,
						style.character_spacing,
						1,
						bits_per_pix,
						color.bg_color);
				bmp_h_combin_3(&bmp_line, &bmp_blank,
						color.bg_color);
			}
		} /* for (;;) */
		bmp_v_combin_3(&bmp_all, &bmp_line, color.bg_color);
		if (style.line_spacing > 0) {
			create_blank_bmp(&bmp_blank,
					1,
					style.line_spacing,
					bits_per_pix,
					color.bg_color);
			bmp_v_combin_3(&bmp_all, &bmp_blank, color.bg_color);
		}
		if (bmp_line.pdata) {
			free(bmp_line.pdata);
			bmp_line.pdata = NULL;
		}
		memset(&bmp_line, 0, sizeof(bmp_line));
	} /* while (fgets_utf8((char *)linebuf, sizeof(linebuf) - 1, in)) */

	/*
	 * 格式处理
	 */
	if (style.left_margin > 0) {
		create_blank_bmp(&bmp_blank,
				style.left_margin,
				1,
				bits_per_pix,
				color.bg_color);
		bmp_h_combin_3(&bmp_blank, &bmp_all, color.bg_color);
		memcpy(&bmp_all.bmp_h, &bmp_blank.bmp_h,
			sizeof(bmp_file_header_t));
		memcpy(&bmp_all.dib_h, &bmp_blank.dib_h, sizeof(dib_header_t));
		bmp_all.pdata = realloc(bmp_all.pdata, bmp_all.dib_h.image_size);
		memcpy(bmp_all.pdata, bmp_blank.pdata, bmp_all.dib_h.image_size);
	}
	if (style.right_margin > 0) {
		create_blank_bmp(&bmp_blank,
				style.right_margin,
				1,
				bits_per_pix,
				color.bg_color);
		bmp_h_combin_3(&bmp_all, &bmp_blank, color.bg_color);
	}
	if (style.up_margin > 0) {
		create_blank_bmp(&bmp_blank,
				1,
				style.up_margin,
				bits_per_pix,
				color.bg_color);
		bmp_v_combin_3(&bmp_blank, &bmp_all, color.bg_color);
		memcpy(&bmp_all.bmp_h, &bmp_blank.bmp_h,
			sizeof(bmp_file_header_t));
		memcpy(&bmp_all.dib_h, &bmp_blank.dib_h, sizeof(dib_header_t));
		bmp_all.pdata = realloc(bmp_all.pdata, bmp_all.dib_h.image_size);
		memcpy(bmp_all.pdata, bmp_blank.pdata, bmp_all.dib_h.image_size);
	}
	if (style.down_margin > 0) {
		create_blank_bmp(&bmp_blank,
				1,
				style.down_margin,
				bits_per_pix,
				color.bg_color);
		bmp_v_combin_3(&bmp_all, &bmp_blank, color.bg_color);
	}

	/*
	 * output
	 */
	output_bmp(stdout, &bmp_all);

	/*
	 * release
	 */
	if (bmp_blank.pdata) {
		free(bmp_blank.pdata);
		bmp_blank.pdata = NULL;
	}
	free(bmp_char.pdata);
	if (bmp_all.pdata) {
		free(bmp_all.pdata);
		bmp_all.pdata = NULL;
	}
	if (bmp_line.pdata) {
		free(bmp_line.pdata);
		bmp_line.pdata = NULL;
	}
	ret = munmap(addr_ascii_fd_in, (size_t) ascii_fd_stat.st_size);
	if (ret == -1) {
		perror("munmap");
		exit(1);
	}
	ret = munmap(addr_fd_in, (size_t) fd_stat.st_size);
	if (ret == -1) {
		perror("munmap");
		exit(1);
	}
	close(ascii_fd);
	close(font_fd);
	unmem_gb2312(mem_addr);
	if (in != stdin)
		fclose(in);
	return 0;
}
Exemplo n.º 7
0
/**
 * Set the response content-type
 * @param res HttpResponse object
 * @param mime Mime content type, e.g. text/html
 */
void set_content_type(HttpResponse res, const char *mime) {
  set_header(res, "Content-Type", mime);
}
Exemplo n.º 8
0
bool
bresultfile::open()
{
    if( m_fp != NULL )
    {
        fseek( m_fp, 0L, SEEK_SET );
    }

    m_header.version = RESULT_CUR_VERSION;
    m_header.format = 0;
    m_header.snp_names_length = 0;
    m_header.col_names_length = 0;
    m_header.num_pairs = 0;
    m_header.num_float_cols = 0;

    m_fp = fopen( m_path.c_str( ), m_mode.c_str( ) );
    if( m_fp == NULL )
    {
        return false;
    }

    if( m_mode == "r" )
    {
        size_t bytes_read = fread( &m_header, sizeof( result_header ), 1, m_fp );
        if( bytes_read != 1 || m_header.version != RESULT_CUR_VERSION )
        {
            fclose( m_fp );
            m_fp = NULL;
            return false;
        }

        char *buffer = (char *) malloc( m_header.snp_names_length );
        bytes_read = fread( buffer, 1, m_header.snp_names_length, m_fp );
        if( bytes_read != m_header.snp_names_length )
        {
            free( buffer );
            fclose( m_fp );
            m_fp = NULL;
            return false;
        }

        m_snp_names = unpack_string( buffer );
        free( buffer );

        buffer = (char *) malloc( m_header.col_names_length );
        bytes_read = fread( buffer, 1, m_header.col_names_length, m_fp );
        if( bytes_read != m_header.col_names_length )
        {
            free( buffer );
            fclose( m_fp );
            m_fp = NULL;
            return false;
        }

        m_col_names = unpack_string( buffer );
    }
    else
    {
        return set_header( m_col_names );
    }

    return m_fp != NULL;
}
Exemplo n.º 9
0
int process_command_file(uint8_t *params, uint8_t *result)
{

    int process_result = 0;
    HEADER header;
    get_header(&header,&params);
    uint8_t buffer[BUFFER_MAX];
    bzero(buffer,BUFFER_SIZE);
    memcpy(buffer,FILE_PATH,sizeof(FILE_PATH)-1);
    printf("process file header.func_id=%d\n",header.func_id);
    switch(header.func_id)
    {
    case FUNID_SDF_CREATEFILE:
        {
            int re = get_data(&params,buffer);
            if(re>0)
            {
                uint32_t buffer_size = get_int(&params);
                buffer[sizeof(FILE_PATH)-1+buffer_size] = '\0';
                uint32_t file_size = get_int(&params);
                if(!create_file(buffer,buffer_size, file_size))
                {
                    HEADER header;
                    header.func_id = FUNID_SDF_CREATEFILE;
                    header.data_size = 0;
                    header.param_sum = 0;
                    header.reserved = 0;
                    process_result+=set_header(&result,header);
                }
            }

            break;
        }
    case FUNID_SDF_DELETEFILE:
        {
            int re = get_data(&params,buffer);
            if(re>0)
            {
                uint32_t buffer_size = get_int(&params);
                buffer[sizeof(FILE_PATH)-1+buffer_size] = '\0';
                if(!delete_file(buffer,buffer_size))
                {
                    HEADER header;
                    header.func_id = FUNID_SDF_DELETEFILE;
                    header.data_size = 0;
                    header.param_sum = 0;
                    header.reserved = 0;
                    process_result+=set_header(&result,header);
                
                }
            }
            
            break;
        }
    case FUNID_SDF_READFILE:
        {
            int re = get_data(&params,buffer);
            if(re>0)
            {
                uint32_t buffer_size = get_int(&params);
                buffer[sizeof(FILE_PATH)-1+buffer_size] = '\0';
                uint32_t offset = get_int(&params);
                uint32_t read_len = get_int(&params);
                uint8_t my_buff[BUFFER_MAX];
                bzero(my_buff,BUFFER_SIZE);
                int size = read_file(buffer,buffer_size,offset,read_len,my_buff);
                if(size>0)
                {
                    HEADER header;
                    header.func_id = FUNID_SDF_READFILE;
                    header.data_size = sizeof(uint32_t)*3+size;
                    header.param_sum = 2;
                    header.reserved = 0;
                    process_result+=set_header(&result,header);
                    process_result+=set_int(&result,size);
                    process_result+=set_data(&result,my_buff,size);
                     
                }
            }

            break;
        }
    case FUNID_SDF_WRITEFILE:
        {
            int re = get_data(&params,buffer);
            if(re>0)
            {
                uint32_t buffer_size = get_int(&params);
                buffer[sizeof(FILE_PATH)-1+buffer_size] = '\0';
                uint32_t offset = get_int(&params);
                uint32_t write_len = get_int(&params);
                uint8_t my_buff[BUFFER_MAX];
                bzero(my_buff,BUFFER_SIZE);
                uint32_t my_buff_size = get_data(&params,my_buff);
                int size = write_file(buffer,buffer_size,offset,write_len,my_buff);
                if(size>0)
                {
                    HEADER header;
                    header.func_id = FUNID_SDF_WRITEFILE;
                    header.data_size = 0;
                    header.param_sum = 0;
                    header.reserved = 0;
                    process_result+=set_header(&result,header);
                     
                }
            }
            break;
        }
    default:
        break;
    }
}
Exemplo n.º 10
0
bool reply::set_header( const std::string& name, const std::string& value )
{
    return set_header( header( name, value ) );
}
Exemplo n.º 11
0
void ImageHeader::clear() {
  memset(&spider_header_, 0, sizeof(SpiderHeader));
  set_header();  // Set a consistent header
  reversed_ = false;
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
    int i = 0, rank, size;
    int numprocs;
    double avg_time = 0.0, max_time = 0.0, min_time = 0.0;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double timer=0.0;
    char *buffer=NULL;
    int po_ret;

    set_header(HEADER);
    set_benchmark_name("osu_bcast");
    enable_accel_support();
    po_ret = process_options(argc, argv);

    if (po_okay == po_ret && none != options.accel) {
        if (init_accel()) {
            fprintf(stderr, "Error initializing device\n");
            exit(EXIT_FAILURE);
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    switch (po_ret) {
        case po_bad_usage:
            print_bad_usage_message(rank);
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            print_help_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_version_message:
            print_version_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs < 2) {
        if (rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    if (options.max_message_size > options.max_mem_limit) {
        options.max_message_size = options.max_mem_limit;
    }

    if (allocate_buffer((void**)&buffer, options.max_message_size, options.accel)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }
    set_buffer(buffer, options.accel, 1, options.max_message_size);

    print_preamble(rank);

    for(size=options.min_message_size; size <= options.max_message_size; size *= 2) {
        if(size > LARGE_MESSAGE_SIZE) {
            options.skip = options.skip_large; 
            options.iterations = options.iterations_large;
        }

        timer=0.0;
        for(i=0; i < options.iterations + options.skip ; i++) {
            t_start = MPI_Wtime();
            MPI_Bcast(buffer, size, MPI_CHAR, 0, MPI_COMM_WORLD);
            t_stop = MPI_Wtime();

            if(i>=options.skip){
                timer+=t_stop-t_start;
            }
            MPI_Barrier(MPI_COMM_WORLD);

        }

        MPI_Barrier(MPI_COMM_WORLD);

        latency = (timer * 1e6) / options.iterations;

        MPI_Reduce(&latency, &min_time, 1, MPI_DOUBLE, MPI_MIN, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &avg_time, 1, MPI_DOUBLE, MPI_SUM, 0,
                MPI_COMM_WORLD);
        avg_time = avg_time/numprocs;

        print_stats(rank, size, avg_time, min_time, max_time);
    }

    free_buffer(buffer, options.accel);

    MPI_Finalize();

    if (none != options.accel) {
        if (cleanup_accel()) {
            fprintf(stderr, "Error cleaning up device\n");
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 13
0
void response::send() {
    if(!dont_send) {
      std::ostringstream r;

      const char *aeh = mg_get_header(conn, "Accept-Encoding");

      int data_length = contents.length();
      unsigned char * data = static_cast<unsigned char *>(malloc(data_length));
      std::copy(contents.begin(), contents.end(), data);

      if(aeh == NULL) {
        /* Do Nothing */
	std::cout << "No Accept-Encoding header." << std::endl;
      } else {
        std::vector<std::string> methods;
	boost::algorithm::split(methods, aeh, boost::algorithm::is_any_of(" ,"));

        for(std::vector<std::string>::const_iterator i = methods.begin();
	    i != methods.end();
	    ++i) {
          std::cout << *i << std::endl;
	}


	if(std::find(methods.begin(), methods.end(), "gzip") == methods.end()) {
          /* Do Nothing */
	  std::cout << "Encoding methods not supported." << std::endl;
	} else {
          z_stream z;
	  z.zalloc    = Z_NULL;
	  z.zfree     = Z_NULL;
	  z.opaque    = Z_NULL;
	  z.total_out = 0;
	  z.next_in   = data;
	  z.avail_in  = data_length;

	  int initError = deflateInit2(&z,
	                               Z_DEFAULT_COMPRESSION,
				       Z_DEFLATED,
				       (15+16), // Use gzip compression
				       8,
				       Z_DEFAULT_STRATEGY);  
	  if(initError != Z_OK) {
            /*switch(initError) {
              case Z_MEM_ERROR:

	      
	    }*/
	    /* There has been an error... */
	  } else {
	    int N = deflateBound(&z, z.avail_in);
            unsigned char * compressedData = static_cast<unsigned char*>(malloc(N));

	    int z_status;

            do {
	      z.next_out  = compressedData + z.total_out;
	      z.avail_out = N - z.total_out;

	      z_status = deflate(&z, Z_FINISH);

	    } while(z_status == Z_OK);
            
	    if(z_status != Z_STREAM_END) {
              /* There has been an error... */
	    } else {
              deflateEnd(&z);
	      free(data);
	      data = compressedData;
	      compressedData = NULL;
	      data_length = N;
	      set_header("Content-Encoding", "gzip");
	    }
	  }
	}
      }
      
      r << "HTTP/1.1 " << status_code << "\r\n"
	<< "Content-Type: " << type << "\r\n"
	<< "Content-Length: " << data_length << "\r\n";

      for(std::map<std::string, std::string>::const_iterator i = headers.begin();
          i != headers.end();
	  ++i) {
        r << i->first << ": " << i->second << "\r\n";
      }

      r << "\r\n";

      //std::cout << r.str() << std::endl;

      mg_write(conn, r.str().c_str(), r.str().length());
      mg_write(conn, data, data_length);

      free(data);
    }
}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
    setbuf(stdout, NULL);
    int i = 0, rank, size;
    int numprocs;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double tcomp = 0.0, tcomp_total = 0.0, latency_in_secs = 0.0;
    double timer = 0.0;
    double test_time = 0.0, test_total = 0.0;
    double wait_time = 0.0, init_time = 0.0;
    double init_total = 0.0, wait_total = 0.0;
    char *sendbuf = NULL;
    char *recvbuf = NULL;
    int po_ret;
    size_t bufsize;

    set_header(HEADER);
    set_benchmark_name("osu_igather");
    enable_accel_support();
    po_ret = process_options(argc, argv);

    if (po_okay == po_ret && none != options.accel) {
        if (init_accel()) {
            fprintf(stderr, "Error initializing device\n");
            exit(EXIT_FAILURE);
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Request request;
    MPI_Status status;

    switch (po_ret) {
        case po_bad_usage:
            print_bad_usage_message(rank);
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            print_help_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_version_message:
            print_version_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs < 2) {
        if (rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    if (options.max_message_size > options.max_mem_limit) {
        options.max_message_size = options.max_mem_limit;
    }

    if (0 == rank) {
        bufsize = options.max_message_size * numprocs;
        if (allocate_buffer((void**)&recvbuf, bufsize, options.accel)) {
            fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
            MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
        }
        set_buffer(recvbuf, options.accel, 1, bufsize);
    }

    if (allocate_buffer((void**)&sendbuf, options.max_message_size,
                options.accel)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }
    set_buffer(sendbuf, options.accel, 0, options.max_message_size);

    print_preamble_nbc(rank);

    for(size=options.min_message_size; size <= options.max_message_size; size *= 2) {
        if(size > LARGE_MESSAGE_SIZE) {
            options.skip = options.skip_large;
            options.iterations = options.iterations_large;
        }

        timer = 0.0;

        for(i=0; i < options.iterations + options.skip ; i++) {
            t_start = MPI_Wtime();
            MPI_Igather(sendbuf, size, MPI_CHAR,
                        recvbuf, size, MPI_CHAR,
                        0, MPI_COMM_WORLD, &request);
            MPI_Wait(&request,&status);

            t_stop = MPI_Wtime();

            if(i>=options.skip){
                timer += t_stop-t_start;
            }
            MPI_Barrier(MPI_COMM_WORLD);
        }

        MPI_Barrier(MPI_COMM_WORLD);

        latency = (timer * 1e6) / options.iterations;

        latency_in_secs = timer/options.iterations;

        init_arrays(latency_in_secs);

        MPI_Barrier(MPI_COMM_WORLD);

        timer = 0.0; tcomp_total = 0; tcomp = 0;
        init_total = 0.0; wait_total = 0.0;
	    test_time = 0.0, test_total = 0.0;

	    /* for loop with dummy_compute */
        for(i=0; i < options.iterations + options.skip ; i++) {
            t_start = MPI_Wtime();

            init_time = MPI_Wtime();
            MPI_Igather(sendbuf, size, MPI_CHAR,
                        recvbuf, size, MPI_CHAR,
                        0, MPI_COMM_WORLD, &request);
            init_time = MPI_Wtime() - init_time;

            tcomp = MPI_Wtime();
            test_time = dummy_compute(latency_in_secs, &request);
            tcomp = MPI_Wtime() - tcomp;

            wait_time = MPI_Wtime();
            MPI_Wait(&request,&status);
            wait_time = MPI_Wtime() - wait_time;

            t_stop = MPI_Wtime();

            if(i>=options.skip){
                timer += t_stop-t_start;
                tcomp_total += tcomp;
                test_total += test_time;
		        init_total += init_time;
                wait_total += wait_time;
            }
            MPI_Barrier(MPI_COMM_WORLD);
        }

        MPI_Barrier(MPI_COMM_WORLD);

        calculate_and_print_stats(rank, size, numprocs,
                                  timer, latency,
                                  test_total, tcomp_total,
                                  wait_total, init_total);
    }

    if (0 == rank) {
        free_buffer(sendbuf, options.accel);
    }
    free_buffer(recvbuf, options.accel);
    MPI_Finalize();

    if (none != options.accel) {
        if (cleanup_accel()) {
            fprintf(stderr, "Error cleaning up device\n");
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 15
0
/*
 * Initiate the communication with a remote site. When communication is
 * established create a minisocket through which the communication can be made
 * from now on.
 *
 * The first argument is the network address of the remote machine.
 *
 * The argument "port" is the port number on the remote machine to which the
 * connection is made. The port number of the local machine is one of the free
 * port numbers.
 *
 * Return value: the minisocket_t created, otherwise NULL with the errorcode
 * stored in the "error" variable.
 */
minisocket_t minisocket_client_create(network_address_t addr, int port, minisocket_error *error) {
	minisocket_t socket;
	// char* buffer;
	int local_port = CLIENT_MIN_PORT;
	// int synack_done;
	int /*send_attempts, timeout,*/ received_SYNACK;
	// network_address_t dest, my_address;
	mini_header_reliable_t hdr; // Header for sending MSG_SYNACK message
	// network_interrupt_arg_t* packet = NULL;

	// semaphore_P(skt_mutex);

	// Check for available ports
	if (used_client_ports >= NUM_CLIENT_PORTS) {
		fprintf(stderr, "ERROR: minisocket_client_create() unable to execute since no available ports exist\n");
		*error = SOCKET_NOMOREPORTS;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Check for valid arguments
	if (addr == NULL) {
		fprintf(stderr, "ERROR: minisocket_client_create() passed NULL network_address_t\n");
		*error = SOCKET_INVALIDPARAMS;
		// semaphore_V(skt_mutex);
		return NULL;
	}
	if (port < SERVER_MIN_PORT || port > SERVER_MAX_PORT) {
		fprintf(stderr, "ERROR: minisocket_client_create() passed invalid remote port number\n");
		*error = SOCKET_INVALIDPARAMS;
		// semaphore_V(skt_mutex);
		return NULL;
	}
	if (sockets[local_port] != NULL) {
		fprintf(stderr, "ERROR: minisocket_client_create() passed port already in use\n");
		*error = SOCKET_PORTINUSE;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Allocate new minisocket
	socket = malloc(sizeof(struct minisocket));
	if (socket == NULL) { // Could not allocate minisocket
		fprintf(stderr, "ERROR: minisocket_client_create() failed to malloc new minisocket\n");
		*error = SOCKET_OUTOFMEMORY;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Find next unused local port (guaranteed to exist due to counter and verification)
	while (local_port <= CLIENT_MAX_PORT && sockets[local_port] != NULL) {
		local_port++; 
	}
	if (sockets[local_port] != NULL) {
		fprintf(stderr, "ERROR: minisocket_client_create() ran out of available ports unexpectedly\n");
		*error = SOCKET_NOMOREPORTS;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Set fields in minisocket
	socket->active = 1;
	socket->local_port = local_port;
	socket->remote_port = port;
	network_address_copy(addr, socket->dest_address);
	socket->datagrams_ready = semaphore_create();
	semaphore_initialize(socket->datagrams_ready, 0);
	socket->sending = semaphore_create();
	semaphore_initialize(socket->sending, 1);
	socket->receiving = semaphore_create();
	semaphore_initialize(socket->receiving, 1);
	socket->timeout = semaphore_create();
	semaphore_initialize(socket->timeout, 0);
	socket->wait_syn = semaphore_create();
	semaphore_initialize(socket->wait_syn, 0);
	socket->incoming_data = queue_new();
	socket->seqnum = 0;
	socket->acknum = 0;
	socket->alarm = NULL;

	sockets[local_port] = socket; // Add socket to socket ports array
	used_client_ports++; // Increment client-ports-in-use counter

	// Send MSG_SYN packet to server
	// Wait timeout, if no response, repeat 7 more times (7 retries)

	// Allocate new header for SYN packet
	hdr = malloc(sizeof(struct mini_header_reliable));
	if (hdr == NULL) {	// Could not allocate header
		fprintf(stderr, "ERROR: minisocket_client_create() failed to malloc new mini_header_reliable\n");
		*error = SOCKET_OUTOFMEMORY;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	socket->seqnum++;

	// Assemble packet header
	set_header(socket, hdr, MSG_SYN);

	// Send SYN packet, expect SYNACK packet
	received_SYNACK = retransmit_packet(socket, (char*) hdr, 0, NULL, error);

	// semaphore_V(skt_mutex);

	if (received_SYNACK) {
		*error = SOCKET_NOERROR;
		return socket;
	} else {
		socket->active = 0;
		*error = SOCKET_RECEIVEERROR;
		return NULL;
	}
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
    int i = 0, rank;
    int numprocs;
    double avg_time = 0.0, max_time = 0.0, min_time = 0.0;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double timer=0.0;
    int po_ret;

    set_header(HEADER);
    set_benchmark_name("osu_barrier");
    enable_accel_support();
    po_ret = process_options(argc, argv);

    if (po_okay == po_ret && none != options.accel) {
        if (init_accel()) {
            fprintf(stderr, "Error initializing device\n");
            exit(EXIT_FAILURE);
        }
    }

    options.show_size = 0;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    switch (po_ret) {
        case po_bad_usage:
            print_bad_usage_message(rank);
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            print_help_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_version_message:
            print_version_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs < 2) {
        if(rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();

        return EXIT_FAILURE;
    }

    print_preamble(rank);

    options.skip = options.skip_large;
    options.iterations = options.iterations_large;
    timer = 0.0;

    for(i=0; i < options.iterations + options.skip ; i++) {
        t_start = MPI_Wtime();
        MPI_Barrier(MPI_COMM_WORLD);
        t_stop = MPI_Wtime();

        if(i>=options.skip){
            timer+=t_stop-t_start;
        }
    }

    MPI_Barrier(MPI_COMM_WORLD);

    latency = (timer * 1e6) / options.iterations;

    MPI_Reduce(&latency, &min_time, 1, MPI_DOUBLE, MPI_MIN, 0,
                MPI_COMM_WORLD);
    MPI_Reduce(&latency, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0,
                MPI_COMM_WORLD);
    MPI_Reduce(&latency, &avg_time, 1, MPI_DOUBLE, MPI_SUM, 0,
                MPI_COMM_WORLD);
    avg_time = avg_time/numprocs;

    print_stats(rank, 0, avg_time, min_time, max_time);
    MPI_Finalize();

    return EXIT_SUCCESS;
}
Exemplo n.º 17
0
/* 
 * Send a message to the other end of the socket.
 *
 * The send call should block until the remote host has ACKnowledged receipt of
 * the message.  This does not necessarily imply that the application has called
 * 'minisocket_receive', only that the packet is buffered pending a future
 * receive.
 *
 * It is expected that the order of calls to 'minisocket_send' implies the order
 * in which the concatenated messages will be received.
 *
 * 'minisocket_send' should block until the whole message is reliably
 * transmitted or an error/timeout occurs
 *
 * Arguments: the socket on which the communication is made (socket), the
 *            message to be transmitted (msg) and its length (len).
 * Return value: returns the number of successfully transmitted bytes. Sets the
 *               error code and returns -1 if an error is encountered.
 */
int minisocket_send(minisocket_t socket, minimsg_t msg, int len, minisocket_error *error) {
	int result, send_len;
	int bytes_sent;
	mini_header_reliable_t header;

	//DEBUG
	// char* the_msg = (char*) msg;
	// printf("msg: %s    length of msg to send: %i\n", msg, len);


	// Check for valid arguments
	if (socket == NULL) {
		fprintf(stderr, "ERROR: minisocket_send() passed NULL minisocket_t\n");
		*error = SOCKET_INVALIDPARAMS;
		// semaphore_V(skt_mutex);
		return -1;
	}
	if (msg == NULL) {
		fprintf(stderr, "ERROR: minisocket_send() passed NULL minimsg_t\n");
		*error = SOCKET_INVALIDPARAMS;
		// semaphore_V(skt_mutex);
		return -1;
	}

	// Allocate new header
	header = malloc(sizeof(struct mini_header_reliable));
	if (header == NULL) {	// Could not allocate header
		fprintf(stderr, "ERROR: minisocket_send() failed to malloc new mini_header_reliable\n");
		*error = SOCKET_OUTOFMEMORY;
		// semaphore_V(skt_mutex);
		return -1;
	}

	// Exclude other threads from sending from the same socket while I'm sending
	semaphore_P(socket->sending);

	bytes_sent = 0;
	// Fragment long messages into smaller packets
	while (bytes_sent < len) {
		socket->seqnum++;
		send_len = ((len - bytes_sent) > MAX_NETWORK_PKT_SIZE) ? MAX_NETWORK_PKT_SIZE : (len - bytes_sent); // Length of data to send in this packet
		set_header(socket, header, MSG_ACK);
		// printf("Message abt to be sent, length of it: (%s, %i)\n", the_msg[0](char*) msg, send_len);
		result = retransmit_packet(socket, (char*) header, send_len, (/*(char*)*/ msg) + bytes_sent, error);

		if (result == 1) { // ACK received (packet send successfully)
			bytes_sent += send_len;
		} else if (result == 0) { // All timeout attempts failed - close connection
			semaphore_V(socket->sending);
			minisocket_close(socket);
			return -1;
		} else { // Generic failure
			semaphore_V(socket->sending);
			return -1;
		}
	}

	semaphore_V(socket->sending);

	return 0;
}
Exemplo n.º 18
0
Arquivo: http.c Projeto: Limpan999/CHL
// Initialize standard headers
void headers_init() {
	set_header("Content-Type", "text/html");
	set_header("X-Powered-By", "CHL v.01 PRE ALPHA");
}
Exemplo n.º 19
0
/* 
 * Listen for a connection from somebody else. When communication link is
 * created return a minisocket_t through which the communication can be made
 * from now on.
 *
 * The argument "port" is the port number on the local machine to which the
 * client will connect.
 *
 * Return value: the minisocket_t created, otherwise NULL with the errorcode
 * stored in the "error" variable.
 */
minisocket_t minisocket_server_create(int port, minisocket_error *error) {
	minisocket_t socket;
	// char* buffer;
	// int syn_done;
	int /*send_attempts, timeout,*/ received_ACK;
	// network_address_t dest, my_address;
	mini_header_reliable_t hdr; // Header for sending MSG_SYNACK message
	// network_interrupt_arg_t* packet = NULL;

	// semaphore_P(skt_mutex);

	// Check for available ports
	if (used_server_ports >= NUM_SERVER_PORTS) {
		fprintf(stderr, "ERROR: minisocket_server_create() unable to execute since no available ports exist\n");
		*error = SOCKET_NOMOREPORTS;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Check for valid arguments
	if (port < SERVER_MIN_PORT || port > SERVER_MAX_PORT) {
		fprintf(stderr, "ERROR: minisocket_server_create() passed invalid port number\n");
		*error = SOCKET_INVALIDPARAMS;
		// semaphore_V(skt_mutex);
		return NULL;
	}
	if (sockets[port] != NULL) {
		fprintf(stderr, "ERROR: minisocket_server_create() passed port already in use\n");
		*error = SOCKET_PORTINUSE;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Allocate new minisocket
	socket = malloc(sizeof(struct minisocket));
	if (socket == NULL) { // Could not allocate minisocket
		fprintf(stderr, "ERROR: minisocket_server_create() failed to malloc new minisocket\n");
		*error = SOCKET_OUTOFMEMORY;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	// Set fields in minisocket
	socket->active = 0;
	socket->local_port = port;
	socket->datagrams_ready = semaphore_create();
	semaphore_initialize(socket->datagrams_ready, 0);
	socket->sending = semaphore_create();
	semaphore_initialize(socket->sending, 1);
	socket->receiving = semaphore_create();
	semaphore_initialize(socket->receiving, 1);
	socket->timeout = semaphore_create();
	semaphore_initialize(socket->timeout, 0);
	socket->wait_syn = semaphore_create();
	semaphore_initialize(socket->wait_syn, 0);
	socket->incoming_data = queue_new();
	socket->seqnum = 0;
	socket->acknum = 0;
	socket->alarm = NULL;

	sockets[port] = socket; // Add socket to socket ports array
	used_server_ports++; // Increment server-ports-in-use counter

	semaphore_P(socket->wait_syn);
	semaphore_initialize(socket->wait_syn, 0); // Handle case when count may be increased excessively due to extra packets coming in(?)

	// Send SYNACK w/ 7 retries
	// Allocate new header for SYNACK packet
	hdr = malloc(sizeof(struct mini_header_reliable));
	if (hdr == NULL) {	// Could not allocate header
		fprintf(stderr, "ERROR: minisocket_server_create() failed to malloc new mini_header_reliable\n");
		*error = SOCKET_OUTOFMEMORY;
		// semaphore_V(skt_mutex);
		return NULL;
	}

	socket->seqnum++;

	// Assemble packet header
	set_header(socket, hdr, MSG_SYNACK);

	// Send SYNACK packet, expect empty ACK packet
	received_ACK = retransmit_packet(socket, (char*) hdr, 0, NULL, error);

	// semaphore_V(skt_mutex);

	if (received_ACK == 1) {
		socket->alarm = NULL;		//No active retransmission alarm
		*error = SOCKET_NOERROR;
		return socket;
	} else {
		*error = SOCKET_RECEIVEERROR;
		return NULL;
	}
}
Exemplo n.º 20
0
 void httpclient::parse_uri()
 {
     std::string surl;
     std::string::size_type x, y;
     protocol = "http";
     user = "";
     password = "";
     port = "80";
     x = uri.find("://");
     if (x != std::string::npos)
     {
         protocol = uri.substr(0, x);
         surl = uri.substr(x + 3);
     }
     else
     {
         surl = uri;
     }
     std::transform(protocol.begin(), protocol.end(), protocol.begin(), tolower);
     if (protocol == "https")
     {
         port = "443";
     }
     x = surl.find('@');
     y = surl.find('/');
     if ((x != std::string::npos) && ((x < y) || (y == std::string::npos)))
     {
         user = surl.substr(0, x);
         surl.erase(0, x + 1);
         x = user.find(':');
         if (x != std::string::npos)
         {
             password = user.substr(x + 1);
             user.erase(x);
         }
     }
     x = surl.find('/');
     if (x != std::string::npos)
     {
         host = surl.substr(0, x);
         surl.erase(0, x + 1);
     }
     else
     {
         host = surl;
         surl = "";
     }
     bool ipv6 = host[0] == '[';
     if (ipv6)
     {
         x = host.find(']');
         if ((x + 1 < host.size()) && (host[x + 1] == ':'))
         {
             port = host.substr(x + 2);
         }
         host = host.substr(1, x - 1);
     }
     else
     {
         x = host.find(':');
         if (x != std::string::npos)
         {
             port = host.substr(x + 1);
             host.erase(x);
         }
     }
     set_header("Host", (ipv6 ? ('[' + host + ']') : host) + ((port == "80") ? std::string() : (':' + port)));
     x = surl.find('?');
     if (x != std::string::npos)
     {
         path = '/' + surl.substr(0, x);
     }
     else
     {
         path = '/' + surl;
     }
     if (host == "")
     {
         host = "localhost";
     }
 }
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    int i, numprocs, rank, size, align_size;
    int skip;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double timer=0.0;
    double avg_time = 0.0, max_time = 0.0, min_time = 0.0;
    float *sendbuf, *recvbuf;
    int *recvcounts;
    int po_ret;
    size_t bufsize;

    set_header(HEADER);
    set_benchmark_name("osu_scatter");
    enable_accel_support();
    po_ret = process_options(argc, argv);

    if (po_okay == po_ret && none != options.accel) {
        if (init_accel()) {
            fprintf(stderr, "Error initializing device\n");
            exit(EXIT_FAILURE);
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    switch (po_ret) {
        case po_bad_usage:
            print_bad_usage_message(rank);
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            print_help_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_version_message:
            print_version_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs < 2) {
        if (rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    if (options.max_message_size > options.max_mem_limit) {
        options.max_message_size = options.max_mem_limit;
    }

    if (allocate_buffer((void**)&recvcounts, numprocs*sizeof(int), none)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }

    bufsize = sizeof(float)*(options.max_message_size/sizeof(float));
    if (allocate_buffer((void**)&sendbuf, bufsize, options.accel)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }
    set_buffer(sendbuf, options.accel, 1, bufsize);

    bufsize = sizeof(float)*((options.max_message_size/numprocs + 1)/sizeof(float));
    if (allocate_buffer((void**)&recvbuf, bufsize,
                options.accel)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }
    set_buffer(recvbuf, options.accel, 0, bufsize);

    print_preamble(rank);

    for(size=1; size*sizeof(float)<= options.max_message_size; size *= 2) {

        if(size > LARGE_MESSAGE_SIZE) {
            skip = SKIP_LARGE;
            options.iterations = options.iterations_large;
        } else {
            skip = SKIP;
        }

        int portion=0, remainder=0;
        portion=size/numprocs;
        remainder=size%numprocs;

        for (i=0; i<numprocs; i++){
            recvcounts[i]=0;
            if(size<numprocs){ 
                if(i<size)
                    recvcounts[i]=1;
            }
            else{
                if((remainder!=0) && (i<remainder)){
                    recvcounts[i]+=1;
                }
                recvcounts[i]+=portion;
            }
        }
        MPI_Barrier(MPI_COMM_WORLD);
        
        timer=0.0;
        for(i=0; i < options.iterations + skip ; i++) {
            t_start = MPI_Wtime();

            MPI_Reduce_scatter( sendbuf, recvbuf, recvcounts, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD );
            t_stop=MPI_Wtime();
            if(i>=skip){

            timer+=t_stop-t_start;
            } 
            MPI_Barrier(MPI_COMM_WORLD);  
        }
        latency = (double)(timer * 1e6) / options.iterations;

        MPI_Reduce(&latency, &min_time, 1, MPI_DOUBLE, MPI_MIN, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &avg_time, 1, MPI_DOUBLE, MPI_SUM, 0,
                MPI_COMM_WORLD);
        avg_time = avg_time/numprocs;

        print_stats(rank, size, avg_time, min_time, max_time);
        MPI_Barrier(MPI_COMM_WORLD);
    }

    free_buffer(recvcounts, none);
    free_buffer(sendbuf, options.accel);
    free_buffer(recvbuf, options.accel);

    MPI_Finalize();

    if (none != options.accel) {
        if (cleanup_accel()) {
            fprintf(stderr, "Error cleaning up device\n");
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}