/* * Dump debugging state to a result string */ bool_t rcmd_debug_dump_to_string_1_svc(char **result, struct svc_req *rqstp) { char* buffer = NULL; size_t buffer_size = 0; FILE* fp = NULL; fp = open_memstream(&buffer, &buffer_size); if (!fp) { error_perror("unable to create in-memory file"); *result = xstrdup("Error: out of memory"); goto cleanup; } show_debugging_info(fp); fclose(fp); *result = buffer ? buffer : xstrdup("Error: out of memory"); cleanup: return true; }
/*! * pixWriteMemPng() * * Input: &data (<return> data of tiff compressed image) * &size (<return> size of returned data) * pix * gamma (use 0.0 if gamma is not defined) * Return: 0 if OK, 1 on error * * Notes: * (1) See pixWriteStreamPng() for usage. This version writes to * memory instead of to a file stream. */ l_int32 pixWriteMemPng(l_uint8 **pdata, size_t *psize, PIX *pix, l_float32 gamma) { l_int32 ret; FILE *fp; PROCNAME("pixWriteMemPng"); if (!pdata) return ERROR_INT("&data not defined", procName, 1 ); if (!psize) return ERROR_INT("&size not defined", procName, 1 ); if (!pix) return ERROR_INT("&pix not defined", procName, 1 ); if ((fp = open_memstream((char **)pdata, psize)) == NULL) return ERROR_INT("stream not opened", procName, 1); ret = pixWriteStreamPng(fp, pix, gamma); fclose(fp); return ret; }
/*! * pixWriteMemJpeg() * * Input: &data (<return> data of jpeg compressed image) * &size (<return> size of returned data) * pix (any depth; cmap is OK) * quality (1 - 100; 75 is default value; 0 is also default) * progressive (0 for baseline sequential; 1 for progressive) * Return: 0 if OK, 1 on error * * Notes: * (1) See pixWriteStreamJpeg() for usage. This version writes to * memory instead of to a file stream. */ l_int32 pixWriteMemJpeg(l_uint8 **pdata, size_t *psize, PIX *pix, l_int32 quality, l_int32 progressive) { l_int32 ret; FILE *fp; PROCNAME("pixWriteMemJpeg"); if (pdata) *pdata = NULL; if (psize) *psize = 0; if (!pdata) return ERROR_INT("&data not defined", procName, 1 ); if (!psize) return ERROR_INT("&size not defined", procName, 1 ); if (!pix) return ERROR_INT("&pix not defined", procName, 1 ); #if HAVE_FMEMOPEN if ((fp = open_memstream((char **)pdata, psize)) == NULL) return ERROR_INT("stream not opened", procName, 1); ret = pixWriteStreamJpeg(fp, pix, quality, progressive); #else L_WARNING("work-around: writing to a temp file\n", procName); if ((fp = tmpfile()) == NULL) return ERROR_INT("tmpfile stream not opened", procName, 1); ret = pixWriteStreamJpeg(fp, pix, quality, progressive); rewind(fp); *pdata = l_binaryReadStream(fp, psize); #endif /* HAVE_FMEMOPEN */ fclose(fp); return ret; }
int DEFUN_VOID(main) { char *bp; size_t size; FILE *stream; int lose = 0; stream = open_memstream (&bp, &size); fprintf (stream, "hello"); fflush (stream); printf ("buf = %s, size = %d\n", bp, size); lose |= size != 5; lose |= strncmp (bp, "hello", size); fprintf (stream, ", world"); fclose (stream); printf ("buf = %s, size = %d\n", bp, size); lose |= size != 12; lose |= strncmp (bp, "hello, world", 12); puts (lose ? "Test FAILED!" : "Test succeeded."); return lose; }
/* io_parse: store copy of infile and outfile from s into cmd return newly allocated string with redirection removed */ static char *io_parse(struct command *cmd, const char *s) { FILE *stream; size_t size; char *buf; if (s == NULL) { errno = EINVAL; return NULL; } buf = NULL, size = 0; if ((stream = open_memstream(&buf, &size)) == NULL) return NULL; while (*s != '\0') { if (*s == '<' || *s == '>') { s += process_redirect(cmd, s); /* moves s over redirect */ } else { (void)fputc(*s, stream); ++s; } } (void)fclose(stream); return buf; }
int calendar_spec_to_string(const CalendarSpec *c, char **p) { char *buf = NULL; size_t sz = 0; FILE *f; int r; assert(c); assert(p); f = open_memstream(&buf, &sz); if (!f) return -ENOMEM; (void) __fsetlocking(f, FSETLOCKING_BYCALLER); if (c->weekdays_bits > 0 && c->weekdays_bits <= BITS_WEEKDAYS) { format_weekdays(f, c); fputc(' ', f); } format_chain(f, 4, c->year, false); fputc('-', f); format_chain(f, 2, c->month, false); fputc(c->end_of_month ? '~' : '-', f); format_chain(f, 2, c->day, false); fputc(' ', f); format_chain(f, 2, c->hour, false); fputc(':', f); format_chain(f, 2, c->minute, false); fputc(':', f); format_chain(f, 2, c->microsecond, true); if (c->utc) fputs(" UTC", f); else if (c->timezone != NULL) { fputc(' ', f); fputs(c->timezone, f); } else if (IN_SET(c->dst, 0, 1)) { /* If daylight saving is explicitly on or off, let's show the used timezone. */ tzset(); if (!isempty(tzname[c->dst])) { fputc(' ', f); fputs(tzname[c->dst], f); } } r = fflush_and_check(f); if (r < 0) { free(buf); fclose(f); return r; } fclose(f); *p = buf; return 0; }
int coredump_make_stack_trace(int fd, const char *executable, char **ret) { static const Dwfl_Callbacks callbacks = { .find_elf = dwfl_build_id_find_elf, .find_debuginfo = dwfl_standard_find_debuginfo, }; struct stack_context c = {}; char *buf = NULL; size_t sz = 0; int r; assert(fd >= 0); assert(ret); if (lseek(fd, 0, SEEK_SET) == (off_t) -1) return -errno; c.f = open_memstream(&buf, &sz); if (!c.f) return -ENOMEM; elf_version(EV_CURRENT); c.elf = elf_begin(fd, ELF_C_READ_MMAP, NULL); if (!c.elf) { r = -EINVAL; goto finish; } c.dwfl = dwfl_begin(&callbacks); if (!c.dwfl) { r = -EINVAL; goto finish; } if (dwfl_core_file_report(c.dwfl, c.elf, executable) < 0) { r = -EINVAL; goto finish; } if (dwfl_report_end(c.dwfl, NULL, NULL) != 0) { r = -EINVAL; goto finish; } if (dwfl_core_file_attach(c.dwfl, c.elf) < 0) { r = -EINVAL; goto finish; } if (dwfl_getthreads(c.dwfl, thread_callback, &c) < 0) { r = -EINVAL; goto finish; } c.f = safe_fclose(c.f); *ret = buf; buf = NULL; r = 0; finish: if (c.dwfl) dwfl_end(c.dwfl); if (c.elf) elf_end(c.elf); safe_fclose(c.f); free(buf); return r; }
int main(int argc, char *argv[]) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *copy = NULL; int r, boolean; const char *x, *x2, *y, *z, *a, *b, *c, *d, *a_signature; uint8_t u, v; void *buffer = NULL; size_t sz; char *h; const int32_t integer_array[] = { -1, -2, 0, 1, 2 }, *return_array; char *s; _cleanup_free_ char *first = NULL, *second = NULL, *third = NULL; _cleanup_fclose_ FILE *ms = NULL; size_t first_size = 0, second_size = 0, third_size = 0; _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL; double dbl; uint64_t u64; r = sd_bus_default_system(&bus); if (r < 0) return EXIT_TEST_SKIP; r = sd_bus_message_new_method_call(bus, &m, "foobar.waldo", "/", "foobar.waldo", "Piep"); assert_se(r >= 0); r = sd_bus_message_append(m, ""); assert_se(r >= 0); r = sd_bus_message_append(m, "s", "a string"); assert_se(r >= 0); r = sd_bus_message_append(m, "s", NULL); assert_se(r >= 0); r = sd_bus_message_append(m, "asg", 2, "string #1", "string #2", "sba(tt)ss"); assert_se(r >= 0); r = sd_bus_message_append(m, "sass", "foobar", 5, "foo", "bar", "waldo", "piep", "pap", "after"); assert_se(r >= 0); r = sd_bus_message_append(m, "a{yv}", 2, 3, "s", "foo", 5, "s", "waldo"); assert_se(r >= 0); r = sd_bus_message_append(m, "y(ty)y(yt)y", 8, 777ULL, 7, 9, 77, 7777ULL, 10); assert_se(r >= 0); r = sd_bus_message_append(m, "()"); assert_se(r >= 0); r = sd_bus_message_append(m, "ba(ss)", 255, 3, "aaa", "1", "bbb", "2", "ccc", "3"); assert_se(r >= 0); r = sd_bus_message_open_container(m, 'a', "s"); assert_se(r >= 0); r = sd_bus_message_append_basic(m, 's', "foobar"); assert_se(r >= 0); r = sd_bus_message_append_basic(m, 's', "waldo"); assert_se(r >= 0); r = sd_bus_message_close_container(m); assert_se(r >= 0); r = sd_bus_message_append_string_space(m, 5, &s); assert_se(r >= 0); strcpy(s, "hallo"); r = sd_bus_message_append_array(m, 'i', integer_array, sizeof(integer_array)); assert_se(r >= 0); r = sd_bus_message_append_array(m, 'u', NULL, 0); assert_se(r >= 0); r = sd_bus_message_append(m, "a(stdo)", 1, "foo", 815ULL, 47.0, "/"); assert_se(r >= 0); r = bus_message_seal(m, 4711, 0); assert_se(r >= 0); bus_message_dump(m, stdout, BUS_MESSAGE_DUMP_WITH_HEADER); ms = open_memstream(&first, &first_size); bus_message_dump(m, ms, 0); fflush(ms); assert_se(!ferror(ms)); r = bus_message_get_blob(m, &buffer, &sz); assert_se(r >= 0); h = hexmem(buffer, sz); assert_se(h); log_info("message size = %zu, contents =\n%s", sz, h); free(h); #ifdef HAVE_GLIB { GDBusMessage *g; char *p; #if !defined(GLIB_VERSION_2_36) g_type_init(); #endif g = g_dbus_message_new_from_blob(buffer, sz, 0, NULL); p = g_dbus_message_print(g, 0); log_info("%s", p); g_free(p); g_object_unref(g); } #endif #ifdef HAVE_DBUS { DBusMessage *w; DBusError error; dbus_error_init(&error); w = dbus_message_demarshal(buffer, sz, &error); if (!w) log_error("%s", error.message); else dbus_message_unref(w); dbus_error_free(&error); } #endif m = sd_bus_message_unref(m); r = bus_message_from_malloc(bus, buffer, sz, NULL, 0, NULL, &m); assert_se(r >= 0); bus_message_dump(m, stdout, BUS_MESSAGE_DUMP_WITH_HEADER); fclose(ms); ms = open_memstream(&second, &second_size); bus_message_dump(m, ms, 0); fflush(ms); assert_se(!ferror(ms)); assert_se(first_size == second_size); assert_se(memcmp(first, second, first_size) == 0); assert_se(sd_bus_message_rewind(m, true) >= 0); r = sd_bus_message_read(m, "ssasg", &x, &x2, 2, &y, &z, &a_signature); assert_se(r > 0); assert_se(streq(x, "a string")); assert_se(streq(x2, "")); assert_se(streq(y, "string #1")); assert_se(streq(z, "string #2")); assert_se(streq(a_signature, "sba(tt)ss")); r = sd_bus_message_read(m, "sass", &x, 5, &y, &z, &a, &b, &c, &d); assert_se(r > 0); assert_se(streq(x, "foobar")); assert_se(streq(y, "foo")); assert_se(streq(z, "bar")); assert_se(streq(a, "waldo")); assert_se(streq(b, "piep")); assert_se(streq(c, "pap")); assert_se(streq(d, "after")); r = sd_bus_message_read(m, "a{yv}", 2, &u, "s", &x, &v, "s", &y); assert_se(r > 0); assert_se(u == 3); assert_se(streq(x, "foo")); assert_se(v == 5); assert_se(streq(y, "waldo")); r = sd_bus_message_read(m, "y(ty)", &v, &u64, &u); assert_se(r > 0); assert_se(v == 8); assert_se(u64 == 777); assert_se(u == 7); r = sd_bus_message_read(m, "y(yt)", &v, &u, &u64); assert_se(r > 0); assert_se(v == 9); assert_se(u == 77); assert_se(u64 == 7777); r = sd_bus_message_read(m, "y", &v); assert_se(r > 0); assert_se(v == 10); r = sd_bus_message_read(m, "()"); assert_se(r > 0); r = sd_bus_message_read(m, "ba(ss)", &boolean, 3, &x, &y, &a, &b, &c, &d); assert_se(r > 0); assert_se(boolean); assert_se(streq(x, "aaa")); assert_se(streq(y, "1")); assert_se(streq(a, "bbb")); assert_se(streq(b, "2")); assert_se(streq(c, "ccc")); assert_se(streq(d, "3")); assert_se(sd_bus_message_verify_type(m, 'a', "s") > 0); r = sd_bus_message_read(m, "as", 2, &x, &y); assert_se(r > 0); assert_se(streq(x, "foobar")); assert_se(streq(y, "waldo")); r = sd_bus_message_read_basic(m, 's', &s); assert_se(r > 0); assert_se(streq(s, "hallo")); r = sd_bus_message_read_array(m, 'i', (const void**) &return_array, &sz); assert_se(r > 0); assert_se(sz == sizeof(integer_array)); assert_se(memcmp(integer_array, return_array, sz) == 0); r = sd_bus_message_read_array(m, 'u', (const void**) &return_array, &sz); assert_se(r > 0); assert_se(sz == 0); r = sd_bus_message_read(m, "a(stdo)", 1, &x, &u64, &dbl, &y); assert_se(r > 0); assert_se(streq(x, "foo")); assert_se(u64 == 815ULL); assert_se(fabs(dbl - 47.0) < 0.1); assert_se(streq(y, "/")); r = sd_bus_message_peek_type(m, NULL, NULL); assert_se(r == 0); r = sd_bus_message_new_method_call(bus, ©, "foobar.waldo", "/", "foobar.waldo", "Piep"); assert_se(r >= 0); r = sd_bus_message_rewind(m, true); assert_se(r >= 0); r = sd_bus_message_copy(copy, m, true); assert_se(r >= 0); r = bus_message_seal(copy, 4712, 0); assert_se(r >= 0); fclose(ms); ms = open_memstream(&third, &third_size); bus_message_dump(copy, ms, 0); fflush(ms); assert_se(!ferror(ms)); printf("<%.*s>\n", (int) first_size, first); printf("<%.*s>\n", (int) third_size, third); assert_se(first_size == third_size); assert_se(memcmp(first, third, third_size) == 0); r = sd_bus_message_rewind(m, true); assert_se(r >= 0); assert_se(sd_bus_message_verify_type(m, 's', NULL) > 0); r = sd_bus_message_skip(m, "ssasg"); assert_se(r > 0); assert_se(sd_bus_message_verify_type(m, 's', NULL) > 0); r = sd_bus_message_skip(m, "sass"); assert_se(r >= 0); assert_se(sd_bus_message_verify_type(m, 'a', "{yv}") > 0); r = sd_bus_message_skip(m, "a{yv}y(ty)y(yt)y()"); assert_se(r >= 0); assert_se(sd_bus_message_verify_type(m, 'b', NULL) > 0); r = sd_bus_message_read(m, "b", &boolean); assert_se(r > 0); assert_se(boolean); r = sd_bus_message_enter_container(m, 0, NULL); assert_se(r > 0); r = sd_bus_message_read(m, "(ss)", &x, &y); assert_se(r > 0); r = sd_bus_message_read(m, "(ss)", &a, &b); assert_se(r > 0); r = sd_bus_message_read(m, "(ss)", &c, &d); assert_se(r > 0); r = sd_bus_message_read(m, "(ss)", &x, &y); assert_se(r == 0); r = sd_bus_message_exit_container(m); assert_se(r >= 0); assert_se(streq(x, "aaa")); assert_se(streq(y, "1")); assert_se(streq(a, "bbb")); assert_se(streq(b, "2")); assert_se(streq(c, "ccc")); assert_se(streq(d, "3")); test_bus_label_escape(); test_bus_path_encode(); test_bus_path_encode_unique(); test_bus_path_encode_many(); return 0; }
void openmemout(void) { INTOFF; memout.stream = open_memstream(&memout.buf, &memout.bufsize); INTON; }
static char *ngx_http_acme_plain_request(ngx_conf_t *cf, void *conf, char *url, ngx_http_acme_http_method_t http_method, ngx_str_t request_data, ngx_str_t *response_data, ngx_http_acme_slist_t **response_headers) { CURL *curl; CURLcode res; struct curl_slist *request_headers = NULL; FILE *response_data_stream; /* Begin cURL part */ curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if(curl == NULL) return NGX_CONF_ERROR; curl_easy_setopt(curl, CURLOPT_URL, url); /* * Setting the HTTP method */ if(http_method == GET) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); } else if(http_method == POST) { curl_easy_setopt(curl, CURLOPT_POST, 1L); } /* * Setting the request data handling */ if(request_data.data != NULL) { // TODO (KK) Add method parameter for the header list to be dynamic in e.g. the content type, since it doesn't always have to be JSON ;) request_headers = curl_slist_append(request_headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, request_headers); /* size of the data to copy from the buffer and send in the request */ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request_data.len); /* send data from the local stack */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_data.data); println_debug("Request data: ", &request_data); } /* * Setting the response data handling */ /* Setup the stream for the response data */ response_data_stream = open_memstream((char **) &response_data->data, &response_data->len); if(response_data_stream == NULL) { curl_slist_free_all(request_headers); curl_easy_cleanup(curl); return NGX_CONF_ERROR; } /* * ATTENTION: Setting CURLOPT_WRITEDATA without CURLOPT_WRITEFUNCTION does not work on Windows * according to https://curl.haxx.se/libcurl/c/CURLOPT_WRITEDATA.html */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_data_stream); /* * Setting the response header handling */ if (response_headers != NULL) { curl_easy_setopt(curl, CURLOPT_HEADERDATA, response_headers); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, ngx_http_acme_header_callback); } /* * Perform the request */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) { ngx_log_error(NGX_LOG_ERR, cf->log, 0, "Error while performing request: %s\n", curl_easy_strerror(res)); fclose(response_data_stream); curl_slist_free_all(request_headers); curl_easy_cleanup(curl); return NGX_CONF_ERROR; } /* always cleanup */ curl_easy_cleanup(curl); fclose(response_data_stream); /* free the custom headers */ curl_slist_free_all(request_headers); /* End cURL part */ println_debug("Response data: ", response_data); return NGX_CONF_OK; } /* ngx_http_acme_plain_request */
static void response_open(VmonResponse *res) { res->out = open_memstream(&res->ptr, &res->len); }
static void setup(void) { result = NULL; memstream = open_memstream(&memstream_buffer, &memstream_size); fputc('\n', memstream); }
static int xmp_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int res; FILE* fp; FILE* mfp; char* mval; size_t mlen; char xattrval[8]; ssize_t xattrlen; int action = -1; char filepath[PATH_MAX]; xmp_extendPath(filepath, path); (void) fi; //open file we want to write fp = fopen(filepath, "r"); if(fp == NULL){ return -errno; } //prep mstream mfp = open_memstream(&mval, &mlen); if(mfp == NULL){ return -errno; } //check if file is encrypted xattrlen = getxattr(filepath, "user.encrypted", xattrval, 8); if (xattrlen != -1 && !memcmp(xattrval, "true", 4)){ action = 0; } //unencrypt if encrypted, otherwise copy do_crypt(fp, mfp, action, XMP_INFO -> pass); fclose(fp); //find write area and load fseek(mfp, offset, SEEK_SET); res = fwrite(buf, 1, size, mfp); if (res == -1) res = -errno; fflush(mfp); //encrypt if we decrypted if(action == 0){ action = 1; } fp = fopen(filepath, "w"); fseek(mfp, 0, SEEK_SET); do_crypt(mfp, fp, action, XMP_INFO -> pass); //cleanup fclose(mfp); fclose(fp); return res; }
static void check (struct sgrp e, const char *expected) { char *buf; size_t buf_size; FILE *f = open_memstream (&buf, &buf_size); if (f == NULL) { printf ("open_memstream: %m\n"); errors = true; return; } int ret = putsgent (&e, f); if (expected == NULL) { if (ret == -1) { if (errno != EINVAL) { printf ("putsgent: unexpected error code: %m\n"); errors = true; } } else { printf ("putsgent: unexpected success (\"%s\")\n", e.sg_namp); errors = true; } } else { /* Expect success. */ size_t expected_length = strlen (expected); if (ret == 0) { long written = ftell (f); if (written <= 0 || fflush (f) < 0) { printf ("stream error: %m\n"); errors = true; } else if (buf[written - 1] != '\n') { printf ("FAILED: \"%s\" without newline\n", expected); errors = true; } else if (strncmp (buf, expected, written - 1) != 0 || written - 1 != expected_length) { printf ("FAILED: \"%s\" (%ld), expected \"%s\" (%zu)\n", buf, written - 1, expected, expected_length); errors = true; } } else { printf ("FAILED: putsgent (expected \"%s\"): %m\n", expected); errors = true; } } fclose (f); free (buf); }
static void simple_tests(void) { static const char zerobuf[] = { 'f', 'o', 'o', 0, 0, 0, 0, 'b', 'a', 'r', 0 }; char c; FILE *fp; fp = open_memstream(&buf, NULL); if (fp != NULL) errx(1, "did not fail to open stream"); else if (errno != EINVAL) err(1, "incorrect error for bad length pointer"); fp = open_memstream(NULL, &len); if (fp != NULL) errx(1, "did not fail to open stream"); else if (errno != EINVAL) err(1, "incorrect error for bad buffer pointer"); fp = open_memstream(&buf, &len); if (fp == NULL) err(1, "failed to open stream"); fflush(fp); assert_stream(""); if (fwide(fp, 0) >= 0) printf("stream is not byte-oriented\n"); fprintf(fp, "fo"); fflush(fp); assert_stream("fo"); fputc('o', fp); fflush(fp); assert_stream("foo"); rewind(fp); fflush(fp); assert_stream(""); fseek(fp, 0, SEEK_END); fflush(fp); assert_stream("foo"); /* * Test seeking out past the current end. Should zero-fill the * intermediate area. */ fseek(fp, 4, SEEK_END); fprintf(fp, "bar"); fflush(fp); /* * Can't use assert_stream() here since this should contain * embedded null characters. */ if (len != 10) printf("bad length %zd for zero-fill test\n", len); else if (memcmp(buf, zerobuf, sizeof(zerobuf)) != 0) printf("bad buffer for zero-fill test\n"); fseek(fp, 3, SEEK_SET); fprintf(fp, " in "); fflush(fp); assert_stream("foo in "); fseek(fp, 0, SEEK_END); fflush(fp); assert_stream("foo in bar"); rewind(fp); if (fread(&c, sizeof(c), 1, fp) != 0) printf("fread did not fail\n"); else if (!ferror(fp)) printf("error indicator not set after fread\n"); else clearerr(fp); fseek(fp, 4, SEEK_SET); fprintf(fp, "bar baz"); fclose(fp); assert_stream("foo bar baz"); free(buf); }
int main(int argc, char *argv[]) { char *buffers[NFILE]; size_t bufsizes[NFILE]; char *fn; int i = 0; memset(buffers, 0, sizeof(buffers)); memset(bufsizes, 0, sizeof(bufsizes)); if ( argc != 2 ) { printf("Usage: spcat BASENAME\n"); exit(1); } fn = strrchr(argv[1], '.'); if ( fn ) fn[0] = (char)0; /* Remove filename extension */ fn = malloc(strlen(argv[1])+5); if ( fn == NULL ) { fprintf(stderr,"Memory allocation failed\n"); exit(1); } for ( ; i < 2; i++ ) { /* Read input files */ FILE *hmem, *hfile; char buf[256]; size_t tempsizer = 0, tempsizew = 0; sprintf(fn, "%s.%s", argv[1], spcat_ext[i]); printf("Reading file %d (%s) into memory: ", i, fn); hmem = open_memstream(&buffers[i], &bufsizes[i]); if( hmem == NULL ) { fprintf(stderr,"Can't open input memory buffer %d: ", i); perror(NULL); exit(1); } hfile = fopen(fn, "r"); if ( hfile == NULL ) { fprintf(stderr,"Can't open input file %d: ", i); perror(NULL); exit(1); } while ( ( tempsizer = fread(buf, 1, sizeof(buf), hfile) ) ) { tempsizew = fwrite(buf, 1, tempsizer, hmem); if ( tempsizew != tempsizer ) { fprintf(stderr,"Write error on file %d\n", i); exit(1); } /* else printf("Loaded %d bytes\n", tempsizer); */ } if ( ferror(hfile) ) { fprintf(stderr,"Read error on file %d\n", i); exit(1); } fclose(hfile); fclose(hmem); printf("Loaded %d bytes\n", bufsizes[i]); } { spcs_t x; if ( init_spcs(&x) ) { fprintf(stderr,"init_spcs error\n"); exit(1); } spcat(&x, buffers, bufsizes); if ( free_spcs(&x) ) { fprintf(stderr,"free_spcs error\n"); exit(1); } /* STILL NEED TO SORT, CLEANUP, ETC */ } for ( ; i < NFILE; i++ ) { /* Write output files */ FILE *hfile; size_t tempsizew = 0; sprintf(fn, "%s.%s", argv[1], spcat_ext[i]); if ( buffers[i] == NULL ) { printf("Skipping file %d (%s): Not written\n", i, fn); continue; } printf("Writing file %d (%s) from memory: ", i, fn); hfile = fopen(fn, "w"); if ( hfile == NULL ) { fprintf(stderr,"Can't open output file %d: ", i); perror(NULL); exit(1); } tempsizew = fwrite(buffers[i], 1, bufsizes[i], hfile); if ( tempsizew != bufsizes[i] ) { fprintf(stderr,"Write error on file %d\n", i); exit(1); } else printf("Saved %d bytes\n", tempsizew); fclose(hfile); } for ( i=0; i < NFILE; i++ ) if ( buffers[i] ) free(buffers[i]); free(fn); return 0; }
/* * Initialize an hprof context struct. * * This will take ownership of "fileName". * * NOTE: ctx is expected to have been zeroed out prior to calling this * function. */ void hprofContextInit(hprof_context_t *ctx, char *fileName, int fd, bool writeHeader, bool directToDdms) { /* * Have to do this here, because it must happen after we * memset the struct (want to treat fileDataPtr/fileDataSize * as read-only while the file is open). */ FILE* fp = open_memstream(&ctx->fileDataPtr, &ctx->fileDataSize); if (fp == NULL) { /* not expected */ ALOGE("hprof: open_memstream failed: %s", strerror(errno)); dvmAbort(); } ctx->directToDdms = directToDdms; ctx->fileName = fileName; ctx->memFp = fp; ctx->fd = fd; ctx->curRec.allocLen = 128; ctx->curRec.body = (unsigned char *)malloc(ctx->curRec.allocLen); //xxx check for/return an error if (writeHeader) { char magic[] = HPROF_MAGIC_STRING; unsigned char buf[4]; struct timeval now; u8 nowMs; /* Write the file header. * * [u1]*: NUL-terminated magic string. */ fwrite(magic, 1, sizeof(magic), fp); /* u4: size of identifiers. We're using addresses * as IDs, so make sure a pointer fits. */ U4_TO_BUF_BE(buf, 0, sizeof(void *)); fwrite(buf, 1, sizeof(u4), fp); /* The current time, in milliseconds since 0:00 GMT, 1/1/70. */ if (gettimeofday(&now, NULL) < 0) { nowMs = 0; } else { nowMs = (u8)now.tv_sec * 1000 + now.tv_usec / 1000; } /* u4: high word of the 64-bit time. */ U4_TO_BUF_BE(buf, 0, (u4)(nowMs >> 32)); fwrite(buf, 1, sizeof(u4), fp); /* u4: low word of the 64-bit time. */ U4_TO_BUF_BE(buf, 0, (u4)(nowMs & 0xffffffffULL)); fwrite(buf, 1, sizeof(u4), fp); //xxx fix the time } }
void vconsoleLogger(int priority, const char *format, va_list optional_arguments) { /*int n = 0;*/ const int saved_errno = errno; const int LogMask = setlogmask(0); /* no cancellation point is currently used in this function * (according to Advanced Programming in the Unix Environment 2nd ed p411) * so there is no thread cancellation clean-up handlers defined */ /* Check for invalid bits. */ if (unlikely(priority & ~(LOG_PRIMASK | LOG_FACMASK))) { /*syslog(INTERNALLOG, "syslog: unknown facility/priority: %x", pri);*/ WARNING_MSG("unknown facility/priority: %x", priority); priority &= LOG_PRIMASK | LOG_FACMASK; } /* Check priority against setlogmask values. */ if ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) { char *buf = 0; size_t bufsize = 1024; /*char logFormat[1024]; char *cursor = logFormat;*/ FILE *f = open_memstream(&buf, &bufsize); if (f != NULL) { struct tm now_tm; time_t now; (void) time(&now); /*cursor += strftime(cursor,sizeof(logFormat),"%h %e %T ",localtime_r(&now, &now_tm));*/ f->_IO_write_ptr += strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); if (LogTag) { //cursor += sprintf (cursor,"%s: ",LogTag); fprintf(f,"%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); /*cursor += sprintf (cursor, "[%d:%d]", (int) getpid (),(int) tid);*/ fprintf(f,"[%d:%d]", (int) getpid (),(int) tid); } else { /*cursor += sprintf (cursor, "[%d]", (int) getpid ());*/ fprintf(f,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); /*cursor += sprintf (cursor, "(%llu)",t);*/ fprintf(f,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { /*cursor += sprintf (cursor, "(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec);*/ fprintf(f,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Emergency * %s",format);*/ fprintf(f,"[EMERG] %s",format); break; case LOG_ALERT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Alert * %s",format);*/ fprintf(f,"[ALERT] %s",format); break; case LOG_CRIT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Critical * %s",format);*/ fprintf(f,"[CRIT] %s",format); break; case LOG_ERR: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Error * %s",format);*/ fprintf(f,"[ERROR] %s",format); break; case LOG_WARNING: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Warning * %s",format);*/ fprintf(f,"[WARNING] %s",format); break; case LOG_NOTICE: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Notice * %s",format); */ fprintf(f,"[NOTICE] %s",format); break; case LOG_INFO: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Info * %s",format);*/ fprintf(f,"[INFO] %s",format); break; case LOG_DEBUG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Debug * %s",format);*/ fprintf(f,"[DEBUG] %s",format); break; default: /*cursor += sprintf(cursor,"* <%d> * %s",priority,format);*/ fprintf(f,"[<%d>] %s",priority,format); } /* switch(priority) */ } else { /* (LogStat & LOG_LEVEL) */ /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"%s",format);*/ fprintf(f,"%s",format); } /*n =*/ /*vfprintf(stderr,logFormat,optional_arguments);*/ /* Close the memory stream; this will finalize the data into a malloc'd buffer in BUF. */ fclose(f); errno = saved_errno; /* restore errno for %m format */ vfprintf(stderr,buf,optional_arguments); free(buf); } else { /* We cannot get a stream: try to write directly to the console (warning may be splitted by other msg) */ struct tm now_tm; time_t now; char buffer[20]; WARNING_MSG("failed to get stream buffer, using the console without buffering instead"); (void) time(&now); strftime(buffer,sizeof(buffer),"%h %e %T ",localtime_r(&now, &now_tm)); fprintf(stderr,"%s",buffer); if (LogTag) { printf("%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); fprintf(stderr,"[%d:%d]", (int) getpid (),(int) tid); } else { fprintf(stderr,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); fprintf(stderr,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { fprintf(stderr,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: fprintf(stderr,"* Emergency * "); break; case LOG_ALERT: fprintf(stderr,"* Alert * "); break; case LOG_CRIT: fprintf(stderr,"* Critical * "); break; case LOG_ERR: fprintf(stderr,"* Error * "); break; case LOG_WARNING: fprintf(stderr,"* Warning * "); break; case LOG_NOTICE: fprintf(stderr,"* Notice * "); break; case LOG_INFO: fprintf(stderr,"* Info * "); break; case LOG_DEBUG: fprintf(stderr,"* Debug * "); break; default: fprintf(f,"* <%d> * ",priority); } /* switch(priority) */ } vfprintf(stderr,format,optional_arguments); } } /* ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) */ /* message has not to be displayed because of the current LogMask and its priority */ /*return n;*/ }
static void perf_new_compilation(struct acr_runtime_perf *perf, unsigned char *monitor_result) { size_t perf_step = perf->list_head == NULL ? 0 : perf->list_head->element.ending_at + 1; char *generated_function = NULL; size_t generated_function_size; char *body = NULL; FILE *bodystream = open_memstream(&body, &generated_function_size); acr_cloog_generate_alternative_code_from_input(bodystream, perf->rdata, monitor_result); fclose(bodystream); FILE *memstring = open_memstream(&generated_function, &generated_function_size); fprintf(memstring, "void acr_function%s {\n%s}\n", perf->rdata->function_prototype, body); fclose(memstring); char *compilation_filename; size_t buffer_size; size_t path_size; switch (perf->type) { case acr_runtime_perf_kernel_only: compilation_filename = NULL; break; case acr_runtime_perf_compilation_time_zero: acr_getcwd(&compilation_filename, &buffer_size); path_size = strlen(compilation_filename); if (path_size + 50 < buffer_size) compilation_filename = realloc(compilation_filename, path_size + 51); snprintf(compilation_filename+path_size, 50, "/acr_compile_%zu.so", perf->list_size); break; case acr_runtime_perf_compilation_time_zero_run: fprintf(stderr, "ACR fatal error: This code should not have been generated\n" "Please fill a bug report with the file and command sequence used\n"); exit(EXIT_FAILURE); break; } char *filename = acr_compile_with_system_compiler( compilation_filename, generated_function, perf->rdata->num_compiler_flags, perf->rdata->compiler_flags); free(generated_function); struct acr_perf_compilation comp; comp.compilation_file_name = filename; comp.handle = dlopen(filename, RTLD_NOW); if (comp.handle == NULL) { perror("dlopen"); exit(EXIT_FAILURE); } switch (perf->type) { case acr_runtime_perf_kernel_only: unlink(filename); break; case acr_runtime_perf_compilation_time_zero: case acr_runtime_perf_compilation_time_zero_run: break; } comp.function = dlsym(comp.handle, "acr_function"); if (comp.function == NULL) { perror("dlsym"); exit(EXIT_FAILURE); } comp.starting_at = perf_step; comp.ending_at = perf_step; comp.monitor_result = monitor_result; comp.loop_body = body; acr_perf_add_compilation_to_list(perf, comp); }
int main (int argc, char *argv[]) { struct qemuopts *qopts; FILE *fp; char *actual; size_t i, len; char **actual_argv; qopts = qemuopts_create (); if (qemuopts_set_binary_by_arch (qopts, NULL) == -1) { if (errno == ENXIO) { fprintf (stderr, "qemuopts: This architecture does not support KVM.\n"); fprintf (stderr, "If this architecture *does* support KVM, then please modify qemuopts.c\n"); fprintf (stderr, "and send us a patch.\n"); exit (77); /* Skip the test. */ } perror ("qemuopts_set_binary_by_arch"); exit (EXIT_FAILURE); } /* ... but for the purposes of testing, it's easier if we * set this to a known string. */ CHECK_ERROR (-1, "qemuopts_set_binary", qemuopts_set_binary (qopts, "qemu-system-x86_64")); CHECK_ERROR (-1, "qemuopts_add_flag", qemuopts_add_flag (qopts, "-no-user-config")); CHECK_ERROR (-1, "qemuopts_add_arg", qemuopts_add_arg (qopts, "-m", "1024")); CHECK_ERROR (-1, "qemuopts_add_arg_format", qemuopts_add_arg_format (qopts, "-smp", "%d", 4)); CHECK_ERROR (-1, "qemuopts_start_arg_list", qemuopts_start_arg_list (qopts, "-drive")); CHECK_ERROR (-1, "qemuopts_append_arg_list", qemuopts_append_arg_list (qopts, "file=/tmp/foo")); CHECK_ERROR (-1, "qemuopts_append_arg_list_format", qemuopts_append_arg_list_format (qopts, "if=%s", "ide")); CHECK_ERROR (-1, "qemuopts_end_arg_list", qemuopts_end_arg_list (qopts)); CHECK_ERROR (-1, "qemuopts_add_arg_list", qemuopts_add_arg_list (qopts, "-drive", "file=/tmp/bar", "serial=123", NULL)); /* Test qemu comma-quoting. */ CHECK_ERROR (-1, "qemuopts_add_arg", qemuopts_add_arg (qopts, "-name", "foo,bar")); CHECK_ERROR (-1, "qemuopts_add_arg_list", qemuopts_add_arg_list (qopts, "-drive", "file=comma,in,name", "serial=$dollar$", NULL)); /* Test shell quoting. */ CHECK_ERROR (-1, "qemuopts_add_arg", qemuopts_add_arg (qopts, "-cdrom", "\"$quoted\".iso")); fp = open_memstream (&actual, &len); if (fp == NULL) { perror ("open_memstream"); exit (EXIT_FAILURE); } CHECK_ERROR (-1, "qemuopts_to_channel", qemuopts_to_channel (qopts, fp)); if (fclose (fp) == EOF) { perror ("fclose"); exit (EXIT_FAILURE); } const char *expected = "qemu-system-x86_64 \\\n" " -no-user-config \\\n" " -m 1024 \\\n" " -smp 4 \\\n" " -drive file=/tmp/foo,if=ide \\\n" " -drive file=/tmp/bar,serial=123 \\\n" " -name \"foo,,bar\" \\\n" " -drive \"file=comma,,in,,name\",\"serial=\\$dollar\\$\" \\\n" " -cdrom \"\\\"\\$quoted\\\".iso\"\n"; if (strcmp (actual, expected) != 0) { fprintf (stderr, "qemuopts: Serialized qemu command line does not match expected\n"); fprintf (stderr, "Actual:\n%s", actual); fprintf (stderr, "Expected:\n%s", expected); exit (EXIT_FAILURE); } free (actual); /* Test qemuopts_to_argv. */ CHECK_ERROR (NULL, "qemuopts_to_argv", actual_argv = qemuopts_to_argv (qopts)); const char *expected_argv[] = { "qemu-system-x86_64", "-no-user-config", "-m", "1024", "-smp", "4", "-drive", "file=/tmp/foo,if=ide", "-drive", "file=/tmp/bar,serial=123", "-name", "foo,,bar", "-drive", "file=comma,,in,,name,serial=$dollar$", "-cdrom", "\"$quoted\".iso", NULL }; for (i = 0; actual_argv[i] != NULL; ++i) { if (expected_argv[i] == NULL || strcmp (actual_argv[i], expected_argv[i])) { fprintf (stderr, "qemuopts: actual != expected argv at position %zu, %s != %s\n", i, actual_argv[i], expected_argv[i]); exit (EXIT_FAILURE); } } assert (expected_argv[i] == NULL); for (i = 0; actual_argv[i] != NULL; ++i) free (actual_argv[i]); free (actual_argv); qemuopts_free (qopts); /* Test qemuopts_to_config_channel. */ qopts = qemuopts_create (); CHECK_ERROR (-1, "qemuopts_start_arg_list", qemuopts_start_arg_list (qopts, "-drive")); CHECK_ERROR (-1, "qemuopts_append_arg_list", qemuopts_append_arg_list (qopts, "file=/tmp/foo")); CHECK_ERROR (-1, "qemuopts_append_arg_list", qemuopts_append_arg_list (qopts, "id=id")); CHECK_ERROR (-1, "qemuopts_append_arg_list_format", qemuopts_append_arg_list_format (qopts, "if=%s", "ide")); CHECK_ERROR (-1, "qemuopts_append_arg_list_format", qemuopts_append_arg_list_format (qopts, "bool")); CHECK_ERROR (-1, "qemuopts_end_arg_list", qemuopts_end_arg_list (qopts)); CHECK_ERROR (-1, "qemuopts_add_arg_list", qemuopts_add_arg_list (qopts, "-drive", "file=/tmp/bar", "serial=123", NULL)); fp = open_memstream (&actual, &len); if (fp == NULL) { perror ("open_memstream"); exit (EXIT_FAILURE); } CHECK_ERROR (-1, "qemuopts_to_config_channel", qemuopts_to_config_channel (qopts, fp)); if (fclose (fp) == EOF) { perror ("fclose"); exit (EXIT_FAILURE); } const char *expected2 = "# qemu config file\n" "\n" "[drive \"id\"]\n" " file = \"/tmp/foo\"\n" " if = \"ide\"\n" " bool = \"on\"\n" "\n" "[drive]\n" " file = \"/tmp/bar\"\n" " serial = \"123\"\n" "\n"; if (strcmp (actual, expected2) != 0) { fprintf (stderr, "qemuopts: Serialized qemu command line does not match expected\n"); fprintf (stderr, "Actual:\n%s", actual); fprintf (stderr, "Expected:\n%s", expected2); exit (EXIT_FAILURE); } free (actual); qemuopts_free (qopts); exit (EXIT_SUCCESS); }
/* Un-locked version: the locking should be done in the calling functions */ static void vqes_vsyslog_ul (int pri, register const char *fmt, va_list ap) { struct tm now_tm; FILE *f; size_t prioff; time_t now; int fd; char *buf = 0; size_t bufsize = 0; size_t msgoff; struct sigaction action, oldaction; struct sigaction *oldaction_ptr = NULL; int sigpipe; #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID /* Check for invalid bits. */ if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) { vqes_syslog(INTERNALLOG, "syslog: unknown facility/priority: %x", pri); pri &= LOG_PRIMASK|LOG_FACMASK; } /* Check priority against setlogmask values. */ if ((LOG_MASK(LOG_PRI(pri)) & LogMask) == 0) return; /* Set default facility if none specified. */ if ((pri & LOG_FACMASK) == 0) pri |= LogFacility; /* Build the message in a memory-buffer stream. */ f = open_memstream(&buf, &bufsize); prioff = fprintf(f, "<%d>", pri); (void) time(&now); char datestring[DATESTRING_LEN]; (void)strftime(datestring, DATESTRING_LEN, "%h %e %T", localtime_r(&now, &now_tm)); fprintf(f, "%s ", datestring); msgoff = ftell(f); if (LogTag == NULL) LogTag = __progname; if (LogTag != NULL) fputs(LogTag, f); if (LogStat & LOG_PID) fprintf(f, "[%d]", getpid()); if (LogTag != NULL) (void)putc(':', f), (void)putc(' ', f); /* We have the header. Print the user's format into the buffer. */ vfprintf(f, fmt, ap); /* Close the memory stream; this will finalize the data into a malloc'd buffer in BUF. */ fclose(f); /* Output to stderr if requested. */ if (LogStat & LOG_PERROR) { struct iovec iov[IOVEC_COUNT]; register struct iovec *v = iov; v->iov_base = buf + msgoff; v->iov_len = bufsize - msgoff; ++v; v->iov_base = (char *) "\n"; v->iov_len = 1; (void)writev(STDERR_FILENO, iov, IOVEC_COUNT); } /* Prepare for a broken connection. */ memset(&action, 0, sizeof(action)); action.sa_handler = sigpipe_handler; (void)sigemptyset(&action.sa_mask); sigpipe = sigaction(SIGPIPE, &action, &oldaction); if (sigpipe == 0) oldaction_ptr = &oldaction; /* Get connected, output the message to the local logger. */ if (!connected) openlog_internal(LogTag, LogStat | LOG_NDELAY, 0, NULL, 0); /* If we have a SOCK_STREAM connection, also send ASCII NUL as a record terminator. */ if (LogType == SOCK_STREAM) ++bufsize; /* first, send buf to default fd, LogFile */ if (send(LogFile, buf, bufsize, 0) < 0) { closelog_internal(); /* attempt re-open next time */ /* * Output the message to the console; don't worry about blocking, * if console blocks everything will. Make sure the error reported * is the one from the syslogd failure. */ if (LogStat & LOG_CONS && (fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) { /* GNU extension */ dprintf(fd, "%s\r\n", buf + msgoff); (void)close(fd); } } /* then, send it to the other specified FDs */ int i; for (i = 0 ; i < num_fds ; i++) { if (write(fds[i], buf, bufsize) < 0) { closelog_internal(); /* attempt re-open next time */ /* * Output the message to the console; don't worry about * blocking, if console blocks everything will. Make sure the * error reported is the one from the syslogd failure. */ if (LogStat & LOG_CONS && (fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) { dprintf(fd, "%s\r\n", buf + msgoff); (void)close(fd); } } } if (sigpipe == 0) (void)sigaction(SIGPIPE, &oldaction, (struct sigaction *) NULL); free(buf); }
static void cmd_http_request( struct server_framework_state *state, struct client_state *p, size_t pkt_size, const struct new_server_prot_packet *pkt_gen) { enum { MAX_PARAM_NUM = 10000, MAX_PARAM_SIZE = 128 * 1024 * 1024, }; const struct new_server_prot_http_request *pkt; size_t in_size; const ej_size_t *arg_sizes, *env_sizes, *param_name_sizes, *param_sizes; unsigned long bptr; const unsigned char ** args; const unsigned char ** envs; const unsigned char ** param_names; const unsigned char ** params; size_t *my_param_sizes; int i; char *out_txt = 0; size_t out_size = 0; FILE *out_f = 0; struct http_request_info hr; unsigned char info_buf[1024]; unsigned char *pbuf = info_buf; memset(&hr, 0, sizeof(hr)); hr.id = p->id; hr.client_state = p; hr.fw_state = state; gettimeofday(&hr.timestamp1, 0); hr.current_time = hr.timestamp1.tv_sec; hr.locale_id = -1; if (pkt_size < sizeof(*pkt)) return nsf_err_packet_too_small(state, p, pkt_size, sizeof(*pkt)); pkt = (const struct new_server_prot_http_request *) pkt_gen; if (pkt->arg_num < 0 || pkt->arg_num > MAX_PARAM_NUM) return nsf_err_protocol_error(state, p); if (pkt->env_num < 0 || pkt->env_num > MAX_PARAM_NUM) return nsf_err_protocol_error(state, p); if (pkt->param_num < 0 || pkt->param_num > MAX_PARAM_NUM) return nsf_err_protocol_error(state, p); in_size = sizeof(*pkt); in_size += pkt->arg_num * sizeof(ej_size_t); in_size += pkt->env_num * sizeof(ej_size_t); in_size += pkt->param_num * 2 * sizeof(ej_size_t); if (pkt_size < in_size) return nsf_err_packet_too_small(state, p, pkt_size, in_size); XALLOCAZ(args, pkt->arg_num); XALLOCAZ(envs, pkt->env_num); XALLOCAZ(param_names, pkt->param_num); XALLOCAZ(params, pkt->param_num); XALLOCAZ(my_param_sizes, pkt->param_num); bptr = (unsigned long) pkt; bptr += sizeof(*pkt); arg_sizes = (const ej_size_t *) bptr; bptr += pkt->arg_num * sizeof(ej_size_t); env_sizes = (const ej_size_t *) bptr; bptr += pkt->env_num * sizeof(ej_size_t); param_name_sizes = (const ej_size_t *) bptr; bptr += pkt->param_num * sizeof(ej_size_t); param_sizes = (const ej_size_t *) bptr; bptr += pkt->param_num * sizeof(ej_size_t); for (i = 0; i < pkt->arg_num; i++) { if (arg_sizes[i] > MAX_PARAM_SIZE) return nsf_err_protocol_error(state, p); in_size += arg_sizes[i] + 1; } for (i = 0; i < pkt->env_num; i++) { if (env_sizes[i] > MAX_PARAM_SIZE) return nsf_err_protocol_error(state, p); in_size += env_sizes[i] + 1; } for (i = 0; i < pkt->param_num; i++) { if (param_name_sizes[i] > MAX_PARAM_SIZE) return nsf_err_protocol_error(state, p); if (param_sizes[i] > MAX_PARAM_SIZE) return nsf_err_protocol_error(state, p); in_size += param_name_sizes[i] + 1; in_size += param_sizes[i] + 1; } if (pkt_size != in_size) return nsf_err_bad_packet_length(state, p, pkt_size, in_size); for (i = 0; i < pkt->arg_num; i++) { args[i] = (const unsigned char*) bptr; bptr += arg_sizes[i] + 1; if (strlen(args[i]) != arg_sizes[i]) return nsf_err_protocol_error(state, p); } for (i = 0; i < pkt->env_num; i++) { envs[i] = (const unsigned char*) bptr; bptr += env_sizes[i] + 1; if (strlen(envs[i]) != env_sizes[i]) return nsf_err_protocol_error(state, p); } for (i = 0; i < pkt->param_num; i++) { param_names[i] = (const unsigned char*) bptr; bptr += param_name_sizes[i] + 1; if (strlen(param_names[i]) != param_name_sizes[i]) return nsf_err_protocol_error(state, p); params[i] = (const unsigned char *) bptr; my_param_sizes[i] = param_sizes[i]; bptr += param_sizes[i] + 1; } hr.arg_num = pkt->arg_num; hr.args = args; hr.env_num = pkt->env_num; hr.envs = envs; hr.param_num = pkt->param_num; hr.param_names = param_names; hr.param_sizes = my_param_sizes; hr.params = params; hr.config = ejudge_config; // ok, generate HTML out_f = open_memstream(&out_txt, &out_size); ns_handle_http_request(state, p, out_f, &hr); close_memstream(out_f); out_f = 0; *pbuf = 0; // report IP? if (hr.ssl_flag) { pbuf = stpcpy(pbuf, "HTTPS:"); } else { pbuf = stpcpy(pbuf, "HTTPS:"); } pbuf = stpcpy(pbuf, xml_unparse_ipv6(&hr.ip)); *pbuf++ = ':'; if (hr.role_name) { pbuf = stpcpy(pbuf, hr.role_name); } if (hr.action > 0 && hr.action < NEW_SRV_ACTION_LAST && ns_symbolic_action_table[hr.action]) { *pbuf++ = '/'; pbuf = stpcpy(pbuf, ns_symbolic_action_table[hr.action]); } if (hr.session_id) { *pbuf++ = '/'; *pbuf++ = 'S'; pbuf += sprintf(pbuf, "%016llx", hr.session_id); if (hr.client_key) { *pbuf++ = '-'; pbuf += sprintf(pbuf, "%016llx", hr.client_key); } } if (hr.user_id > 0) { *pbuf++ = '/'; *pbuf++ = 'U'; pbuf += sprintf(pbuf, "%d", hr.user_id); } if (hr.contest_id > 0) { *pbuf++ = '/'; *pbuf++ = 'C'; pbuf += sprintf(pbuf, "%d", hr.contest_id); } // no reply now if (hr.no_reply) goto cleanup; if (hr.protocol_reply) { xfree(out_txt); out_txt = 0; info("%d:%s -> %d", p->id, info_buf, hr.protocol_reply); nsf_close_client_fds(p); nsf_send_reply(state, p, hr.protocol_reply); goto cleanup; } // if (hr.content_type && hr.content_type[0]) { // generate header char *hdr_t = NULL; size_t hdr_z = 0; FILE *hdr_f = open_memstream(&hdr_t, &hdr_z); fprintf(hdr_f, "Content-Type: %s\n", hr.content_type); fprintf(hdr_f, "Cache-Control: no-cache\n"); fprintf(hdr_f, "Pragma: no-cache\n"); if (hr.client_key) { fprintf(hdr_f, "Set-Cookie: EJSID=%016llx; Path=/\n", hr.client_key); } putc('\n', hdr_f); if (out_size > 0) { fwrite(out_txt, 1, out_size, hdr_f); } fclose(hdr_f); hdr_f = NULL; free(out_txt); out_txt = hdr_t; out_size = hdr_z; } if (!out_txt || !*out_txt) { xfree(out_txt); out_txt = 0; if (hr.allow_empty_output) { info("%d:%s -> OK", p->id, info_buf); nsf_close_client_fds(p); nsf_send_reply(state, p, NEW_SRV_RPL_OK); goto cleanup; } out_f = open_memstream(&out_txt, &out_size); ns_html_err_internal_error(out_f, &hr, 0, "empty output generated"); close_memstream(out_f); out_f = 0; xfree(out_txt); out_txt = 0; } nsf_new_autoclose(state, p, out_txt, out_size); info("%d:%s -> OK, %zu", p->id, info_buf, out_size); nsf_send_reply(state, p, NEW_SRV_RPL_OK); cleanup: if (hr.log_f) fclose(hr.log_f); xfree(hr.log_t); xfree(hr.login); xfree(hr.name); xfree(hr.name_arm); xfree(hr.script_part); xfree(hr.body_attr); }
static LV2_State_Status save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features) { B3S* b3s = (B3S*)instance; LOCALEGUARD_START; char *cfg = (char*) calloc(1, sizeof(char)); rc_loop_state(b3s->inst->state, rcstate_cb, (void*) &cfg); int i; size_t rs = 0; char *out = NULL; #ifdef _WIN32 char temppath[MAX_PATH - 13]; char filename[MAX_PATH + 1]; if (0 == GetTempPath(sizeof(temppath), temppath)) return LV2_STATE_ERR_UNKNOWN; if (0 == GetTempFileName(temppath, "sbfstate", 0, filename)) return LV2_STATE_ERR_UNKNOWN; FILE *x = fopen(filename, "w+b"); #else // POSIX FILE *x = open_memstream(&out, &rs); #endif for (i=0 ; i < 128; ++i) { int pgmNr = i + b3s->inst->progs->MIDIControllerPgmOffset; if (!(b3s->inst->progs->programmes[pgmNr].flags[0] & FL_INUSE)) { continue; } fprintf(x, "P "); writeProgramm(pgmNr, &b3s->inst->progs->programmes[pgmNr], " ", x); } fclose(x); #ifdef _WIN32 x = fopen(filename, "rb"); fseek (x , 0 , SEEK_END); long int rsize = ftell (x); rewind(x); out = (char*) malloc(rsize); fread(out, sizeof(char), rsize, x); fclose(x); unlink(filename); #endif cfg = (char*) realloc(cfg, strlen(cfg) + strlen(out) +1); strcat(cfg, out); LOCALEGUARD_END; store(handle, b3s->uris.sb3_state, cfg, strlen(cfg) + 1, b3s->uris.atom_String, LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE); free(cfg); free(out); return LV2_STATE_SUCCESS; }
void vfileLogger(int priority, const char *format, va_list optional_arguments) { int n = 0; int error = EXIT_SUCCESS; const int saved_errno = errno; int internalError = EXIT_SUCCESS; const int LogMask = setlogmask(0); /* Check priority against setlogmask values. */ if ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) { //char logMsg[2048]; //char logFormat[1024]; //char *cursor = logFormat; char *buf = 0; size_t bufsize = 1024; FILE *f = open_memstream(&buf, &bufsize); if (f != NULL) { struct tm now_tm; time_t now; (void) time(&now); /*cursor += strftime(cursor,sizeof(logFormat),"%h %e %T ",localtime_r(&now, &now_tm));*/ n = strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); //f->_IO_write_ptr += strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); f->_IO_write_ptr += n; if (LogTag) { /*cursor += sprintf (cursor,"%s: ",LogTag);*/ n += fprintf(f,"%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); /*cursor += sprintf (cursor, "[%d:%d]", (int) getpid (),(int) tid);*/ n += fprintf(f,"[%d:%d]", (int) getpid (),(int) tid); } else { /*cursor += sprintf (cursor, "[%d]", (int) getpid ());*/ n += fprintf(f,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); /*cursor += sprintf (cursor, "(%llu)",t);*/ n += fprintf(f,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { /*cursor += sprintf (cursor, "(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec);*/ n += fprintf(f,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Emergency * %s",format);*/ n += fprintf(f, "[EMERG]"); break; case LOG_ALERT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Alert * %s",format);*/ n += fprintf(f, "[ALERT]"); break; case LOG_CRIT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Critical * %s",format);*/ n += fprintf(f, "[CRIT]"); break; case LOG_ERR: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Error * %s",format);*/ n += fprintf(f, "[ERROR]"); break; case LOG_WARNING: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Warning * %s",format);*/ n += fprintf(f, "[WARNING]"); break; case LOG_NOTICE: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Notice * %s",format); */ n += fprintf(f, "[NOTICE]"); break; case LOG_INFO: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Info * %s",format);*/ n += fprintf(f, "[INFO]"); break; case LOG_DEBUG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Debug * %s",format);*/ n += fprintf(f, "[DEBUG]"); break; default: /*cursor += sprintf(cursor,"* <%d> * %s",priority,format);*/ n += fprintf(f,"[<%d>]",priority); } /* switch(priority) */ } /* (LogStat & LOG_LEVEL) */ errno = saved_errno; /* restore errno for %m format */ n += vfprintf(f, format, optional_arguments); /* Close the memory stream; this will finalize the data into a malloc'd buffer in BUF. */ fclose(f); /* * begin of the critical section. * Some of the function used below are thread cancellation points * (according to Advanced Programming in the Unix Environment 2nd ed p411) * so set the handler to avoid deadlocks and memory leaks */ cleanup_args cancelArgs; cancelArgs.buffer = buf; pthread_cleanup_push(cancel_handler, &cancelArgs); error = pthread_mutex_lock(&fileLock); if (likely(EXIT_SUCCESS == error)) { if (unlikely(LogStat & LOG_PERROR)) { /* add the format argument to the header */ const size_t n = strlen(format); const size_t size = bufsize + n + 1; char *logFormatBuffer = (char *)malloc(size); if (logFormatBuffer) { pthread_cleanup_push(free,logFormatBuffer); strcpyNcat(logFormatBuffer,buf,format); vfprintf(stderr, logFormatBuffer, optional_arguments); pthread_cleanup_pop(1); /* pop the handler and free the allocated memory */ } else { ERROR_MSG("failed to allocate %u bytes to print the msg on stderr",size); } } /* (LogStat & LOG_PERROR) */ /* file management */ if (unlikely(LOG_FILE_DURATION & LogStat)) { const time_t currentTime = time(NULL); const time_t elapsedTime = currentTime - startTime; if (unlikely(elapsedTime >= maxDuration)) { close(logFile); logFile = -1; } } /* (LOG_FILE_DURATION & LogStat) */ if (unlikely(-1 == logFile)) { error = createFile(); /* error already logged */ } if (likely(EXIT_SUCCESS == error)) { const ssize_t written = write(logFile,buf,n); if (written > 0) { if (unlikely(written != n)) { ERROR_MSG("only %d byte(s) of %d has been written to %s",written,n,fullFileName); if (LogStat & LOG_CONS) { int fd = open("/dev/console", O_WRONLY | O_NOCTTY, 0); if (fd >= 0 ) { dprintf(fd,"logMsg"); close(fd); fd = -1; } } /* (LogStat & LOG_CONS) */ if (unlikely((LogStat & LOG_FILE_SYNC_ON_ERRORS_ONLY) && (LOG_PRI(priority) <= LOG_ERR))) { /* flush data if the log priority is "upper" or equal to error */ error = fdatasync(logFile); if (error != 0) { error = errno; ERROR_MSG("fdatasync to %s error %d (%m)",fullFileName,error); } error = posix_fadvise(logFile, 0,0,POSIX_FADV_DONTNEED); /* tell the OS that log message bytes could be released from the file system cache */ if (error != 0) { ERROR_MSG("posix_fadvise to %s error %d (%m)",fullFileName,error); } } /* (unlikely((LogStat & LOG_FILE_SYNC_ON_ERRORS_ONLY) && (LOG_PRI(priority) <= LOG_ERR))) */ } /* (unlikely(written != n)) */ fileSize += written; #ifdef FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD static size_t currentPageCacheMaxSize = 0; currentPageCacheMaxSize += written; if (currentPageCacheMaxSize >= FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD) { /* tell the OS that log message bytes could be released from the file system cache */ if (likely(posix_fadvise(logFile, 0,0,POSIX_FADV_DONTNEED) == 0)) { currentPageCacheMaxSize = 0; DEBUG_MSG("used file system cache allowed to be flushed (size was %u)",currentPageCacheMaxSize); } else { NOTICE_MSG("posix_fadvise to %s error %d (%m), current page cache max size is %u",fullFileName,error,currentPageCacheMaxSize); } } #endif /* FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD */ if ((LOG_FILE_ROTATE & LogStat) || (LOG_FILE_HISTO & LogStat)) { if (fileSize >= maxSize) { close(logFile); logFile = -1; } } } else if (0 == written) { WARNING_MSG("nothing has been written in %s", fullFileName); } else { error = errno; ERROR_MSG("write to %s error %d (%m)", fullFileName, error); } } /*(likely(EXIT_SUCCESS == error)) */ /* End of critical section. */ /*pthread_cleanup_pop(0); implementation can't allow to set this instruction here */ /* free allocated ressources */ internalError = pthread_mutex_unlock(&fileLock); if (internalError != EXIT_SUCCESS) { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", internalError, strerror(internalError)); if (EXIT_SUCCESS == error) { error = internalError; } } /* (internalError != EXIT_SUCCESS) */ } else { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", error, strerror(error)); } pthread_cleanup_pop(0); /* moved to avoid a build error, use the preprocessor to understand why * or have a look on man 3 pthread_cleanup_push: * push & pop MUST BE in the SAME lexical nesting level !!! */ free(buf); cancelArgs.buffer = buf = NULL; } else { /* open_memstream(&buf, &bufsize) == NULL */ ERROR_MSG("failed to get stream buffer"); /* TMP! display the raw message to the console */ vfprintf(stderr,format,optional_arguments); /* TODO: write the raw message to the file */ } } /* ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) */ /* message has not to be displayed because of the current LogMask and its priority */ /*return n;*/ }
void run_tccode(void) { char * ccode; size_t ccodelen; FILE * ofd; TCCState *s; int rv; void * memp; #ifdef __STRICT_ANSI__ void * iso_workaround; #endif libtcc_specials = 1; ofd = open_memstream(&ccode, &ccodelen); if (ofd == NULL) { perror("open_memstream"); exit(7); } print_ccode(ofd); putc('\0', ofd); fclose(ofd); memp = map_hugeram(); s = tcc_new(); if (s == NULL) { perror("tcc_new()"); exit(7); } tcc_set_output_type(s, TCC_OUTPUT_MEMORY); tcc_compile_string(s, ccode); tcc_add_symbol(s, "mem", memp); /* If our code was read from stdin it'll be done in standard mode, * the stdio stream is now modal (always a bad idea) so it's been switched * to standard mode, stupidly, it's now impossible to switch it back. * * So have the loaded C code use our getch and putch functions. * * The ugly casting is forced by the C99 standard as a (void*) is not a * valid cast for a function pointer. */ #ifdef __STRICT_ANSI__ *(void_func*) &iso_workaround = (void_func) &getch; tcc_add_symbol(s, "getch", iso_workaround); *(void_func*) &iso_workaround = (void_func) &putch; tcc_add_symbol(s, "putch", iso_workaround); #else tcc_add_symbol(s, "getch", &getch); tcc_add_symbol(s, "putch", &putch); #if defined(__TCCLIB_VERSION) && __TCCLIB_VERSION == 0x000925 #define TCCDONE { int (*func)(void); int imagesize; void * image = 0; if (verbose) fprintf(stderr, "Running C Code using libtcc 9.25.\n"); imagesize = tcc_relocate(s, 0); if (imagesize <= 0) { fprintf(stderr, "tcc_relocate failed to return code size.\n"); exit(1); } image = malloc(imagesize); rv = tcc_relocate(s, image); if (rv) { fprintf(stderr, "tcc_relocate failed error=%d\n", rv); exit(1); } /* * The ugly casting is forced by the C99 standard as a (void*) is not a * valid cast for a function pointer. * *(void **) (&func) = tcc_get_symbol(s, "main"); */ func = tcc_get_symbol(s, "main"); if (!func) { fprintf(stderr, "Could not find compiled code entry point\n"); exit(1); } tcc_delete(s); free(ccode); start_runclock(); func(); finish_runclock(&run_time, &io_time); free(image); } #endif #if defined(__TCCLIB_VERSION) && __TCCLIB_VERSION == 0x000926 #define TCCDONE { int (*func)(void); if (verbose) fprintf(stderr, "Running C Code using libtcc 9.26.\n"); rv = tcc_relocate(s); if (rv) { perror("tcc_relocate()"); fprintf(stderr, "tcc_relocate failed return value=%d\n", rv); exit(1); } /* * The ugly casting is forced by the C99 standard as a (void*) is not a * valid cast for a function pointer. *(void **) (&func) = tcc_get_symbol(s, "main"); */ func = tcc_get_symbol(s, "main"); if (!func) { fprintf(stderr, "Could not find compiled code entry point\n"); exit(1); } start_runclock(); func(); finish_runclock(&run_time, &io_time); tcc_delete(s); free(ccode); } #endif #endif #if !defined(TCCDONE) { static char arg0_tcclib[] = "tcclib"; static char * args[] = {arg0_tcclib, 0}; /* Hmm, I want to do the above without named initialisers ... so it looks like this ... but without the const problem. static char * args[] = {"tcclib", 0}; */ if (verbose) fprintf(stderr, "Running C Code using libtcc tcc_run() to compile & run.\n"); rv = tcc_run(s, 1, args); if (verbose && rv) fprintf(stderr, "tcc_run returned %d\n", rv); tcc_delete(s); free(ccode); } #endif }
/* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines: * 0:/dev/pts/23 * pos: 0 * flags: 0100002 * * 1:/dev/pts/23 * pos: 0 * flags: 0100002 * * 2:/dev/pts/23 * pos: 0 * flags: 0100002 * EOF */ static int compose_open_fds(pid_t pid, char **open_fds) { _cleanup_closedir_ DIR *proc_fd_dir = NULL; _cleanup_close_ int proc_fdinfo_fd = -1; _cleanup_free_ char *buffer = NULL; _cleanup_fclose_ FILE *stream = NULL; const char *fddelim = "", *path; struct dirent *dent = NULL; size_t size = 0; int r = 0; assert(pid >= 0); assert(open_fds != NULL); path = procfs_file_alloca(pid, "fd"); proc_fd_dir = opendir(path); if (!proc_fd_dir) return -errno; proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH); if (proc_fdinfo_fd < 0) return -errno; stream = open_memstream(&buffer, &size); if (!stream) return -ENOMEM; FOREACH_DIRENT(dent, proc_fd_dir, return -errno) { _cleanup_fclose_ FILE *fdinfo = NULL; _cleanup_free_ char *fdname = NULL; char line[LINE_MAX]; int fd; r = readlinkat_malloc(dirfd(proc_fd_dir), dent->d_name, &fdname); if (r < 0) return r; fprintf(stream, "%s%s:%s\n", fddelim, dent->d_name, fdname); fddelim = "\n"; /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */ fd = openat(proc_fdinfo_fd, dent->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY); if (fd < 0) continue; fdinfo = fdopen(fd, "re"); if (fdinfo == NULL) { close(fd); continue; } FOREACH_LINE(line, fdinfo, break) { fputs(line, stream); if (!endswith(line, "\n")) fputc('\n', stream); } } errno = 0; stream = safe_fclose(stream); if (errno != 0) return -errno; *open_fds = buffer; buffer = NULL; return 0; }
int abrt_post(abrt_post_state_t *state, const char *url, const char *content_type, const char *data, off_t data_size) { CURLcode curl_err; long response_code; abrt_post_state_t localstate; VERB3 log("abrt_post('%s','%s')", url, data); if (!state) { memset(&localstate, 0, sizeof(localstate)); state = &localstate; } state->http_resp_code = response_code = -1; CURL *handle = xcurl_easy_init(); // Buffer[CURL_ERROR_SIZE] curl stores human readable error messages in. // This may be more helpful than just return code from curl_easy_perform. // curl will need it until curl_easy_cleanup. state->errmsg[0] = '\0'; xcurl_easy_setopt_ptr(handle, CURLOPT_ERRORBUFFER, state->errmsg); // Shut off the built-in progress meter completely xcurl_easy_setopt_long(handle, CURLOPT_NOPROGRESS, 1); if (g_verbose >= 2) { // "Display a lot of verbose information about its operations. // Very useful for libcurl and/or protocol debugging and understanding. // The verbose information will be sent to stderr, or the stream set // with CURLOPT_STDERR" xcurl_easy_setopt_long(handle, CURLOPT_VERBOSE, 1); xcurl_easy_setopt_ptr(handle, CURLOPT_DEBUGFUNCTION, curl_debug); } // TODO: do we need to check for CURLE_URL_MALFORMAT error *here*, // not in curl_easy_perform? xcurl_easy_setopt_ptr(handle, CURLOPT_URL, url); // Auth if configured if (state->username) { // bitmask of allowed auth methods xcurl_easy_setopt_long(handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); xcurl_easy_setopt_ptr(handle, CURLOPT_USERNAME, state->username); xcurl_easy_setopt_ptr(handle, CURLOPT_PASSWORD, (state->password ? state->password : "")); } // Do a regular HTTP post. This also makes curl use // a "Content-Type: application/x-www-form-urlencoded" header. // (This is by far the most commonly used POST method). xcurl_easy_setopt_long(handle, CURLOPT_POST, 1); // Supply POST data... struct curl_httppost* post = NULL; struct curl_httppost* last = NULL; FILE* data_file = NULL; if (data_size == ABRT_POST_DATA_FROMFILE) { // ...from a file data_file = fopen(data, "r"); if (!data_file) //FIXME: perror_msg_and_die("can't open '%s'", data); xcurl_easy_setopt_ptr(handle, CURLOPT_READDATA, data_file); // Want to use custom read function xcurl_easy_setopt_ptr(handle, CURLOPT_READFUNCTION, (const void*)fread_with_reporting); } else if (data_size == ABRT_POST_DATA_FROMFILE_AS_FORM_DATA) { // ...from a file, in multipart/formdata format const char *basename = strrchr(data, '/'); if (basename) basename++; else basename = data; #if 0 // Simple way, without custom reader function CURLFORMcode curlform_err = curl_formadd(&post, &last, CURLFORM_PTRNAME, "file", // element name CURLFORM_FILE, data, // filename to read from CURLFORM_CONTENTTYPE, content_type, CURLFORM_FILENAME, basename, // filename to put in the form CURLFORM_END); #else data_file = fopen(data, "r"); if (!data_file) //FIXME: perror_msg_and_die("can't open '%s'", data); // Want to use custom read function xcurl_easy_setopt_ptr(handle, CURLOPT_READFUNCTION, (const void*)fread_with_reporting); // Need to know file size fseeko(data_file, 0, SEEK_END); off_t sz = ftello(data_file); fseeko(data_file, 0, SEEK_SET); // Create formdata CURLFORMcode curlform_err = curl_formadd(&post, &last, CURLFORM_PTRNAME, "file", // element name // use CURLOPT_READFUNCTION for reading, pass data_file as its last param: CURLFORM_STREAM, data_file, CURLFORM_CONTENTSLENGTH, (long)sz, // a must if we use CURLFORM_STREAM option CURLFORM_CONTENTTYPE, content_type, CURLFORM_FILENAME, basename, // filename to put in the form CURLFORM_END); #endif if (curlform_err != 0) //FIXME: error_msg_and_die("out of memory or read error (curl_formadd error code: %d)", (int)curlform_err); xcurl_easy_setopt_ptr(handle, CURLOPT_HTTPPOST, post); } else { // .. from a blob in memory xcurl_easy_setopt_ptr(handle, CURLOPT_POSTFIELDS, data); // note1: if data_size == ABRT_POST_DATA_STRING == -1, curl will use strlen(data) xcurl_easy_setopt_long(handle, CURLOPT_POSTFIELDSIZE, data_size); // note2: CURLOPT_POSTFIELDSIZE_LARGE can't be used: xcurl_easy_setopt_long() // truncates data_size on 32-bit arch. Need xcurl_easy_setopt_long_long()? // Also, I'm not sure CURLOPT_POSTFIELDSIZE_LARGE special-cases -1. } struct curl_slist *httpheader_list = NULL; // Override "Content-Type:" if (data_size != ABRT_POST_DATA_FROMFILE_AS_FORM_DATA) { char *content_type_header = xasprintf("Content-Type: %s", content_type); // Note: curl_slist_append() copies content_type_header httpheader_list = curl_slist_append(httpheader_list, content_type_header); if (!httpheader_list) error_msg_and_die("out of memory"); free(content_type_header); xcurl_easy_setopt_ptr(handle, CURLOPT_HTTPHEADER, httpheader_list); } // Override "Accept: text/plain": helps convince server to send plain-text // error messages in the body of HTTP error responses [not verified to work] httpheader_list = curl_slist_append(httpheader_list, "Accept: text/plain"); if (!httpheader_list) error_msg_and_die("out of memory"); // Add User-Agent: ABRT/N.M httpheader_list = curl_slist_append(httpheader_list, "User-Agent: ABRT/"VERSION); if (!httpheader_list) error_msg_and_die("out of memory"); // Disabled: was observed to also handle "305 Use proxy" redirect, // apparently with POST->GET remapping - which server didn't like at all. // Attempted to suppress remapping on 305 using CURLOPT_POSTREDIR of -1, // but it still did not work. #if 0 // Please handle 301/302 redirects for me xcurl_easy_setopt_long(handle, CURLOPT_FOLLOWLOCATION, 1); xcurl_easy_setopt_long(handle, CURLOPT_MAXREDIRS, 10); // Bitmask to control how libcurl acts on redirects after POSTs. // Bit 0 set (value CURL_REDIR_POST_301) makes libcurl // not convert POST requests into GET requests when following // a 301 redirection. Bit 1 (value CURL_REDIR_POST_302) makes libcurl // maintain the request method after a 302 redirect. // CURL_REDIR_POST_ALL is a convenience define that sets both bits. // The non-RFC behaviour is ubiquitous in web browsers, so the library // does the conversion by default to maintain consistency. // However, a server may require a POST to remain a POST. xcurl_easy_setopt_long(handle, CURLOPT_POSTREDIR, -1L /*CURL_REDIR_POST_ALL*/ ); #endif // Prepare for saving information if (state->flags & ABRT_POST_WANT_HEADERS) { xcurl_easy_setopt_ptr(handle, CURLOPT_HEADERFUNCTION, (void*)save_headers); xcurl_easy_setopt_ptr(handle, CURLOPT_WRITEHEADER, state); } FILE* body_stream = NULL; if (state->flags & ABRT_POST_WANT_BODY) { body_stream = open_memstream(&state->body, &state->body_size); if (!body_stream) error_msg_and_die("out of memory"); xcurl_easy_setopt_ptr(handle, CURLOPT_WRITEDATA, body_stream); } if (!(state->flags & ABRT_POST_WANT_SSL_VERIFY)) { xcurl_easy_setopt_long(handle, CURLOPT_SSL_VERIFYPEER, 0); xcurl_easy_setopt_long(handle, CURLOPT_SSL_VERIFYHOST, 0); } // This is the place where everything happens. // Here errors are not limited to "out of memory", can't just die. curl_err = curl_easy_perform(handle); if (curl_err) { VERB2 log("curl_easy_perform: error %d", (int)curl_err); if (state->flags & ABRT_POST_WANT_ERROR_MSG) { state->curl_error_msg = check_curl_error(curl_err, "curl_easy_perform"); VERB3 log("curl_easy_perform: error_msg: %s", state->curl_error_msg); } goto ret; } // curl-7.20.1 doesn't do it, we get NULL body in the log message below // unless we fflush the body memstream ourself if (body_stream) fflush(body_stream); // Headers/body are already saved (if requested), extract more info curl_err = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &response_code); die_if_curl_error(curl_err); state->http_resp_code = response_code; VERB3 log("after curl_easy_perform: http code %ld body:'%s'", response_code, state->body); ret: curl_easy_cleanup(handle); if (httpheader_list) curl_slist_free_all(httpheader_list); if (body_stream) fclose(body_stream); if (data_file) fclose(data_file); if (post) curl_formfree(post); return response_code; }
OFCondition DJCompressJP2K::encode( Uint16 columns, Uint16 rows, EP_Interpretation colorSpace, Uint16 samplesPerPixel, Uint16 * image_buffer, Uint16 * & to, Uint32 & length, Uint8 bitsAllocated, Uint8 pixelRepresentation, double minUsed, double maxUsed) { int bitsstored = bitsAllocated; if( samplesPerPixel > 1) bitsstored = bitsAllocated = 8; OFBool isSigned = pixelRepresentation; if( bitsAllocated >= 16) { int amplitude = maxUsed; if( minUsed < 0) amplitude -= minUsed; int bits = 1, value = 2; while( value < amplitude && bits <= 16) { value *= 2; bits++; } if( minUsed < 0) // K A10009536850 22.06.12 bits++; if( bits < 9) bits = 9; // avoid the artifacts... switch to lossless if( (maxUsed >= 32000 && minUsed <= -32000) || maxUsed >= 65000 || bits > 16) quality = 0; if( bits > 16) bits = 16; bitsstored = bits; } opj_cparameters_t parameters; opj_image_t *image = NULL; // printf( "JP2K OPJ-DCMTK-Encode "); opj_set_default_encoder_parameters(¶meters); parameters.tcp_numlayers = 1; parameters.cp_disto_alloc = 1; switch( quality) { case 0: // DCMLosslessQuality parameters.tcp_rates[0] = 0; break; case 1: // DCMHighQuality parameters.tcp_rates[0] = 4; break; case 2: // DCMMediumQuality if( columns <= 600 || rows <= 600) parameters.tcp_rates[0] = 6; else parameters.tcp_rates[0] = 8; break; case 3: // DCMLowQuality parameters.tcp_rates[0] = 16; break; default: //printf( "****** warning unknown compression rate -> MediumQuality : %d", quality); if( columns <= 600 || rows <= 600) parameters.tcp_rates[0] = 6; else parameters.tcp_rates[0] = 8; break; } int image_width = columns; int image_height = rows; int sample_pixel = samplesPerPixel; if (colorSpace == EPI_Monochrome1 || colorSpace == EPI_Monochrome2) { } else { if( sample_pixel != 3) printf( "*** RGB Photometric?, but... SamplesPerPixel != 3 ?"); sample_pixel = 3; } image = rawtoimage( (char *)image_buffer, ¶meters, static_cast<int>( columns*rows*samplesPerPixel*bitsAllocated/8), image_width, image_height, sample_pixel, bitsAllocated, bitsstored, isSigned, quality, 0); if(!image) { fprintf(stderr, "Unable to load buffer image\n"); return EC_Normal; } parameters.cod_format = 0; /* J2K format output */ int codestream_length; opj_codec_t *l_codec = 00; l_codec = opj_create_compress(OPJ_CODEC_J2K); opj_set_info_handler(l_codec, info_callback,00); opj_set_warning_handler(l_codec, warning_callback,00); opj_set_error_handler(l_codec, error_callback,00); /* setup the encoder parameters using the current image and using user parameters */ opj_setup_encoder(l_codec, ¶meters, image); char * l_out; size_t l_size; FILE * l_file = open_memstream(&l_out, &l_size); opj_stream_t * l_stream = opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE, OPJ_FALSE); if (! l_stream){ fprintf(stderr, "failed to create stream\n"); return EC_Normal; } opj_stream_set_user_data(l_stream, l_file, (opj_stream_free_user_data_fn)NULL); opj_stream_set_write_function(l_stream, (opj_stream_write_fn)_write); /* encode the image */ int bSuccess = opj_start_compress(l_codec, image, l_stream); if (!bSuccess) { fprintf(stderr, "failed to encode image\n"); return EC_Normal; } bSuccess = bSuccess && opj_encode(l_codec, l_stream); if (!bSuccess) { opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(image); fprintf(stderr, "failed to encode image 2\n"); remove(parameters.outfile); return EC_Normal; } bSuccess = bSuccess && opj_end_compress(l_codec, l_stream); if (!bSuccess) { fprintf(stderr, "failed to encode image: opj_end_compress\n"); return EC_Normal; } /* l_file memstream must be flushed to allow accessint to l_out and l_size values */ fflush(l_file); #ifdef _WIN32 get_buffer_and_size(l_file); #endif fclose(l_file); /* copy compressed stream to "to" UINT8* */ to = new Uint16[l_size]; memcpy( to, l_out, l_size); length = l_size; /* free remaining compression structures */ free(l_out); opj_stream_destroy(l_stream); opj_destroy_codec(l_codec); opj_image_destroy(image); // } return EC_Normal; }
static telf_status headerfs_read_info(void *obj_hdl, char **bufp, size_t *buf_lenp) { telf_obj *obj = obj_hdl; size_t off = 0; int i; char ident_str[128] = ""; telf_status ret; char *buf = NULL; size_t buf_len = 0; FILE *out = NULL; ElfW(Ehdr) *ehdr = obj->ctx->ehdr; for (i = 0; i < EI_NIDENT; i++) off += sprintf(ident_str + off, "%.2x ", ehdr->e_ident[i]); out = open_memstream(&buf, &buf_len); if (! out) { ERR("open_memstream: %s", strerror(errno)); ret = ELF_ENOMEM; goto end; } fprintf(out, "Ident: %s\n" "Version: %d\n" "Class: %d\n" "Type: %s\n" "ELF Header size: %d bytes\n" "Entry point: %p\n" "Program Header offset: %lu bytes\n" "Program Header entry size: %d bytes\n" "Number of Program Header entries: %d\n" "Section Header offset: %lu bytes\n" "Section Header entry size: %d bytes\n" "Number of Section Header entries: %d\n" "SH string table index: %d\n", ident_str, ehdr->e_ident[EI_VERSION], ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? 64 : 32, headerfs_type_to_str(ehdr->e_type), ehdr->e_ehsize, (void *) ehdr->e_entry, ehdr->e_phoff, ehdr->e_phentsize, ehdr->e_phnum, ehdr->e_shoff, ehdr->e_shentsize, ehdr->e_shnum, ehdr->e_shstrndx); ret = ELF_SUCCESS; end: if (out) fclose(out); if (bufp) *bufp = buf; else free(buf); if (buf_lenp) *buf_lenp = buf_len; return ret; }
/* Show open FDs. */ static char * debug_fds (const char *subcmd, size_t argc, char *const *const argv) { int r; char *out; size_t size; FILE *fp; DIR *dir; struct dirent *d; char fname[256], link[256]; struct stat statbuf; fp = open_memstream (&out, &size); if (!fp) { reply_with_perror ("open_memstream"); return NULL; } dir = opendir ("/proc/self/fd"); if (!dir) { reply_with_perror ("opendir: /proc/self/fd"); fclose (fp); return NULL; } while ((d = readdir (dir)) != NULL) { if (STREQ (d->d_name, ".") || STREQ (d->d_name, "..")) continue; snprintf (fname, sizeof fname, "/proc/self/fd/%s", d->d_name); r = lstat (fname, &statbuf); if (r == -1) { reply_with_perror ("stat: %s", fname); fclose (fp); free (out); closedir (dir); return NULL; } if (S_ISLNK (statbuf.st_mode)) { r = readlink (fname, link, sizeof link - 1); if (r == -1) { reply_with_perror ("readline: %s", fname); fclose (fp); free (out); closedir (dir); return NULL; } link[r] = '\0'; fprintf (fp, "%2s %s\n", d->d_name, link); } else fprintf (fp, "%2s 0%o\n", d->d_name, statbuf.st_mode); } fclose (fp); if (closedir (dir) == -1) { reply_with_perror ("closedir"); free (out); return NULL; } return out; }