Пример #1
0
/* This test check append mode initial position (a/a+) based on POSIX defition
   (BZ#6544 and BZ#13151) for buffer without null byte end.  */
static int
do_test_write_append_without_null (const char *mode)
{
  char buf[] = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 };
  char exp[] = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 };

  /* If '\0' is not found in buffer, POSIX states that SEEK_SET should be
     the size argument.  */
  FILE *fp = fmemopen (buf, sizeof (buf) - 2, "a");

  fflush (fp);
  fputc (0x70, fp);
  fseek (fp, 0, SEEK_SET);
  fputc (0x70, fp);
  fputc (0x70, fp);
  fclose (fp);

  /* POSIX also states that a write operation on the stream shall not advance
     the current buffer size beyond the size given in fmemopen, so the string
     should be same.  */
  if (memcmp (buf, exp, sizeof (buf)) != 0)
    {
      printf ("%s: check failed: ", __FUNCTION__);
      print_buffer (buf, sizeof (buf));
      printf ("!= ");
      print_buffer (exp, sizeof (exp));
      printf ("\n");
      return 1;
    }

  return 0;
}
Пример #2
0
int Base64Decode(char* b64message, char** buffer, int *decl) { //Decodes a base64 encoded string
    BIO *bio, *b64;
    int decodeLen = calcDecodeLength(b64message),
            len = 0;
    *buffer = (char*)malloc(decodeLen+1);
    FILE* stream = fmemopen(b64message, strlen(b64message), "r");
    memset(*buffer, 0x00, decodeLen+1);

    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new_fp(stream, BIO_NOCLOSE);
    // bio = BIO_new_mem_buf(b64message,strlen(b64message) );
    bio = BIO_push(b64, bio);
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer
    len = BIO_read(bio, *buffer, strlen(b64message));
    //Can test here if len == decodeLen - if not, then return an error
    //(*buffer)[len] = '\0';

    // BIO_free(b64);
    BIO_free_all(bio);

    fclose(stream);

    *decl = len;
    return (0); //success
}
Пример #3
0
/*!
 *  pixReadMemJp2k()
 *
 *      Input:  data (const; jpeg-encoded)
 *              size (of data)
 *              reduction (scaling factor: 1, 2, 4, 8)
 *              box  (<optional> for extracting a subregion), can be null
 *              hint (a bitwise OR of L_JP2K_* values; 0 for default)
 *              debug (output callback messages, etc)
 *      Return: pix, or null on error
 *
 *  Notes:
 *      (1) This crashes when reading through the fmemopen cookie.
 *          Until we can fix this, we use the file-based work-around.
 *          And fixing this may take some time, because the basic
 *          stream interface is no longer supported in openjpeg.
 *      (2) See pixReadJp2k() for usage.
 */
PIX *
pixReadMemJp2k(const l_uint8  *data,
               size_t          size,
               l_uint32        reduction,
               BOX            *box,
               l_int32         hint,
               l_int32         debug)
{
FILE     *fp;
PIX      *pix;

    PROCNAME("pixReadMemJp2k");

    if (!data)
        return (PIX *)ERROR_PTR("data not defined", procName, NULL);

#if 0  /* Avoid the crash for now */
    if ((fp = fmemopen((void *)data, size, "r")) == NULL)
        return (PIX *)ERROR_PTR("stream not opened", procName, NULL);
#else
    L_WARNING("work-around: writing to a temp file\n", procName);
    if ((fp = tmpfile()) == NULL)
        return (PIX *)ERROR_PTR("tmpfile stream not opened", procName, NULL);
    fwrite(data, 1, size, fp);
    rewind(fp);
#endif  /* HAVE_FMEMOPEN */
    pix = pixReadStreamJp2k(fp, reduction, box, hint, debug);
    fclose(fp);
    if (!pix) L_ERROR("pix not read\n", procName);
    return pix;
}
Пример #4
0
Файл: stream.c Проект: epa/lrzip
static int zpaq_decompress_buf(struct stream *s)
{
	uchar *c_buf;
	FILE *in, *out;
	size_t dlen;

	in = fmemopen(s->buf, s->buflen, "r");
	if (!in) {
		err_msg("Failed to fmemopen in zpaq_decompress_buf\n");
		return -1;
	}
	out = open_memstream((char **)&c_buf, &dlen);
	if (!out) {
		err_msg("Failed to open_memstream in zpaq_decompress_buf\n");
		return -1;
	}

	zpipe_decompress(in, out, control.msgout, s->buflen, (int)(control.flags & FLAG_SHOW_PROGRESS));

	if (memstream_update_buffer(out, &c_buf, &dlen) != 0)
	        fatal("Failed to memstream_update_buffer in zpaq_decompress_buf");

	fclose(in);
	fclose(out);
	free(s->buf);
	s->buf = c_buf;

	if ((i64)dlen != s->buflen) {
		err_msg("Inconsistent length after decompression. Got %d bytes, expected %d\n", dlen, s->buflen);
		return -1;
	}

	return 0;
}
Пример #5
0
bool WebServiceFSM::postJson(JsonObject& msg) {
  // .printTo stupidly writes a '\0' in its last position, so any destination
  // printed to must ask for one more than the strlen of the JSON.
  char to_server[MAX_MSG_SIZE];
  msg.printTo(to_server, 1+msg.measureLength());
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, to_server);

  char from_server[MAX_MSG_SIZE];
  auto fin = fmemopen(from_server, MAX_MSG_SIZE, "w");

  curl_easy_setopt(curl, CURLOPT_WRITEDATA, fin);

  res = curl_easy_perform(curl);
  fclose(fin);

  // Check for errors
  if(res != CURLE_OK) {
    fprintf(stderr, "WebQ: Failed to access %s: %s\n", "localhost",
        curl_easy_strerror(res));
  }
  else {
    fprintf(stderr, "WebQ: Connection successful, received '%s'\n", from_server);
  }

  return res == CURLE_OK;
}
Пример #6
0
Файл: stream.c Проект: epa/lrzip
static void zpaq_compress_buf(struct stream *s, int *c_type, i64 *c_len)
{
	uchar *c_buf;
	FILE *in, *out;
	size_t dlen;

	if (!lzo_compresses(s))
		return;

	in = fmemopen(s->buf, s->buflen, "r");
	if (!in)
		fatal("Failed to fmemopen in zpaq_compress_buf\n");
	out = open_memstream((char **)&c_buf, &dlen);
	if (!out)
		fatal("Failed to open_memstream in zpaq_compress_buf\n");

	zpipe_compress(in, out, control.msgout, s->buflen, (int)(control.flags & FLAG_SHOW_PROGRESS));

	if (memstream_update_buffer(out, &c_buf, &dlen) != 0)
	        fatal("Failed to memstream_update_buffer in zpaq_compress_buf");

	fclose(in);
	fclose(out);

	if ((i64)dlen >= *c_len) {
		/* Incompressible, leave as CTYPE_NONE */
		free(c_buf);
		return;
	}

	*c_len = dlen;
	free(s->buf);
	s->buf = c_buf;
	*c_type = CTYPE_ZPAQ;
}
Пример #7
0
void
test_binary()
{
	/*
	 * Make sure that NULL bytes are never appended when opening a buffer
	 * in binary mode.
	 */

	FILE *fp;
	char buf[20];
	char str[] = "Test";
	size_t nofw;
	int rc, i;

	/* Pre-fill the buffer. */
	memset(buf, 'A', sizeof(buf));

	/* Open a FILE * in binary mode. */
	fp = fmemopen(buf, sizeof(buf), "w+b");
	assert(fp != NULL);

	/* Write some data into it. */
	nofw = fwrite(str, 1, strlen(str), fp);
	assert(nofw == strlen(str));

	/* Make sure that the buffer doesn't contain any NULL bytes. */
	for (i = 0; i < sizeof(buf); i++)
		assert(buf[i] != '\0');

	/* Close the FILE *. */
	rc = fclose(fp);
	assert(rc == 0);
}
Пример #8
0
/* This test check for fseek (SEEK_END) using negative offsets (BZ#14292).  The
   starting position of descriptor is different base on the opening mode.  */
static int
do_test_read_seek_neg (const char *mode, const char *expected)
{
  char buf[] = "abcdefghijklmnopqrstuvxz0123456789";
  char tmp[10];
  size_t tmps = sizeof (tmps);
  long offset = -11;

  FILE *fp = fmemopen (buf, sizeof (buf), mode);
  fseek (fp, offset, SEEK_END);
  fread (tmp, tmps, 1, fp);

  if (memcmp (tmp, expected, tmps) != 0)
    {
      printf ("%s: fmemopen(%s) - fseek (fp, %li, SEEK_END):\n",
	      __FUNCTION__, mode, offset);
      printf ("  returned: ");
      print_buffer (tmp, tmps);
      printf ("\n");
      printf ("  expected: ");
      print_buffer (expected, tmps);
      printf ("\n");
      return 1;
    }

  fclose (fp);

  return 0;
}
Пример #9
0
int ccv_read_impl(const void* in, ccv_dense_matrix_t** x, int type, int rows, int cols, int scanline)
{
	FILE* fd = 0;
	if (type & CCV_IO_ANY_FILE)
	{
		assert(rows == 0 && cols == 0 && scanline == 0);
		fd = fopen((const char*)in, "rb");
		if (!fd)
			return CCV_IO_ERROR;
		return _ccv_read_and_close_fd(fd, x, type);
	} else if (type & CCV_IO_ANY_STREAM) {
		assert(rows > 8 && cols == 0 && scanline == 0);
		assert((type & 0xFF) != CCV_IO_DEFLATE_STREAM); // deflate stream (compressed stream) is not supported yet
#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L || defined(__APPLE__) || defined(BSD)
		// this is only supported by glibc
#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
		fd = fmemopen((void*)in, (size_t)rows, "rb");
#else
		ccv_io_mem_t mem = {
			.size = rows,
			.pos = 0,
			.buffer = (char*)in,
		};
		fd = funopen(&mem, readfn, 0, seekfn, 0);
#endif
		if (!fd)
			return CCV_IO_ERROR;
		// mimicking itself as a "file"
		type = (type & ~0x10) | 0x20;
		return _ccv_read_and_close_fd(fd, x, type);
#endif
	} else if (type & CCV_IO_ANY_RAW) {
Пример #10
0
int
base64_decode(const char *b64message, const size_t length, unsigned char **buffer) {
	BIO *bio;
	BIO *b64;
	int decodedLength = calc_decode_length(b64message, length);

	*buffer = (unsigned char*)malloc(decodedLength+1);
	if(*buffer == NULL) {
		fprintf(stderr, "Failed to allocate memory\n");
		exit(1);
	}
	FILE* stream = fmemopen((char*)b64message, length, "r");

	b64 = BIO_new(BIO_f_base64());
	bio = BIO_new_fp(stream, BIO_NOCLOSE);
	bio = BIO_push(b64, bio);
	BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
	decodedLength = BIO_read(bio, *buffer, length);
	(*buffer)[decodedLength] = '\0';

	BIO_free_all(bio);
	fclose(stream);

	return decodedLength;
}
Пример #11
0
int
main ( int argc, char** argv )
{
  FILE* file = fmemopen( data, sizeof(data), "r" );
  if ( file == NULL )
  {
    printf("fmemopen failed\n");
    return (-1);
  }

  char* copy = (char*)alloca( sizeof(data ) );
  int read_result = fread( copy, sizeof(data), 1, file );
  if ( read_result == 1 )
  {
    printf("%s\n", copy );
  }
  else
  {
    printf("read failed result=%d\n",read_result);
  }
  int close_result = fclose(file);
  if ( close_result != 0 )
  {
    printf("close failed result=%d\n",close_result);
  }

  return ( 0 );
}
Пример #12
0
FILE *fopenstr (const char *str)
{
  /* strlen(str) instead of strlen(str) + 1 because files shouldn't appear
   * null-terminated. Cast away constness because we're in read mode, but the
   * fmemopen prototype has no way to express that. */
  return fmemopen ( (char *) str, strlen (str), "r");
}
Пример #13
0
Файл: 5.15.c Проект: kaiiak/APUE
int main(void)
{
	FILE *fp;
	char buf[BSZ];

	memset(buf, 'a', BSZ-2);
	buf[BSZ - 2] = '\0';
	buf[BSZ - 1] = 'X';
	if ((fp = fmemopen(buf, BSZ, "w+")) == NULL)
		err_sys("fmemopen failed");
	printf("initial buffer contents: %s\n", buf);
	fprintf(fp, "hello world");
	printf("bufore flush: %s\n", buf);
	fflush(fp);
	printf("after fflush: %s\n", buf);
	printf("len of string in buf = %ld\n", (long)strlen(buf));

	memset(buf, 'b', BSZ-2);
	buf[BSZ - 2] = '\0';
	buf[BSZ - 1] = 'X';
	fprintf(fp, "hello, world");
	fseek(fp, 0, SEEK_SET);
	printf("after fseek: %s\n", buf);
	printf("len of string in buf = %ld\n", (long)strlen(buf));

	memset(buf, 'c', BSZ-2);
	buf[BSZ - 2] = '\0';
	buf[BSZ - 1] = 'X';
	fprintf(fp, "hello world");
	fclose(fp);
	printf("after fclose: %s\n", buf);
	printf("len of string in buf = %ld\n", (long)strlen(buf));

	return 0;
}
Пример #14
0
void H2DReader::load_str(char* mesh_str, Mesh *mesh)
{
  // open the mesh file
  FILE* f = fmemopen(mesh_str, strlen(mesh_str), "r");
  if (f == NULL) error("Could not create the read buffer");
  this->load_stream(f, mesh);
}
Пример #15
0
void test_parser_print_three_way_points() {
	char expected_description[32] = "points N-SE N-S N-SW";
	char actual_description[32];
	FILE* out = fmemopen(actual_description, 32*sizeof(char), "w");

	sem_tile tile;

	sem_track trackN_S;
	sem_track_set(&trackN_S, SEM_NORTH, SEM_SOUTH);
	sem_tile_set_points(&tile, &trackN_S);

	sem_track trackN_SE;
	sem_track_set(&trackN_SE, SEM_NORTH, SEM_SOUTH | SEM_EAST);
	tile.points[1] = &trackN_SE;	

	sem_track trackN_SW;
	sem_track_set(&trackN_SW, SEM_NORTH, SEM_SOUTH | SEM_WEST);
	tile.points[2] = &trackN_SW;	

	sem_tile_switch_points(&tile);
	sem_tile_print(out, &tile);

	fclose(out);

	g_assert_cmpstr(expected_description, ==, actual_description);
}
PyObject*
PyGccPrettyPrinter_New(void)
{
    struct PyGccPrettyPrinter *obj;

    obj = PyObject_New(struct PyGccPrettyPrinter, &PyGccPrettyPrinter_TypeObj);
    if (!obj) {
	return NULL;
    }
    
    //printf("PyGccPrettyPrinter_New\n");

    /* Gross hack for getting at a FILE* ; rewrite using fopencookie? */
    obj->buf[0] = '\0';
    obj->file_ptr = fmemopen(obj->buf, sizeof(obj->buf), "w");

#if (TARGET_GCC_VERSION >= 4009)
    /* GCC 4.9 eliminated pp_construct in favor of a C++ ctor.
       Use placement new to run it on obj->pp.  */
    new ((void*)&obj->pp) pretty_printer(NULL, 0);
#else
    pp_construct(&obj->pp, /* prefix */NULL, /* line-width */0);
#endif
    pp_needs_newline(&obj->pp) = false;
    pp_translate_identifiers(&obj->pp) = false;

    /* Connect the pp to the (FILE*): */
    obj->pp.buffer->stream = obj->file_ptr;

    //printf("PyGccPrettyPrinter_New returning: %p\n", obj);
    
    return (PyObject*)obj;
}
Пример #17
0
static int
do_test (void)
{
  int ch;
  FILE *stream;
  int ret = 0;

  mtrace ();

  stream = fmemopen (buffer, strlen (buffer), "r+");

  while ((ch = fgetc (stream)) != EOF)
    printf ("Got %c\n", ch);

  fputc ('1', stream);
  if (fflush (stream) != EOF || errno != ENOSPC)
    {
      printf ("fflush didn't fail with ENOSPC\n");
      ret = 1;
    }

  fclose (stream);

  return ret + do_bz18820 ();
}
Пример #18
0
modulepath = /usr/lib/apache2/modules";

void fmemopen_test()
{
  size_t count=0;
  ssize_t len;
  char *line=NULL;
  size_t linecap=0;

  FILE *fp = fmemopen((void*)data,strlen(data),"r");
  if (fp==NULL)
    err(1,"fmemopen failed");

  while ((len = getline(&line, &linecap, fp)) > 0) {
    if (line[len-1]=='\n') {
      line[len-1]=0;
      --len;
    }
    ++count;

    printf("line %zu: %s\n", count, line);
  }
  if (ferror(fp))
    err(1,"memfile read error");

  if (fclose(fp)!=0)
    err(1,"fclose");

  free(line);
}
Пример #19
0
char*
base64_encode(const unsigned char *message, const size_t length) {
	BIO *bio;
	BIO *b64;
	FILE* stream;

	int encodedSize = 4*ceil((double)length/3);
	char *buffer = (char*)malloc(encodedSize+1);
	if(buffer == NULL) {
		fprintf(stderr, "Failed to allocate memory\n");
		exit(1);
	}

	stream = fmemopen(buffer, encodedSize+1, "w");
	b64 = BIO_new(BIO_f_base64());
	bio = BIO_new_fp(stream, BIO_NOCLOSE);
	bio = BIO_push(b64, bio);
	BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
	BIO_write(bio, message, length);
	(void)BIO_flush(bio);
	BIO_free_all(bio);
	fclose(stream);

	return buffer;
}
Пример #20
0
static FILE *open_config_file(char **filename) {
	assert(filename != NULL);

	char *config = getenv("MACSPOOF_CONFIG");
	if (config != NULL) {
		*filename = "<none>";
		FILE *file = fmemopen(config, strlen(config), "r");
		if (file == NULL) perror_die("fmemopen");
		return file;
	}

	*filename = getenv("MACSPOOF_CONFIG_FILE");
	if (*filename != NULL) {
		FILE *file = fopen(*filename, "r");
		if (file == NULL) perror_die("fopen");
		return file;
	}

	*filename = "~/.macspoofrc";
	FILE *file = fopen(*filename, "r");
	if (file != NULL) return file;

	*filename = MACSPOOF_ETCDIR "/macspoof.conf";
	file = fopen(*filename, "r");
	if (file == NULL) {
		perror("fopen");
		die("Cannot open any config file.");
	}
	return file;
}
Пример #21
0
static int
init_plugins_conf()
{
	int fd;
	FILE *fp;
	struct stat st;
	char buf[2048], *tmp;
	
	fd = open(PLUGIN_CONF, O_RDONLY);
	if (fd < 0) {
		perror("open");
		bot_warning("open %s failed", PLUGIN_CONF);
		return -1;
	}
	if (fstat(fd, &st) == -1) {
		perror("stat");
		bot_warning("state %s failed", PLUGIN_CONF);
		return -1;
	}

	/* 配置文件未被修改,不重新载入 */
	if (p.mtime == st.st_mtime) { 
		return 0;
	}

	if (p.content != NULL) {
		free(p.content);
	}
	p.content = (char *)malloc(st.st_size + 1);
	p.content[st.st_size] = '\0';
	if (read(fd, p.content, st.st_size) != st.st_size) {
		perror("read");
		bot_warning("read %s failed", PLUGIN_CONF);
		return -1;
	}


	p.size = st.st_size;
	p.mtime = st.st_mtime;

	fp = fmemopen(p.content, p.size, "r");
	while (fgets(buf, sizeof(buf), fp)) {
		tmp = strchr(buf, '#');
		if (tmp) *tmp = '\0';
		tmp = buf;
		while (isblank(*tmp)) tmp++;
		if (!strncasecmp(tmp, "plugins", 7)) {
			char *str = strtok(tmp, "\"");
			str = strtok(NULL, "\"");
			snprintf(p.plugins, sizeof(p.plugins), "%s", str);
			break;
		}
	}
	bot_debug("Plugins: %s", p.plugins);

	fclose(fp);
	close(fd);
	return 0;
}
Пример #22
0
void
influxdb_put(const char *id, double value)
{
  char url[1024];
  cfg_root(root);

  const char *urlprefix = cfg_get_str(root, CFG("influxdb", "url"), NULL);
  const char *db        = cfg_get_str(root, CFG("influxdb", "db"), NULL);
  const char *username  = cfg_get_str(root, CFG("influxdb", "username"), NULL);
  const char *password  = cfg_get_str(root, CFG("influxdb", "password"), NULL);
  if(urlprefix == NULL || db == NULL || username == NULL || password == NULL)
    return;

  snprintf(url, sizeof(url), "%s/db/%s/series?u=%s&p=%s",
           urlprefix, db, username, password);

  htsmsg_t *doc = htsmsg_create_list();
  htsmsg_t *item = htsmsg_create_map();

  htsmsg_add_str(item, "name", id);

  htsmsg_t *columns = htsmsg_create_list();
  htsmsg_add_str(columns, NULL, "value");
  htsmsg_add_msg(item, "columns", columns);

  htsmsg_t *points = htsmsg_create_list();
  htsmsg_t *point = htsmsg_create_list();
  htsmsg_add_dbl(point, NULL, value);
  htsmsg_add_msg(points, NULL, point);
  htsmsg_add_msg(item, "points", points);

  htsmsg_add_msg(doc, NULL, item);

  char *data = htsmsg_json_serialize_to_str(doc, 0);
  htsmsg_destroy(doc);

  size_t len = strlen(data);

  FILE *f = fmemopen(data, len, "r");

  CURL *curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &libsvc_curl_waste_output);
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  curl_easy_setopt(curl, CURLOPT_READDATA, (void *)f);
  curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)len);

  CURLcode result = curl_easy_perform(curl);

  curl_easy_cleanup(curl);

  if(result)
    trace(LOG_ERR, "CURL Failed %s error %d", url, result);
  fclose(f);
  free(data);
}
Пример #23
0
int
simpletest(void)
{
	FILE	*s1, *s2;
	char	 string[] = "fmemopen test string!";
	char	 buffer[1024], *buf = NULL;
	size_t	 len;
	int	 c, failures = 0;

	s1 = fmemopen(string, strlen(string) + 1, "r");
	if (s1 == NULL) {
		warn("unable to open a stream s1");
		return (1);
	}

	s2 = fmemopen(buf, 22, "w+");
	if (s2 == NULL) {
		warn("unable to create a stream s2");
		fclose(s1);
		return (1);
	}

	while ((c = fgetc(s1)) != EOF)
		fputc(c, s2);

	if (ftell(s2) != strlen(string) + 1) {
		warnx("failed copy test (1)");
		failures++;
	}
	fclose(s1);

	fseek(s2, 0, SEEK_SET);
	if (ftell(s2) != 0) {
		warnx("failed seek test (2)");
		failures++;
	}

	len = fread(buffer, 1, sizeof(buffer) - 1, s2);
	if (len != strlen(string) + 1) {
		warnx("failed read test (3) %zu != %zu",
		    len, strlen(string) + 1);
		failures++;
	}

	return (failures);
}
Пример #24
0
int
writetest(void)
{
	FILE	*s1;
	char	 string[] = "super test number 3";
	char	 buffer[256];
	size_t	 len, slen;
	int	 failures = 0;

	slen = strlen(string) + 1;

	s1 = fmemopen(string, slen, "w");
	if (s1 == NULL)
		return (1);

	len = fwrite("short", 1, 5, s1);
	if (len != strlen("short")) {
		warnx("failed write test (9)");
		failures++;
	}
	fclose(s1);

	s1 = fmemopen(string, slen, "r");
	if (s1 == NULL) {
		warnx("failed open test (10)");
		failures++;
	}

	len = fread(buffer, 1, sizeof(buffer) - 1, s1);
	if (strncmp(string, buffer, len)) {
		warnx("failed compare test (11)");
		failures++;
	}

	if (strcmp(string, "short")) {
		warnx("failed compare test (12)");
		failures++;
	}

	if (strcmp(string + strlen(string) + 1, "test number 3")) {
		warnx("failed compare test (13)");
		failures++;
	}

	return (failures);
}
Пример #25
0
/*
 * Test successful coalesce
 */
void test_cbt_util_coalesce_success(void **state)
{
	int result;
	int file_size;
	char* args[] = { "cbt-util", "coalesce", "-p", "test_parent.log", "-c" , "test_child.log"};
	void *parent_data;
	void *child_data;
	struct fwrite_data *output;
	uint64_t size = 4194304;

	uint64_t bmsize = bitmap_size(size);
	file_size = sizeof(struct cbt_log_metadata) + bmsize;
	parent_data = malloc(file_size);
	child_data = malloc(file_size);

	//Intialise size in metadata file
	((struct cbt_log_metadata*)parent_data)->size = size;
	//Fill bitmap with random bytes
	memcpy(parent_data + sizeof(struct cbt_log_metadata), (void*)memcpy, bmsize );
	FILE *parent_log = fmemopen((void*)parent_data, file_size, "r");

	//Intialise size in metadata file
	((struct cbt_log_metadata*)child_data)->size = size;
	//Fill bitmap with random bytes
	memcpy(child_data + sizeof(struct cbt_log_metadata), (void*)memcpy, bmsize );
	FILE *child_log = fmemopen((void*)child_data, file_size, "r");

	will_return(__wrap_fopen, parent_log);
	expect_value(__wrap_fclose, fp, parent_log);
	will_return(__wrap_fopen, child_log);
	expect_value(__wrap_fclose, fp, child_log);
	enable_mock_fwrite();
	output = setup_fwrite_mock(bmsize);

	result = cbt_util_coalesce(6, args);
	// OR the contents of bitmap of both files
	*((char *)child_data + sizeof(struct cbt_log_metadata))
				|= *((char *)parent_data + sizeof(struct cbt_log_metadata));
	assert_int_equal(result, 0);
	assert_memory_equal(output->buf,
				child_data + sizeof(struct cbt_log_metadata), bmsize);

	free_fwrite_data(output);
	free(parent_data);
	free(child_data);
}
Пример #26
0
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {
	if (size > 0) {
		str[size - 1] = '\0';
		FILE * stream = fmemopen(str, size, "r");
		return vfprintf(stream, format, ap);
	}
	return 0;
}
Пример #27
0
static int send_email(struct email *email)
{
    CURL *curl;
    char *smtp_url;
    FILE *email_body;

    CURLcode result = CURLE_OK;
    struct curl_slist *rec = NULL;

    curl = curl_easy_init();

    if (!curl)
    {
        return 1;
    }

    if (email->verbose)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    }

    smtp_url = get_server_url(email);

    curl_easy_setopt(curl, CURLOPT_URL, smtp_url);

    curl_easy_setopt(curl, CURLOPT_USERNAME, email->user);

    curl_easy_setopt(curl, CURLOPT_PASSWORD, email->password);

    curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
    
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, email->from_addr);

    rec = curl_slist_append(rec, email->to_addr);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, rec);

    email_body = fmemopen(email->body, strlen(email->body), "r");

    curl_easy_setopt(curl, CURLOPT_READDATA, email_body);

    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

    result = curl_easy_perform(curl);

    free(smtp_url);
    fclose(email_body);
    curl_slist_free_all(rec);
    curl_easy_cleanup(curl);

    if (result != CURLE_OK)
    {
        fprintf(stderr, "%s\n", curl_easy_strerror(result));
        return 1;
    }

    return 0;
}
Пример #28
0
/* This test check for initial position and feek value for fmemopen objects
   opened with append mode.  */
static int
do_test_read_append (void)
{
  char buf[32] = "testing buffer";
  size_t buflen = strlen (buf);
  long fpos;

  /* POSIX defines for 'a+' the initial position is the first null byte.  */
  FILE *fp = fmemopen (buf, sizeof (buf), "a+");

  fpos = ftell (fp);
  if (fpos != buflen)
    {
      printf ("%s: ftell|SEEK_SET (fp) %li != strlen (%s) %zu\n",
	      __FUNCTION__, fpos, buf, buflen);
      fclose (fp);
      return 1;
    }

  fseek (fp, 0, SEEK_END);

  if (fpos != buflen)
    {
      printf ("%s: ftell|SEEK_END (fp) %li != strlen (%s) %zu\n",
	      __FUNCTION__, fpos, buf, buflen);
      fclose (fp);
      return 1;
    }
  fclose (fp);

  /* Check if attempting to read past the current size, defined as strlen (buf)
     yield an EOF.  */
  fp = fmemopen (buf, sizeof (buf), "a+");
  if (getc(fp) != EOF)
    {
      printf ("%s: getc(fp) != EOF\n", __FUNCTION__);
      fclose (fp);
      return -1;
    }

  fclose (fp);

  return 0;
}
Пример #29
0
static int
do_bz18820 (void)
{
  char ch;
  FILE *stream;

  errno = 0;
  stream = fmemopen (&ch, 1, "?");
  if (stream)
    {
      printf ("fmemopen: expected NULL, got %p\n", stream);
      fclose (stream);
      return 1;
    }
  if (errno != EINVAL)
    {
      printf ("fmemopen: got %i, expected EINVAL (%i)\n", errno, EINVAL);
      return 10;
    }

  stream = fmemopen (NULL, 42, "?");
  if (stream)
    {
      printf ("fmemopen: expected NULL, got %p\n", stream);
      fclose (stream);
      return 2;
    }

  errno = 0;
  stream = fmemopen (NULL, ~0, "w");
  if (stream)
    {
      printf ("fmemopen: expected NULL, got %p\n", stream);
      fclose (stream);
      return 3;
    }
  if (errno != ENOMEM)
    {
      printf ("fmemopen: got %i, expected ENOMEM (%i)\n", errno, ENOMEM);
      return 20;
    }

  return 0;
}
Пример #30
0
/**
 * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
 * registered.
 *
 * \param event              A list of llapi_json_items comprising a
 *                           single JSON-formatted event.
 *
 * \retval 0 on success.
 * \retval -errno on error.
 */
static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
{
	int				rc;
	char				time_string[40];
	char				json_buf[PIPE_BUF];
	FILE				*buf_file;
	time_t				event_time = time(0);
	struct tm			time_components;
	struct llapi_json_item_list	*json_items;

	/* Noop unless the event fd was initialized */
	if (llapi_hsm_event_fd < 0)
		return 0;

	if (event == NULL || *event == NULL)
		return -EINVAL;

	json_items = *event;

	localtime_r(&event_time, &time_components);

	if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
		     &time_components) == 0) {
		rc = -EINVAL;
		llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
		return rc;
	}

	rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
				 time_string);
	if (rc < 0) {
		llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
			    "llapi_json_add_item()");
		return rc;
	}

	buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
	if (buf_file == NULL)
		return -errno;

	rc = llapi_json_write_list(event, buf_file);
	if (rc < 0) {
		fclose(buf_file);
		return rc;
	}

	fclose(buf_file);

	if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
		/* Ignore write failures due to missing reader. */
		if (errno != EPIPE)
			return -errno;
	}

	return 0;
}