void kappa_fifo_parse_yuv4mpeg(char *group,kafifo_t *info) { if (strncmp(info->buffer,"YUV4MPEG2",9)) { fprintf(stderr,"Pipe name %s is not YUV4MPEG2, exitting now...\n",info->name); exit(1); } byte *headend = index(info->buffer,'\n'); int headlen; *headend = '\0'; headlen = strlen(info->buffer) + 1; fprintf(stderr,"Header output %s %d %s\n",group,headlen,info->buffer); *headend = '\n'; if (strstr(info->buffer," W")) { info->width = atoi(strstr(info->buffer," W") + 2); } if (strstr(info->buffer," H")) { info->height = atoi(strstr(info->buffer," H") + 2); } if (strstr(info->buffer," F")) { info->fps_num = atoi(strstr(info->buffer," F") + 2); info->fps_den = atoi(strstr(strstr(info->buffer," F") + 2,":") + 1); } if (strstr(info->buffer," A")) { info->aspect_num = atoi(strstr(info->buffer," A") + 2); info->aspect_den = atoi(strstr(strstr(info->buffer," A") + 2,":") + 1); } if (strstr(info->buffer," I")) { info->mode = *(strstr(info->buffer," I") + 2); } if (strstr(info->buffer," C")) { info->format = atoi(strstr(info->buffer," C") + 2); if (info->format == 420) info->pixfmt = AV_PIX_FMT_YUV420P; if (info->format == 422) info->pixfmt = AV_PIX_FMT_YUV422P; if (info->format == 444) info->pixfmt = AV_PIX_FMT_YUV444P; } info->framesize = avpicture_get_size(info->pixfmt,info->width,info->height); info->chunksize = info->framesize + strlen("FRAME\n"); fprintf(stderr,"Header output %s %d %d %d F%d:%d A%d:%d I%c %s framesize=%d\n", group, info->width,info->height, info->format, info->fps_num,info->fps_den, info->aspect_num,info->aspect_den, info->mode,av_get_pix_fmt_name(info->pixfmt), info->framesize); // // Remove header from buffer. // memcpy(info->buffer,info->buffer + headlen,info->bufsiz - headlen); info->iobytes -= headlen; // // Reallocate the current buffer to a multiple // of the frame chunk size including header. // int frames = (info->bufsiz / info->chunksize) + 1; byte *newbuf = (byte *) malloc(info->chunksize * frames); memcpy(newbuf,info->buffer,info->bufsiz); free(info->buffer); info->buffer = newbuf; info->bufsiz = info->chunksize * frames; info->wantimage = (kappa_fifo_stillsizes != NULL); info->wantscene = (kappa_fifo_sceneparam != NULL); info->wantstill = (kappa_fifo_stillparam != NULL); if (info->wantscene) { int error; sscanf(kappa_fifo_sceneparam,"%d:%d:%d",&info->threshold,&info->minframes,&info->maxframes); info->scenesizes = kappa_fifo_sceneparam; if (info->scenesizes) info->scenesizes = index(info->scenesizes + 1,':'); if (info->scenesizes) info->scenesizes = index(info->scenesizes + 1,':'); if (info->scenesizes) info->scenesizes = index(info->scenesizes + 1,':'); if (info->scenesizes) { info->scenesizes++; } else { info->scenesizes = "0x360:0x120"; } if (! info->threshold) info->threshold = 40; if (! info->minframes) info->minframes = 10; if (! info->maxframes) info->maxframes = 60 * 25; if (info->wantstill) { char *suffix = index(kappa_fifo_stillparam,':'); if (suffix) { snprintf(info->scenezipname,sizeof(info->scenezipname),"%s_%s.zip",kappa_fifo_fileprefix,suffix + 1); } else { snprintf(info->scenezipname,sizeof(info->scenezipname),"%s_stills.zip",kappa_fifo_fileprefix); } } else { snprintf(info->scenezipname,sizeof(info->scenezipname),"%s_scene.zip",kappa_fifo_fileprefix); } info->scenezip = zip_open(info->scenezipname,ZIP_CREATE + ZIP_TRUNCATE,&error); if (error == 0) { fprintf(stderr,"Header scene %s %s => %d %s\n",group,info->scenezipname,error,"Success"); } else { fprintf(stderr,"Header scene %s %s => %d %s\n",group,info->scenezipname,error,zip_strerror(info->scenezip)); } if (! info->scenezip) { fprintf(stderr,"Could not create scene zip %s %d, exitting now...\n",info->scenezipname,error); exit(1); } fprintf(stderr,"Scenezip:%s\n",info->scenezipname); fflush(stderr); } if (info->wantstill) { int numimages = atoi(kappa_fifo_stillparam); int intervall = (kappa_fifo_maxframe <= 0) ? (25 * 60) : (kappa_fifo_maxframe / numimages); info->threshold = 0; info->minframes = intervall; info->maxframes = intervall; info->scenemaximg = numimages; fprintf(stderr,"Header still %s %d %d %d\n",group,kappa_fifo_maxframe,numimages,intervall); } if (info->wantimage || info->wantscene) { info->stillframe = av_frame_alloc(); info->stillframe->format = info->pixfmt; info->stillframe->width = info->width; info->stillframe->height = info->height; info->stillalloc = 256 * 1024; info->stillbuffer = (uint8_t *) malloc(info->stillalloc); } info->haveheader = true; }
int main(int argc, char *argv[]) { struct zip *za; int c, err; char errstr[1024], *tname; prg = argv[0]; confirm = CONFIRM_ALL_YES; name_flags = 0; while ((c=getopt(argc, argv, OPTIONS)) != -1) { switch (c) { case 'D': name_flags |= ZIP_FL_NODIR; break; case 'i': confirm &= ~CONFIRM_ALL_YES; break; case 'I': name_flags |= ZIP_FL_NOCASE; break; case 's': confirm &= ~CONFIRM_SAME_NO; confirm |= CONFIRM_SAME_YES; break; case 'S': confirm &= ~CONFIRM_SAME_YES; confirm |= CONFIRM_SAME_NO; break; case 'h': fputs(help_head, stdout); printf(usage, prg); fputs(help, stdout); exit(0); case 'V': fputs(version_string, stdout); exit(0); default: fprintf(stderr, usage, prg); exit(2); } } if (argc < optind+2) { fprintf(stderr, usage, prg); exit(2); } tname = argv[optind++]; if ((za=zip_open(tname, ZIP_CREATE, &err)) == NULL) { zip_error_to_str(errstr, sizeof(errstr), err, errno); fprintf(stderr, "%s: cannot open zip archive `%s': %s\n", prg, tname, errstr); exit(1); } while (optind<argc) { if (merge_zip(za, tname, argv[optind++]) < 0) exit(1); } if (zip_close(za) < 0) { fprintf(stderr, "%s: cannot write zip archive `%s': %s\n", prg, tname, zip_strerror(za)); exit(1); } exit(0); }
BinaryInput::BinaryInput( const std::string& filename, G3DEndian fileEndian, bool compressed) : m_filename(filename), m_bitPos(0), m_bitString(0), m_beginEndBits(0), m_alreadyRead(0), m_length(0), m_bufferLength(0), m_buffer(NULL), m_pos(0), m_freeBuffer(true) { setEndian(fileEndian); // Update global file tracker _internal::currentFilesUsed.insert(m_filename); #if _HAVE_ZIP /* G3DFIX: Use ZIP-library only if defined */ std::string zipfile; if (FileSystem::inZipfile(m_filename, zipfile)) { // Load from zipfile // zipRead(filename, v, s); std::string internalFile = m_filename.substr(zipfile.length() + 1); struct zip* z = zip_open(zipfile.c_str(), ZIP_CHECKCONS, NULL); { struct zip_stat info; zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. zip_stat(z, internalFile.c_str(), ZIP_FL_NOCASE, &info); m_bufferLength = m_length = info.size; // sets machines up to use MMX, if they want m_buffer = reinterpret_cast<uint8*>(System::alignedMalloc(m_length, 16)); struct zip_file* zf = zip_fopen( z, internalFile.c_str(), ZIP_FL_NOCASE ); { int64 test = zip_fread( zf, m_buffer, m_length ); debugAssertM(test == m_length, internalFile + " was corrupt because it unzipped to the wrong size."); (void)test; } zip_fclose( zf ); } zip_close( z ); if (compressed) { decompress(); } m_freeBuffer = true; return; } #endif // Figure out how big the file is and verify that it exists. m_length = FileSystem::size(m_filename); // Read the file into memory FILE* file = fopen(m_filename.c_str(), "rb"); if (! file || (m_length == -1)) { throw format("File not found: \"%s\"", m_filename.c_str()); return; } if (! compressed && (m_length > INITIAL_BUFFER_LENGTH)) { // Read only a subset of the file so we don't consume // all available memory. m_bufferLength = INITIAL_BUFFER_LENGTH; } else { // Either the length is fine or the file is compressed // and requires us to read the whole thing for zlib. m_bufferLength = m_length; } debugAssert(m_freeBuffer); m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); if (m_buffer == NULL) { if (compressed) { throw "Not enough memory to load compressed file. (1)"; } // Try to allocate a small array; not much memory is available. // Give up if we can't allocate even 1k. while ((m_buffer == NULL) && (m_bufferLength > 1024)) { m_bufferLength /= 2; m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); } } debugAssert(m_buffer); fread(m_buffer, m_bufferLength, sizeof(int8), file); fclose(file); file = NULL; if (compressed) { if (m_bufferLength != m_length) { throw "Not enough memory to load compressed file. (2)"; } decompress(); } }
// TODO: This looks like should be ported to C code. or a big part of it. bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected) { static const char errPrefix[] = "divelog.de-upload:"; if (!amount_selected) { report_error(tr("no dives were selected").toUtf8()); return false; } xsltStylesheetPtr xslt = NULL; struct zip *zip; xslt = get_stylesheet("divelogs-export.xslt"); if (!xslt) { qDebug() << errPrefix << "missing stylesheet"; return false; } int error_code; zip = zip_open(QFile::encodeName(QDir::toNativeSeparators(tempfile)), ZIP_CREATE, &error_code); if (!zip) { char buffer[1024]; zip_error_to_str(buffer, sizeof buffer, error_code, errno); report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer); return false; } /* walk the dive list in chronological order */ int i; struct dive *dive; struct membuffer mb = { 0 }; for_each_dive (i, dive) { FILE *f; char filename[PATH_MAX]; int streamsize; const char *membuf; xmlDoc *transformed; struct zip_source *s; /* * Get the i'th dive in XML format so we can process it. * We need to save to a file before we can reload it back into memory... */ if (selected && !dive->selected) continue; /* make sure the buffer is empty and add the dive */ mb.len = 0; save_one_dive_to_mb(&mb, dive); membuf = mb_cstring(&mb); streamsize = strlen(membuf); /* * Parse the memory buffer into XML document and * transform it to divelogs.de format, finally dumping * the XML into a character buffer. */ xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0); if (!doc) { qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!"; report_error(tr("internal error").toUtf8()); goto error_close_zip; } free((void *)membuf); transformed = xsltApplyStylesheet(xslt, doc, NULL); xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize); xmlFreeDoc(doc); xmlFreeDoc(transformed); /* * Save the XML document into a zip file. */ snprintf(filename, PATH_MAX, "%d.xml", i + 1); s = zip_source_buffer(zip, membuf, streamsize, 1); if (s) { int64_t ret = zip_add(zip, filename, s); if (ret == -1) qDebug() << errPrefix << "failed to include dive:" << i; } }
static void test_read(void) { char *buf = NULL; ssize_t bufsize; size_t buftmp; struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); assert(zip != NULL); assert(0 == zip_entry_open(zip, "test\\test-1.txt")); assert(strlen(TESTDATA1) == zip_entry_size(zip)); assert(CRC32DATA1 == zip_entry_crc32(zip)); bufsize = zip_entry_read(zip, (void **)&buf, &buftmp); assert(bufsize == strlen(TESTDATA1)); assert((size_t)bufsize == buftmp); assert(0 == strncmp(buf, TESTDATA1, bufsize)); assert(0 == zip_entry_close(zip)); free(buf); buf = NULL; bufsize = 0; assert(0 == zip_entry_open(zip, "test/test-2.txt")); assert(strlen(TESTDATA2) == zip_entry_size(zip)); assert(CRC32DATA2 == zip_entry_crc32(zip)); bufsize = zip_entry_read(zip, (void **)&buf, NULL); assert((size_t)bufsize == strlen(TESTDATA2)); assert(0 == strncmp(buf, TESTDATA2, (size_t)bufsize)); assert(0 == zip_entry_close(zip)); free(buf); buf = NULL; bufsize = 0; assert(0 == zip_entry_open(zip, "test\\empty/")); assert(0 == strcmp(zip_entry_name(zip), "test/empty/")); assert(0 == zip_entry_size(zip)); assert(0 == zip_entry_crc32(zip)); assert(0 == zip_entry_close(zip)); buftmp = strlen(TESTDATA2); buf = calloc(buftmp, sizeof(char)); assert(0 == zip_entry_open(zip, "test/test-2.txt")); bufsize = zip_entry_noallocread(zip, (void *)buf, buftmp); assert(buftmp == (size_t)bufsize); assert(0 == strncmp(buf, TESTDATA2, buftmp)); assert(0 == zip_entry_close(zip)); free(buf); buf = NULL; bufsize = 0; buftmp = strlen(TESTDATA1); buf = calloc(buftmp, sizeof(char)); assert(0 == zip_entry_open(zip, "test/test-1.txt")); bufsize = zip_entry_noallocread(zip, (void *)buf, buftmp); assert(buftmp == (size_t)bufsize); assert(0 == strncmp(buf, TESTDATA1, buftmp)); assert(0 == zip_entry_close(zip)); free(buf); buf = NULL; bufsize = 0; zip_close(zip); }
int file_open(const char *fname1, const char *fname2, const u32 crc, char *fname) { int found = 0; struct zip_find_t file; char path[MAX_PATH]; sprintf(path, "%s/%s.zip", game_dir, fname1); if (zip_open(path) != -1) { if (zip_findfirst(&file)) { if (file.crc32 == crc) { found = 1; } else { while (zip_findnext(&file)) { if (file.crc32 == crc) { found = 1; break; } } } } if (!found) zip_close(); } if (!found && fname2 != NULL) { sprintf(path, "%s/%s.zip", game_dir, fname2); if (zip_open(path) != -1) { if (zip_findfirst(&file)) { if (file.crc32 == crc) { found = 1; } else { while (zip_findnext(&file)) { if (file.crc32 == crc) { found = 1; break; } } } } if (!found) zip_close(); } } if (found) { if (fname) strcpy(fname, file.name); rom_fd = zopen(file.name); return rom_fd; } return -1; }
void ZipArchive::Open(const String &fileName) { Int error = 0; mZipHandle = (zip*)zip_open(fileName.GetCString(), 0, &error); }
/** * Initialize a saved session file. * * @param filename The name of the filename to save the current session as. * Must not be NULL. * @param samplerate The samplerate to store for this session. * @param channels A NULL-terminated array of strings containing the names * of all the channels active in this session. * * @retval SR_OK Success * @retval SR_ERR_ARG Invalid arguments * @retval SR_ERR Other errors * * @since 0.3.0 */ SR_API int sr_session_save_init(const char *filename, uint64_t samplerate, char **channels) { FILE *meta; struct zip *zipfile; struct zip_source *versrc, *metasrc; int tmpfile, cnt, ret, i; char version[1], metafile[32], *s; if (!filename) { sr_err("%s: filename was NULL", __func__); return SR_ERR_ARG; } /* Quietly delete it first, libzip wants replace ops otherwise. */ unlink(filename); if (!(zipfile = zip_open(filename, ZIP_CREATE, &ret))) return SR_ERR; /* "version" */ version[0] = '2'; if (!(versrc = zip_source_buffer(zipfile, version, 1, 0))) return SR_ERR; if (zip_add(zipfile, "version", versrc) == -1) { sr_info("error saving version into zipfile: %s", zip_strerror(zipfile)); return SR_ERR; } /* init "metadata" */ strcpy(metafile, "sigrok-meta-XXXXXX"); if ((tmpfile = g_mkstemp(metafile)) == -1) return SR_ERR; close(tmpfile); meta = g_fopen(metafile, "wb"); fprintf(meta, "[global]\n"); fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION); /* metadata */ fprintf(meta, "[device 1]\n"); /* metadata */ fprintf(meta, "capturefile = logic-1\n"); cnt = 0; for (i = 0; channels[i]; i++) cnt++; fprintf(meta, "total probes = %d\n", cnt); s = sr_samplerate_string(samplerate); fprintf(meta, "samplerate = %s\n", s); g_free(s); for (i = 0; channels[i]; i++) fprintf(meta, "probe%d = %s\n", i + 1, channels[i]); fclose(meta); if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) { unlink(metafile); return SR_ERR; } if (zip_add(zipfile, "metadata", metasrc) == -1) { unlink(metafile); return SR_ERR; } if ((ret = zip_close(zipfile)) == -1) { sr_info("error saving zipfile: %s", zip_strerror(zipfile)); unlink(metafile); return SR_ERR; } unlink(metafile); return SR_OK; }
/** * Append data to an existing session file. * * The session file must have been created with sr_session_save_init() * or sr_session_save() beforehand. * * @param filename The name of the filename to append to. Must not be NULL. * @param buf The data to be appended. * @param unitsize The number of bytes per sample. * @param units The number of samples. * * @retval SR_OK Success * @retval SR_ERR_ARG Invalid arguments * @retval SR_ERR Other errors * * @since 0.3.0 */ SR_API int sr_session_append(const char *filename, unsigned char *buf, int unitsize, int units) { struct zip *archive; struct zip_source *logicsrc; zip_int64_t num_files; struct zip_file *zf; struct zip_stat zs; struct zip_source *metasrc; GKeyFile *kf; GError *error; gsize len; int chunk_num, next_chunk_num, tmpfile, ret, i; const char *entry_name; char *metafile, tmpname[32], chunkname[16]; if ((ret = sr_sessionfile_check(filename)) != SR_OK) return ret; if (!(archive = zip_open(filename, 0, &ret))) return SR_ERR; if (zip_stat(archive, "metadata", 0, &zs) == -1) return SR_ERR; metafile = g_malloc(zs.size); zf = zip_fopen_index(archive, zs.index, 0); zip_fread(zf, metafile, zs.size); zip_fclose(zf); /* * If the file was only initialized but doesn't yet have any * data it in, it won't have a unitsize field in metadata yet. */ error = NULL; kf = g_key_file_new(); if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, &error)) { sr_err("Failed to parse metadata: %s.", error->message); return SR_ERR; } g_free(metafile); tmpname[0] = '\0'; if (!g_key_file_has_key(kf, "device 1", "unitsize", &error)) { if (error && error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) { sr_err("Failed to check unitsize key: %s", error ? error->message : "?"); return SR_ERR; } /* Add unitsize field. */ g_key_file_set_integer(kf, "device 1", "unitsize", unitsize); metafile = g_key_file_to_data(kf, &len, &error); strcpy(tmpname, "sigrok-meta-XXXXXX"); if ((tmpfile = g_mkstemp(tmpname)) == -1) return SR_ERR; if (write(tmpfile, metafile, len) < 0) { sr_dbg("Failed to create new metadata: %s", strerror(errno)); g_free(metafile); unlink(tmpname); return SR_ERR; } close(tmpfile); if (!(metasrc = zip_source_file(archive, tmpname, 0, -1))) { sr_err("Failed to create zip source for metadata."); g_free(metafile); unlink(tmpname); return SR_ERR; } if (zip_replace(archive, zs.index, metasrc) == -1) { sr_err("Failed to replace metadata file."); g_free(metafile); unlink(tmpname); return SR_ERR; } g_free(metafile); } g_key_file_free(kf); next_chunk_num = 1; num_files = zip_get_num_entries(archive, 0); for (i = 0; i < num_files; i++) { entry_name = zip_get_name(archive, i, 0); if (strncmp(entry_name, "logic-1", 7)) continue; if (strlen(entry_name) == 7) { /* This file has no extra chunks, just a single "logic-1". * Rename it to "logic-1-1" * and continue with chunk 2. */ if (zip_rename(archive, i, "logic-1-1") == -1) { sr_err("Failed to rename 'logic-1' to 'logic-1-1'."); unlink(tmpname); return SR_ERR; } next_chunk_num = 2; break; } else if (strlen(entry_name) > 8 && entry_name[7] == '-') { chunk_num = strtoull(entry_name + 8, NULL, 10); if (chunk_num >= next_chunk_num) next_chunk_num = chunk_num + 1; } } snprintf(chunkname, 15, "logic-1-%d", next_chunk_num); if (!(logicsrc = zip_source_buffer(archive, buf, units * unitsize, FALSE))) { unlink(tmpname); return SR_ERR; } if (zip_add(archive, chunkname, logicsrc) == -1) { unlink(tmpname); return SR_ERR; } if ((ret = zip_close(archive)) == -1) { sr_info("error saving session file: %s", zip_strerror(archive)); unlink(tmpname); return SR_ERR; } unlink(tmpname); return SR_OK; }
/** * Load the session from the specified filename. * * @param filename The name of the session file to load. Must not be NULL. * * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, * SR_ERR_MALLOC upon memory allocation errors, or SR_ERR upon * other errors. */ SR_API int sr_session_load(const char *filename) { GKeyFile *kf; GPtrArray *capturefiles; struct zip *archive; struct zip_file *zf; struct zip_stat zs; struct sr_dev_inst *sdi; struct sr_channel *probe; int ret, devcnt, i, j, k; uint16_t probenum; uint64_t tmp_u64, total_probes, enabled_probes; uint16_t p; char **sections, **keys, *metafile, *val, s[11]; char probename[SR_MAX_PROBENAME_LEN + 1]; int mode = LOGIC; int channel_type = SR_CHANNEL_LOGIC; double tmp_double; if (!filename) { sr_err("%s: filename was NULL", __func__); return SR_ERR_ARG; } if (!(archive = zip_open(filename, 0, &ret))) { sr_dbg("Failed to open session file: zip error %d", ret); return SR_ERR; } /* read "metadata" */ if (zip_stat(archive, "header", 0, &zs) == -1) { sr_dbg("Not a valid DSView data file."); return SR_ERR; } if (!(metafile = g_try_malloc(zs.size))) { sr_err("%s: metafile malloc failed", __func__); return SR_ERR_MALLOC; } zf = zip_fopen_index(archive, zs.index, 0); zip_fread(zf, metafile, zs.size); zip_fclose(zf); kf = g_key_file_new(); if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, NULL)) { sr_dbg("Failed to parse metadata."); return SR_ERR; } sr_session_new(); devcnt = 0; capturefiles = g_ptr_array_new_with_free_func(g_free); sections = g_key_file_get_groups(kf, NULL); for (i = 0; sections[i]; i++) { if (!strcmp(sections[i], "version")) /* nothing really interesting in here yet */ continue; if (!strncmp(sections[i], "header", 6)) { /* device section */ sdi = NULL; enabled_probes = total_probes = 0; keys = g_key_file_get_keys(kf, sections[i], NULL, NULL); for (j = 0; keys[j]; j++) { val = g_key_file_get_string(kf, sections[i], keys[j], NULL); if (!strcmp(keys[j], "device mode")) { mode = strtoull(val, NULL, 10); } else if (!strcmp(keys[j], "capturefile")) { sdi = sr_dev_inst_new(mode, devcnt, SR_ST_ACTIVE, NULL, NULL, NULL); sdi->driver = &session_driver; if (devcnt == 0) /* first device, init the driver */ sdi->driver->init(NULL); sr_dev_open(sdi); sr_session_dev_add(sdi); sdi->driver->config_set(SR_CONF_SESSIONFILE, g_variant_new_bytestring(filename), sdi, NULL, NULL); sdi->driver->config_set(SR_CONF_CAPTUREFILE, g_variant_new_bytestring(val), sdi, NULL, NULL); g_ptr_array_add(capturefiles, val); } else if (!strcmp(keys[j], "samplerate")) { sr_parse_sizestring(val, &tmp_u64); sdi->driver->config_set(SR_CONF_SAMPLERATE, g_variant_new_uint64(tmp_u64), sdi, NULL, NULL); } else if (!strcmp(keys[j], "unitsize")) { tmp_u64 = strtoull(val, NULL, 10); sdi->driver->config_set(SR_CONF_CAPTURE_UNITSIZE, g_variant_new_uint64(tmp_u64), sdi, NULL, NULL); } else if (!strcmp(keys[j], "total samples")) { tmp_u64 = strtoull(val, NULL, 10); sdi->driver->config_set(SR_CONF_LIMIT_SAMPLES, g_variant_new_uint64(tmp_u64), sdi, NULL, NULL); } else if (!strcmp(keys[j], "hDiv")) { tmp_u64 = strtoull(val, NULL, 10); sdi->driver->config_set(SR_CONF_TIMEBASE, g_variant_new_uint64(tmp_u64), sdi, NULL, NULL); } else if (!strcmp(keys[j], "total probes")) { total_probes = strtoull(val, NULL, 10); sdi->driver->config_set(SR_CONF_CAPTURE_NUM_PROBES, g_variant_new_uint64(total_probes), sdi, NULL, NULL); channel_type = (mode == DSO) ? SR_CHANNEL_DSO : (mode == ANALOG) ? SR_CHANNEL_ANALOG : SR_CHANNEL_LOGIC; for (p = 0; p < total_probes; p++) { snprintf(probename, SR_MAX_PROBENAME_LEN, "%" PRIu64, p); if (!(probe = sr_channel_new(p, channel_type, FALSE, probename))) return SR_ERR; sdi->channels = g_slist_append(sdi->channels, probe); } } else if (!strncmp(keys[j], "probe", 5)) { if (!sdi) continue; enabled_probes++; tmp_u64 = strtoul(keys[j]+5, NULL, 10); /* sr_session_save() */ sr_dev_probe_name_set(sdi, tmp_u64, val); sr_dev_probe_enable(sdi, tmp_u64, TRUE); } else if (!strncmp(keys[j], "trigger", 7)) { probenum = strtoul(keys[j]+7, NULL, 10); sr_dev_trigger_set(sdi, probenum, val); } else if (!strncmp(keys[j], "enable", 6)) { probenum = strtoul(keys[j]+6, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_EN_CH, g_variant_new_boolean(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "coupling", 8)) { probenum = strtoul(keys[j]+8, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_COUPLING, g_variant_new_byte(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "vDiv", 4)) { probenum = strtoul(keys[j]+4, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_VDIV, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "vFactor", 7)) { probenum = strtoul(keys[j]+7, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_FACTOR, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "vPos", 4)) { probenum = strtoul(keys[j]+4, NULL, 10); tmp_double = strtod(val, NULL); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_VPOS, g_variant_new_double(tmp_double), sdi, probe, NULL); } } else if (!strncmp(keys[j], "period", 6)) { probenum = strtoul(keys[j]+6, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_STATUS_PERIOD, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "pcnt", 4)) { probenum = strtoul(keys[j]+4, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_STATUS_PCNT, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "max", 3)) { probenum = strtoul(keys[j]+3, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_STATUS_MAX, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } else if (!strncmp(keys[j], "min", 3)) { probenum = strtoul(keys[j]+3, NULL, 10); tmp_u64 = strtoull(val, NULL, 10); if (probenum < g_slist_length(sdi->channels)) { probe = g_slist_nth(sdi->channels, probenum)->data; sdi->driver->config_set(SR_CONF_STATUS_MIN, g_variant_new_uint64(tmp_u64), sdi, probe, NULL); } } } g_strfreev(keys); } devcnt++; } g_strfreev(sections); g_key_file_free(kf); return SR_OK; }
/** * Save the current session to the specified file. * * @param filename The name of the filename to save the current session as. * Must not be NULL. * @param sdi The device instance from which the data was captured. * @param buf The data to be saved. * @param unitsize The number of bytes per sample. * @param units The number of samples. * * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or SR_ERR * upon other errors. */ SR_API int sr_session_save(const char *filename, const struct sr_dev_inst *sdi, unsigned char *buf, int unitsize, int units) { GSList *l; GVariant *gvar; FILE *meta; struct sr_channel *probe; struct zip *zipfile; struct zip_source *versrc, *metasrc, *logicsrc; int tmpfile, ret, probecnt; uint64_t samplerate, timeBase, tmp_u64; char rawname[16], metafile[32], *s; struct sr_status status; if (!filename) { sr_err("%s: filename was NULL", __func__); return SR_ERR_ARG; } /* Quietly delete it first, libzip wants replace ops otherwise. */ unlink(filename); if (!(zipfile = zip_open(filename, ZIP_CREATE, &ret))) return SR_ERR; /* init "metadata" */ strcpy(metafile, "DSView-meta-XXXXXX"); if ((tmpfile = g_mkstemp(metafile)) == -1) return SR_ERR; close(tmpfile); meta = g_fopen(metafile, "wb"); fprintf(meta, "[version]\n"); fprintf(meta, "DSView version = %s\n", PACKAGE_VERSION); /* metadata */ fprintf(meta, "[header]\n"); if (sdi->driver) { fprintf(meta, "driver = %s\n", sdi->driver->name); fprintf(meta, "device mode = %d\n", sdi->mode); } /* metadata */ fprintf(meta, "capturefile = data\n"); fprintf(meta, "unitsize = %d\n", unitsize); fprintf(meta, "total samples = %d\n", units); fprintf(meta, "total probes = %d\n", g_slist_length(sdi->channels)); if (sr_config_get(sdi->driver, sdi, NULL, NULL, SR_CONF_SAMPLERATE, &gvar) == SR_OK) { samplerate = g_variant_get_uint64(gvar); s = sr_samplerate_string(samplerate); fprintf(meta, "samplerate = %s\n", s); g_free(s); g_variant_unref(gvar); } if (sdi->mode == DSO && sr_config_get(sdi->driver, sdi, NULL, NULL, SR_CONF_TIMEBASE, &gvar) == SR_OK) { timeBase = g_variant_get_uint64(gvar); fprintf(meta, "hDiv = %d\n", timeBase); g_variant_unref(gvar); } probecnt = 1; for (l = sdi->channels; l; l = l->next) { probe = l->data; if (probe->enabled || sdi->mode == DSO) { if (probe->name) fprintf(meta, "probe%d = %s\n", probe->index, probe->name); if (probe->trigger) fprintf(meta, " trigger%d = %s\n", probe->index, probe->trigger); if (sdi->mode == DSO) { fprintf(meta, " enable%d = %d\n", probe->index, probe->enabled); fprintf(meta, " coupling%d = %d\n", probe->index, probe->coupling); fprintf(meta, " vDiv%d = %d\n", probe->index, probe->vdiv); fprintf(meta, " vFactor%d = %d\n", probe->index, probe->vfactor); fprintf(meta, " vPos%d = %lf\n", probe->index, probe->vpos); if (sr_status_get(sdi, &status, 0, 0) == SR_OK) { if (probe->index == 0) { fprintf(meta, " period%d = %d\n", probe->index, status.ch0_period); fprintf(meta, " pcnt%d = %d\n", probe->index, status.ch0_pcnt); fprintf(meta, " max%d = %d\n", probe->index, status.ch0_max); fprintf(meta, " min%d = %d\n", probe->index, status.ch0_min); } else { fprintf(meta, " period%d = %d\n", probe->index, status.ch1_period); fprintf(meta, " pcnt%d = %d\n", probe->index, status.ch1_pcnt); fprintf(meta, " max%d = %d\n", probe->index, status.ch1_max); fprintf(meta, " min%d = %d\n", probe->index, status.ch1_min); } } } probecnt++; } } if (!(logicsrc = zip_source_buffer(zipfile, buf, units * unitsize, FALSE))) return SR_ERR; snprintf(rawname, 15, "data"); if (zip_add(zipfile, rawname, logicsrc) == -1) return SR_ERR; fclose(meta); if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) return SR_ERR; if (zip_add(zipfile, "header", metasrc) == -1) return SR_ERR; if ((ret = zip_close(zipfile)) == -1) { sr_info("error saving zipfile: %s", zip_strerror(zipfile)); return SR_ERR; } unlink(metafile); return SR_OK; }
/** * Content handler. * * @param r * Request structure pointer * @return * Response status */ static ngx_int_t ngx_http_unzip_handler(ngx_http_request_t *r) { ngx_buf_t *b; ngx_chain_t out; ngx_str_t unzip_filename; ngx_str_t unzip_extract; struct zip *zip_source; struct zip_stat zip_st; struct zip_file *file_in_zip; int err = 0; char *unzipfile_path; char *unzipextract_path; unsigned char *zip_content; unsigned int zip_read_bytes; ngx_http_unzip_loc_conf_t *unzip_config; unzip_config = ngx_http_get_module_loc_conf(r, ngx_http_unzip_module); /* let's try to get file_in_unzip_archivefile and file_in_unzip_extract from nginx configuration */ if (ngx_http_complex_value(r, unzip_config->file_in_unzip_archivefile, &unzip_filename) != NGX_OK || ngx_http_complex_value(r, unzip_config->file_in_unzip_extract, &unzip_extract) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to read unzip module configuration settings."); return NGX_ERROR; } /* we're supporting just GET and HEAD requests */ if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Only GET and HEAD requests are supported by the unzip module."); return NGX_HTTP_NOT_ALLOWED; } /* fill path variables with 0 as ngx_string_t doesn't terminate string with 0 */ unzipfile_path = malloc(unzip_filename.len+1); if (unzipfile_path == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate buffer."); return NGX_HTTP_INTERNAL_SERVER_ERROR; } unzipextract_path = malloc(unzip_extract.len+1); if (unzipextract_path == NULL) { free(unzipfile_path); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate buffer."); return NGX_HTTP_INTERNAL_SERVER_ERROR; } memset(unzipfile_path, 0, unzip_filename.len+1); memset(unzipextract_path, 0, unzip_extract.len+1); /* get path variables terminated with 0 */ strncpy(unzipfile_path, (char *)unzip_filename.data, unzip_filename.len); strncpy(unzipextract_path, (char *)unzip_extract.data, unzip_extract.len); /* try to open archive (zip) file */ if (!(zip_source = zip_open(unzipfile_path, 0, &err))) { free(unzipfile_path); free(unzipextract_path); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "%s : no such archive file.", unzipfile_path); return NGX_HTTP_NOT_FOUND; } /* initialize structure */ zip_stat_init(&zip_st); /* let's check what's the size of a file. return 404 if we can't stat file inside archive */ if (0 != zip_stat(zip_source, unzipextract_path, 0, &zip_st)) { free(unzipfile_path); free(unzipextract_path); zip_close(zip_source); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "no file %s inside %s archive.", unzipextract_path, unzipfile_path); return NGX_HTTP_NOT_FOUND; } /* allocate buffer for the file content */ if (!(zip_content = ngx_palloc(r->pool, zip_st.size))) { free(unzipfile_path); free(unzipextract_path); zip_close(zip_source); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer memory."); return NGX_HTTP_INTERNAL_SERVER_ERROR; } /* * try to open a file that we want - if not return 500 as we know that the file is there (making zip_stat before) * so let's return 500. */ if (!(file_in_zip = zip_fopen(zip_source, unzipextract_path, 0))) { free(unzipfile_path); free(unzipextract_path); zip_close(zip_source); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to open %s from %s archive (corrupted?).", unzipextract_path, unzipfile_path); return NGX_HTTP_INTERNAL_SERVER_ERROR; } /* * let's get file content and check if we got all * we're expecting to get zip_st.size bytes so return 500 if we get something else. */ if (!(zip_read_bytes = zip_fread(file_in_zip, zip_content, zip_st.size)) || zip_read_bytes != zip_st.size) { free(unzipfile_path); free(unzipextract_path); zip_fclose(file_in_zip); zip_close(zip_source); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "couldn't get %d bytes of %s from %s archive (corrupted?).", zip_st.size, unzipextract_path, unzipfile_path); return NGX_HTTP_INTERNAL_SERVER_ERROR; } /* close both files */ zip_fclose(file_in_zip); zip_close(zip_source); /* let's clean */ free(unzipfile_path); free(unzipextract_path); /* set the content-type header. */ if (ngx_http_set_content_type(r) != NGX_OK) { r->headers_out.content_type.len = sizeof("text/plain") - 1; r->headers_out.content_type.data = (u_char *) "text/plain"; } /* allocate a new buffer for sending out the reply. */ b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer."); return NGX_HTTP_INTERNAL_SERVER_ERROR; } /* insertion in the buffer chain. */ out.buf = b; out.next = NULL; /* just one buffer */ b->pos = zip_content; b->last = zip_content + zip_read_bytes; b->memory = 1; b->last_buf = 1; /* sending the headers for the reply. */ r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = zip_read_bytes; ngx_http_send_header(r); return ngx_http_output_filter(r, &out); } /* ngx_http_unzip_handler */
int main(int argc, char *argv[]) { const char *archive; struct zip *za, *z_in; struct zip_source *zs; char buf[100]; int c, arg, err, flags, idx; flags = 0; prg = argv[0]; if (argc < 2) { fprintf(stderr, usage, prg); return 1; } while ((c=getopt(argc, argv, "cent")) != -1) { switch (c) { case 'c': flags |= ZIP_CHECKCONS; break; case 'e': flags |= ZIP_EXCL; break; case 'n': flags |= ZIP_CREATE; break; case 't': flags |= ZIP_TRUNCATE; break; default: fprintf(stderr, usage, argv[0]); return 1; } } arg = optind; archive = argv[arg++]; if (flags == 0) flags = ZIP_CREATE; if ((za=zip_open(archive, flags, &err)) == NULL) { zip_error_to_str(buf, sizeof(buf), err, errno); fprintf(stderr, "can't open zip archive `%s': %s\n", archive, buf); return 1; } err = 0; while (arg < argc) { if (strcmp(argv[arg], "add") == 0 && arg+2 < argc) { /* add */ if ((zs=zip_source_buffer(za, argv[arg+2], strlen(argv[arg+2]), 0)) == NULL) { fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za)); err = 1; break; } if (zip_add(za, argv[arg+1], zs) == -1) { zip_source_free(zs); fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za)); err = 1; break; } arg += 3; } else if (strcmp(argv[arg], "add_dir") == 0 && arg+1 < argc) { /* add directory */ if (zip_add_dir(za, argv[arg+1]) < 0) { fprintf(stderr, "can't add directory `%s': %s\n", argv[arg+1], zip_strerror(za)); err = 1; break; } arg += 2; } else if (strcmp(argv[arg], "add_file") == 0 && arg+4 < argc) { /* add */ if ((zs=zip_source_file(za, argv[arg+2], atoi(argv[arg+3]), atoi(argv[arg+4]))) == NULL) { fprintf(stderr, "can't create zip_source from file: %s\n", zip_strerror(za)); err = 1; break; } if (zip_add(za, argv[arg+1], zs) == -1) { zip_source_free(zs); fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za)); err = 1; break; } arg += 5; } else if (strcmp(argv[arg], "add_from_zip") == 0 && arg+5 < argc) { /* add from another zip file */ idx = atoi(argv[arg+3]); if ((z_in=zip_open(argv[arg+2], ZIP_CHECKCONS, &err)) == NULL) { zip_error_to_str(buf, sizeof(buf), err, errno); fprintf(stderr, "can't open source zip archive `%s': %s\n", argv[arg+2], buf); err = 1; break; } if ((zs=zip_source_zip(za, z_in, idx, 0, atoi(argv[arg+4]), atoi(argv[arg+5]))) == NULL) { fprintf(stderr, "error creating file source from `%s' index '%d': %s\n", argv[arg+2], idx, zip_strerror(za)); zip_close(z_in); err = 1; break; } if (zip_add(za, argv[arg+1], zs) == -1) { fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za)); zip_source_free(zs); zip_close(z_in); err = 1; break; } arg += 6; } else if (strcmp(argv[arg], "count_extra") == 0 && arg+2 < argc) { zip_int16_t count; zip_flags_t ceflags = 0; idx = atoi(argv[arg+1]); ceflags = get_flags(argv[arg+2]); if ((count=zip_file_extra_fields_count(za, idx, ceflags)) < 0) { fprintf(stderr, "can't get extra field count for file at index `%d': %s\n", idx, zip_strerror(za)); err = 1; break; } else { printf("Extra field count: %d\n", count); } arg += 3; } else if (strcmp(argv[arg], "count_extra_by_id") == 0 && arg+3 < argc) { zip_int16_t count, eid; zip_flags_t ceflags = 0; idx = atoi(argv[arg+1]); eid = atoi(argv[arg+2]); ceflags = get_flags(argv[arg+3]); if ((count=zip_file_extra_fields_count_by_id(za, idx, eid, ceflags)) < 0) { fprintf(stderr, "can't get extra field count for file at index `%d' and for id `%d': %s\n", idx, eid, zip_strerror(za)); err = 1; break; } else { printf("Extra field count: %d\n", count); } arg += 4; } else if (strcmp(argv[arg], "delete") == 0 && arg+1 < argc) { /* delete */ idx = atoi(argv[arg+1]); if (zip_delete(za, idx) < 0) { fprintf(stderr, "can't delete file at index `%d': %s\n", idx, zip_strerror(za)); err = 1; break; } arg += 2; } else if (strcmp(argv[arg], "delete_extra") == 0 && arg+1 < argc) { zip_flags_t geflags; zip_uint16_t eid; idx = atoi(argv[arg+1]); eid = atoi(argv[arg+2]); geflags = get_flags(argv[arg+3]); if ((zip_file_extra_field_delete(za, idx, eid, geflags)) < 0) { fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d': %s\n", idx, eid, zip_strerror(za)); err = 1; break; } arg += 4; } else if (strcmp(argv[arg], "delete_extra_by_id") == 0 && arg+1 < argc) { zip_flags_t geflags; zip_uint16_t eid, eidx; idx = atoi(argv[arg+1]); eid = atoi(argv[arg+2]); eidx = atoi(argv[arg+3]); geflags = get_flags(argv[arg+4]); if ((zip_file_extra_field_delete_by_id(za, idx, eid, eidx, geflags)) < 0) { fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d', extra field idx `%d': %s\n", idx, eid, eidx, zip_strerror(za)); err = 1; break; } arg += 5; } else if (strcmp(argv[arg], "get_archive_comment") == 0) { const char *comment; int len; /* get archive comment */ if ((comment=zip_get_archive_comment(za, &len, 0)) == NULL) printf("No archive comment\n"); else printf("Archive comment: %.*s\n", len, comment); arg += 1; } else if (strcmp(argv[arg], "get_extra") == 0 && arg+3 < argc) { zip_flags_t geflags; zip_uint16_t id, eidx, eflen; const zip_uint8_t *efdata; /* get extra field data */ idx = atoi(argv[arg+1]); eidx = atoi(argv[arg+2]); geflags = get_flags(argv[arg+3]); if ((efdata=zip_file_extra_field_get(za, idx, eidx, &id, &eflen, geflags)) == NULL) { fprintf(stderr, "can't get extra field data for file at index %d, extra field %d, flags %u: %s\n", idx, eidx, geflags, zip_strerror(za)); err = 1; } else { printf("Extra field 0x%04x: len %d", id, eflen); if (eflen > 0) { printf(", data "); hexdump(efdata, eflen); } printf("\n"); } arg += 4; } else if (strcmp(argv[arg], "get_extra_by_id") == 0 && arg+4 < argc) { zip_flags_t geflags; zip_uint16_t eid, eidx, eflen; const zip_uint8_t *efdata; idx = atoi(argv[arg+1]); eid = atoi(argv[arg+2]); eidx = atoi(argv[arg+3]); geflags = get_flags(argv[arg+4]); if ((efdata=zip_file_extra_field_get_by_id(za, idx, eid, eidx, &eflen, geflags)) == NULL) { fprintf(stderr, "can't get extra field data for file at index %d, extra field id %d, ef index %d, flags %u: %s\n", idx, eid, eidx, geflags, zip_strerror(za)); err = 1; } else { printf("Extra field 0x%04x: len %d", eid, eflen); if (eflen > 0) { printf(", data "); hexdump(efdata, eflen); } printf("\n"); } arg += 5; } else if (strcmp(argv[arg], "get_file_comment") == 0 && arg+1 < argc) { const char *comment; int len; /* get file comment */ idx = atoi(argv[arg+1]); if ((comment=zip_get_file_comment(za, idx, &len, 0)) == NULL) { fprintf(stderr, "can't get comment for `%s': %s\n", zip_get_name(za, idx, 0), zip_strerror(za)); err = 1; break; } else if (len == 0) printf("No comment for `%s'\n", zip_get_name(za, idx, 0)); else printf("File comment for `%s': %.*s\n", zip_get_name(za, idx, 0), len, comment); arg += 2; } else if (strcmp(argv[arg], "rename") == 0 && arg+2 < argc) { /* rename */ idx = atoi(argv[arg+1]); if (zip_rename(za, idx, argv[arg+2]) < 0) { fprintf(stderr, "can't rename file at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za)); err = 1; break; } arg += 3; } else if (strcmp(argv[arg], "set_extra") == 0 && arg+5 < argc) { zip_flags_t geflags; zip_uint16_t eid, eidx; const zip_uint8_t *efdata; idx = atoi(argv[arg+1]); eid = atoi(argv[arg+2]); eidx = atoi(argv[arg+3]); geflags = get_flags(argv[arg+4]); efdata = (zip_uint8_t *)argv[arg+5]; if ((zip_file_extra_field_set(za, idx, eid, eidx, efdata, (zip_uint16_t)strlen((const char *)efdata), geflags)) < 0) { fprintf(stderr, "can't set extra field data for file at index `%d', extra field id `%d', index `%d': %s\n", idx, eid, eidx, zip_strerror(za)); err = 1; break; } arg += 6; } else if (strcmp(argv[arg], "set_file_comment") == 0 && arg+2 < argc) { /* set file comment */ idx = atoi(argv[arg+1]); if (zip_file_set_comment(za, idx, argv[arg+2], (zip_uint16_t)strlen(argv[arg+2]), 0) < 0) { fprintf(stderr, "can't set file comment at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za)); err = 1; break; } arg += 3; } else if (strcmp(argv[arg], "set_file_compression") == 0 && arg+3 < argc) { /* set file compression */ zip_int32_t method; zip_uint32_t flags; idx = atoi(argv[arg+1]); method = get_compression_method(argv[arg+2]); flags = atoi(argv[arg+3]); if (zip_set_file_compression(za, idx, method, flags) < 0) { fprintf(stderr, "can't set file compression method at index `%d' to `%s', flags `%d': %s\n", idx, argv[arg+2], flags, zip_strerror(za)); err = 1; break; } arg += 4; } else { fprintf(stderr, "unrecognized command `%s', or not enough arguments\n", argv[arg]); err = 1; break; } } if (zip_close(za) == -1) { fprintf(stderr, "can't close zip archive `%s': %s\n", archive, zip_strerror(za)); return 1; } return err; }
bool extractMap(const std::string& file) { int err = 0; zip* zipFile = zip_open(file.c_str(), 0, &err); if(!zipFile) { std::cout << "[ERROR]: Failed to open archive file: " << file << ".\n"; return false; } auto fileNumber = zip_get_num_entries(zipFile, 0); std::string folderName = file.substr(0, file.find_last_of('.')) + "/"; // cut off file extension, add dir char stripWebChars(folderName); if(!makeFolder(folderName)) return false; for(auto i = 0u; i < fileNumber; i++) { zip_file* zipped = zip_fopen_index(zipFile, i, 0); struct zip_stat fileInfo; zip_stat_init(&fileInfo); zip_stat_index(zipFile, i, 0, &fileInfo); if(fileInfo.valid & ZIP_STAT_NAME && fileInfo.valid & ZIP_STAT_SIZE && fileInfo.valid & ZIP_STAT_COMP_SIZE) { std::string fileStr = fileInfo.name; if(fileStr.find('.') == std::string::npos) // if we don't have a dot, this is a folder { continue; // skip this folder } if(fileStr.find('/') != std::string::npos) // if we have any dir chars in the string, strip out dirs { fileStr = fileStr.substr(fileStr.find_last_of('/') + 1); } #ifndef __linux__ #pragma warning(push) #pragma warning(disable: 4244) #endif std::vector<bbyte> bytes(fileInfo.size); // just gotta deal with this conversion #ifndef __linux__ #pragma warning(pop) #endif zip_fread(zipped, bytes.data(), fileInfo.size); std::ofstream fout; fout.open(folderName + fileStr, std::ofstream::binary); if(fout.bad()) { std::cout << "[ERROR]: Unable to extract file: " << fileInfo.name << '\n'; return false; } fout.write(bytes.data(), bytes.size()); fout.close(); } else { std::cout << "[ERROR]: Bad file data for file in archive: " << file << '\n'; return false; } zip_fclose(zipped); } zip_close(zipFile); // delete the zip file, it's no longer needed #ifdef __linux__ // TBD #else DeleteFile(file.c_str()); #endif return true; }
// This function is called to load the CA bundle // from http://curl.haxx.se/libcurl/c/cacertinmem.html¯ static CURLcode sslctx_function(CURL * /* curl */, void *sslctx, void * /* parm */) { int error = 0; struct zip *apk = zip_open(mbgl::android::apkPath.c_str(), 0, &error); if (apk == nullptr) { return CURLE_SSL_CACERT_BADFILE; } struct zip_file *apkFile = zip_fopen(apk, "assets/ca-bundle.crt", ZIP_FL_NOCASE); if (apkFile == nullptr) { zip_close(apk); apk = nullptr; return CURLE_SSL_CACERT_BADFILE; } struct zip_stat stat; if (zip_stat(apk, "assets/ca-bundle.crt", ZIP_FL_NOCASE, &stat) != 0) { zip_fclose(apkFile); apkFile = nullptr; zip_close(apk); apk = nullptr; return CURLE_SSL_CACERT_BADFILE; } if (stat.size > std::numeric_limits<int>::max()) { zip_fclose(apkFile); apkFile = nullptr; zip_close(apk); apk = nullptr; return CURLE_SSL_CACERT_BADFILE; } const auto pem = std::make_unique<char[]>(stat.size); if (static_cast<zip_uint64_t>(zip_fread(apkFile, reinterpret_cast<void *>(pem.get()), stat.size)) != stat.size) { zip_fclose(apkFile); apkFile = nullptr; zip_close(apk); apk = nullptr; return CURLE_SSL_CACERT_BADFILE; } // get a pointer to the X509 certificate store (which may be empty!) X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX *)sslctx); if (store == nullptr) { return CURLE_SSL_CACERT_BADFILE; } // get a BIO BIO *bio = BIO_new_mem_buf(pem.get(), static_cast<int>(stat.size)); if (bio == nullptr) { store = nullptr; return CURLE_SSL_CACERT_BADFILE; } // use it to read the PEM formatted certificate from memory into an X509 // structure that SSL can use X509 *cert = nullptr; while (PEM_read_bio_X509(bio, &cert, 0, nullptr) != nullptr) { if (cert == nullptr) { BIO_free(bio); bio = nullptr; store = nullptr; return CURLE_SSL_CACERT_BADFILE; } // add our certificate to this store if (X509_STORE_add_cert(store, cert) == 0) { X509_free(cert); cert = nullptr; BIO_free(bio); bio = nullptr; store = nullptr; return CURLE_SSL_CACERT_BADFILE; } X509_free(cert); cert = nullptr; } // decrease reference counts BIO_free(bio); bio = nullptr; zip_fclose(apkFile); apkFile = nullptr; zip_close(apk); apk = nullptr; // all set to go return CURLE_OK; }
void dlgPackageExporter::slot_export_package(){ //#ifndef Q_OS_WIN // filePath = ui->filePath->text(); //#endif QFile file_xml( filePath ); if( file_xml.open( QIODevice::WriteOnly ) ) { XMLexport writer( mpHost ); //write trigs QList<QTreeWidgetItem *> items = treeWidget->findItems(QString("Triggers"), Qt::MatchExactly, 0); QTreeWidgetItem * top = items.first(); QList<QTreeWidgetItem *> trigList; recurseTree(top,trigList); for (int i=0;i<trigList.size();i++){ QTreeWidgetItem * item = trigList.at(i); if (item->checkState(0) == Qt::Unchecked && triggerMap.contains(item)){ triggerMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && triggerMap.contains(item) && triggerMap[item]->mModuleMasterFolder){ triggerMap[item]->mModuleMasterFolder=false; modTriggerMap.insert(item, triggerMap[item]); } } items = treeWidget->findItems(QString("Timers"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> timerList; recurseTree(top,timerList); for (int i=0;i<timerList.size();i++){ QTreeWidgetItem * item = timerList.at(i); if (item->checkState(0) == Qt::Unchecked && timerMap.contains(item)){ timerMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && timerMap.contains(item) && timerMap[item]->mModuleMasterFolder){ timerMap[item]->mModuleMasterFolder=false; modTimerMap.insert(item, timerMap[item]); } } items = treeWidget->findItems(QString("Aliases"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> aliasList; recurseTree(top,aliasList); for (int i=0;i<aliasList.size();i++){ QTreeWidgetItem * item = aliasList.at(i); if (item->checkState(0) == Qt::Unchecked && aliasMap.contains(item)){ aliasMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && aliasMap.contains(item) && aliasMap[item]->mModuleMasterFolder){ aliasMap[item]->mModuleMasterFolder=false; modAliasMap.insert(item, aliasMap[item]); } } items = treeWidget->findItems(QString("Buttons"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> actionList; recurseTree(top,actionList); for (int i=0;i<actionList.size();i++){ QTreeWidgetItem * item = actionList.at(i); if (item->checkState(0) == Qt::Unchecked && actionMap.contains(item)){ actionMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && actionMap.contains(item) && actionMap[item]->mModuleMasterFolder){ actionMap[item]->mModuleMasterFolder=false; modActionMap.insert(item, actionMap[item]); } } items = treeWidget->findItems(QString("Scripts"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> scriptList; recurseTree(top,scriptList); for (int i=0;i<scriptList.size();i++){ QTreeWidgetItem * item = scriptList.at(i); if (item->checkState(0) == Qt::Unchecked && scriptMap.contains(item)){ scriptMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && scriptMap.contains(item) && scriptMap[item]->mModuleMasterFolder){ scriptMap[item]->mModuleMasterFolder=false; modScriptMap.insert(item, scriptMap[item]); } } items = treeWidget->findItems(QString("Keys"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> keyList; recurseTree(top,keyList); for (int i=0;i<keyList.size();i++){ QTreeWidgetItem * item = keyList.at(i); if (item->checkState(0) == Qt::Unchecked && keyMap.contains(item)){ keyMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && keyMap.contains(item) && keyMap[item]->mModuleMasterFolder){ keyMap[item]->mModuleMasterFolder=false; modKeyMap.insert(item, keyMap[item]); } } writer.exportGenericPackage(&file_xml); file_xml.close(); //now fix all the stuff we weren't exporting //trigger, timer, alias,action,script, keys for (int i=0;i<trigList.size();i++){ QTreeWidgetItem * item = trigList.at(i); if (triggerMap.contains(item)){ triggerMap[item]->exportItem = true; } if (modTriggerMap.contains(item)){ modTriggerMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<timerList.size();i++){ QTreeWidgetItem * item = timerList.at(i); if (timerMap.contains(item)){ timerMap[item]->exportItem = true; } if (modTimerMap.contains(item)){ modTimerMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<actionList.size();i++){ QTreeWidgetItem * item = actionList.at(i); if (actionMap.contains(item)){ actionMap[item]->exportItem = true; } if (modActionMap.contains(item)){ modActionMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<scriptList.size();i++){ QTreeWidgetItem * item = scriptList.at(i); if (scriptMap.contains(item)){ scriptMap[item]->exportItem = true; } if (modScriptMap.contains(item)){ modScriptMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<keyList.size();i++){ QTreeWidgetItem * item = keyList.at(i); if (keyMap.contains(item)){ keyMap[item]->exportItem = true; } if (modKeyMap.contains(item)){ modKeyMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<aliasList.size();i++){ QTreeWidgetItem * item = aliasList.at(i); if (aliasMap.contains(item)){ aliasMap[item]->exportItem = true; } if (modAliasMap.contains(item)){ modAliasMap[item]->mModuleMasterFolder = true; } } //#ifdef Q_OS_WIN int err = 0; char buf[100]; zip* archive = zip_open( zipFile.toStdString().c_str(), ZIP_CREATE|ZIP_TRUNCATE, &err); qDebug()<<"dp saving to"<<zipFile; if ( err != 0 ) { zip_error_to_str(buf, sizeof(buf), err, errno); qDebug()<<"dp zip open error"<<zipFile<<buf; close(); return; } err = zip_dir_add( archive, tempDir.toStdString().c_str(), ZIP_FL_ENC_GUESS ); if ( err != 0 ) { zip_error_to_str(buf, sizeof(buf), err, errno); qDebug()<<"dp zip add dir error"<<buf; close(); return; } QDir dir(tempDir); QStringList contents = dir.entryList(); for(int i=0;i<contents.size();i++) { QString fname = contents[i]; if ( fname == "." || fname == ".." ) continue; QString fullName = tempDir+"/"+contents[i]; struct zip_source *s = zip_source_file( archive, fullName.toStdString().c_str(), 0, 0); if ( s == NULL ) { int sep = 0; zip_error_get( archive, &err, &sep); zip_error_to_str(buf, sizeof(buf), err, errno); qDebug()<<"zip source error"<<fullName<<fname<<buf; } err = zip_file_add( archive, fname.toStdString().c_str(), s, ZIP_FL_OVERWRITE ); if ( err == -1 ) { int sep = 0; zip_error_get( archive, &err, &sep); zip_error_to_str(buf, sizeof(buf), err, errno); qDebug()<<"added file error"<<fullName<<fname<<buf; } } err = zip_close( archive ); if ( err != 0 ){ zip_error_to_str(buf, sizeof(buf), err, errno); qDebug()<<"dp close file error"<<buf; close(); return; } //JlCompress::compressDir(zip, tempDir ); // #else // ui->infoLabel->setText("Exported package to "+filePath); // #endif } else { ui->infoLabel->setText("Failed to export - couldn't open "+filePath+" for writing in. Do you have the necessary permissions to write to that folder?"); } close(); }
bool GameManager::InstallGame(std::string zipfile, bool deleteAfter) { if (installInProgress_) { ERROR_LOG(HLE, "Cannot have two installs in progress at the same time"); return false; } installInProgress_ = true; std::string pspGame = GetSysDirectory(DIRECTORY_GAME); INFO_LOG(HLE, "Installing %s into %s", zipfile.c_str(), pspGame.c_str()); if (!File::Exists(zipfile)) { ERROR_LOG(HLE, "ZIP file %s doesn't exist", zipfile.c_str()); return false; } int error; #ifdef _WIN32 struct zip *z = zip_open(ConvertUTF8ToWString(zipfile).c_str(), 0, &error); #elif defined(__SYMBIAN32__) // If zipfile is non-ascii, this may not function correctly. Other options? struct zip *z = zip_open(std::wstring(zipfile.begin(), zipfile.end()).c_str(), 0, &error); #else struct zip *z = zip_open(zipfile.c_str(), 0, &error); #endif if (!z) { ERROR_LOG(HLE, "Failed to open ZIP file %s, error code=%i", zipfile.c_str(), error); return false; } int numFiles = zip_get_num_files(z); // First, find all the directories, and precreate them before we fill in with files. // Also, verify that this is a PSP zip file with the correct layout. bool isPSP = false; int stripChars = 0; for (int i = 0; i < numFiles; i++) { const char *fn = zip_get_name(z, i, 0); std::string zippedName = fn; if (zippedName.find("EBOOT.PBP") != std::string::npos) { int slashCount = 0; int lastSlashLocation = -1; int slashLocation = -1; for (size_t i = 0; i < zippedName.size(); i++) { if (zippedName[i] == '/') { slashCount++; slashLocation = lastSlashLocation; lastSlashLocation = i; } } if (slashCount >= 1 && (!isPSP || slashLocation < stripChars + 1)) { stripChars = slashLocation + 1; isPSP = true; } else { INFO_LOG(HLE, "Wrong number of slashes (%i) in %s", slashCount, zippedName.c_str()); } } } if (!isPSP) { ERROR_LOG(HLE, "File not a PSP game, no EBOOT.PBP found."); return false; } size_t allBytes = 0, bytesCopied = 0; // Create all the directories in one pass std::set<std::string> createdDirs; for (int i = 0; i < numFiles; i++) { const char *fn = zip_get_name(z, i, 0); std::string zippedName = fn; std::string outFilename = pspGame + zippedName.substr(stripChars); bool isDir = *outFilename.rbegin() == '/'; if (!isDir && outFilename.find("/") != std::string::npos) { outFilename = outFilename.substr(0, outFilename.rfind('/')); } if (createdDirs.find(outFilename) == createdDirs.end()) { File::CreateFullPath(outFilename.c_str()); createdDirs.insert(outFilename); } if (!isDir) { struct zip_stat zstat; if (zip_stat_index(z, i, 0, &zstat) >= 0) { allBytes += zstat.size; } } } // Now, loop through again in a second pass, writing files. for (int i = 0; i < numFiles; i++) { const char *fn = zip_get_name(z, i, 0); // Note that we do NOT write files that are not in a directory, to avoid random // README files etc. if (strstr(fn, "/") != 0) { struct zip_stat zstat; zip_stat_index(z, i, 0, &zstat); size_t size = zstat.size; fn += stripChars; std::string outFilename = pspGame + fn; bool isDir = *outFilename.rbegin() == '/'; if (isDir) continue; if (i < 10) { INFO_LOG(HLE, "Writing %i bytes to %s", (int)size, outFilename.c_str()); } zip_file *zf = zip_fopen_index(z, i, 0); FILE *f = fopen(outFilename.c_str(), "wb"); if (f) { size_t pos = 0; const size_t blockSize = 1024 * 128; u8 *buffer = new u8[blockSize]; while (pos < size) { size_t bs = std::min(blockSize, pos - size); zip_fread(zf, buffer, bs); size_t written = fwrite(buffer, 1, bs, f); if (written != bs) { ERROR_LOG(HLE, "Wrote %i bytes out of %i - Disk full?", (int)written, (int)bs); // TODO: What do we do? } pos += bs; bytesCopied += bs; installProgress_ = (float)bytesCopied / (float)allBytes; // printf("Progress: %f\n", installProgress_); } zip_fclose(zf); fclose(f); delete [] buffer; } else { ERROR_LOG(HLE, "Failed to open file for writing"); } } } INFO_LOG(HLE, "Extracted %i files (%i bytes).", numFiles, (int)bytesCopied); zip_close(z); installProgress_ = 1.0f; installInProgress_ = false; if (deleteAfter) { deleteFile(zipfile.c_str()); } InstallDone(); return true; }
void process_zip(char *pPath) { #ifdef HAVE_LIBZZIP ZZIP_DIR *dir; ZZIP_FILE *fp; ZZIP_DIRENT dirent; char buf[BUF_SIZE]; int nRead; long depth = 0; int ret = 0; dir = zzip_dir_open(pPath, 0); if (!dir) { return; } while (zzip_dir_read(dir, &dirent)) { fp = zzip_file_open(dir, dirent.d_name, 0); if (fp) { // pull the data and scan while ((nRead = zzip_file_read(fp, buf, BUF_SIZE)) > 0) { depth += nRead; if (is_match(buf,nRead)) { ret = 1; if (!LogTotalMatches) { send_match(hit,pPath); break; } } bzero(buf, sizeof(buf)); if ((ScanDepth != 0) && (depth >= (ScanDepth * 1024))) { break; } } zzip_file_close(fp); } } if ((LogTotalMatches && TotalMatches) || ret) { send_match(hit, pPath); } zzip_dir_close(dir); #else #ifdef HAVE_LIBZIP struct zip *za; int err, ret = 0, nRead; char errstr[1024], buf[BUF_SIZE]; long depth; if ((za = zip_open(pPath, 0, &err)) == NULL) { return; } while ((nRead = zip_fread(za, &buf, BUF_SIZE)) > 0) { depth += nRead; if (is_match(buf,nRead)) { ret = 1; if (!LogTotalMatches) { send_match(hit,pPath); zip_close(za); return; } } bzero(buf, sizeof(buf)); if ((ScanDepth != 0) && (depth >= (ScanDepth * 1024))) { break; } } if ((LogTotalMatches && TotalMatches) || ret) { send_match(hit, pPath); } zip_close(za); #endif /* HAVE_LIBZIP */ return; #endif /* HAVE_ZZIP */ }
/** * Load the session from the specified filename. * * @param ctx The context in which to load the session. * @param filename The name of the session file to load. * @param session The session to load the file into. * * @retval SR_OK Success * @retval SR_ERR_MALLOC Memory allocation error * @retval SR_ERR_DATA Malformed session file * @retval SR_ERR This is not a session file */ SR_API int sr_session_load(struct sr_context *ctx, const char *filename, struct sr_session **session) { GKeyFile *kf; GError *error; struct zip *archive; struct zip_stat zs; struct sr_dev_inst *sdi; struct sr_channel *ch; int ret, i, j; uint64_t tmp_u64; int total_channels, total_analog, k; GSList *l; int unitsize; char **sections, **keys, *val; char channelname[SR_MAX_CHANNELNAME_LEN + 1]; gboolean file_has_logic; if ((ret = sr_sessionfile_check(filename)) != SR_OK) return ret; if (!(archive = zip_open(filename, 0, NULL))) return SR_ERR; if (zip_stat(archive, "metadata", 0, &zs) < 0) { zip_discard(archive); return SR_ERR; } kf = sr_sessionfile_read_metadata(archive, &zs); zip_discard(archive); if (!kf) return SR_ERR_DATA; if ((ret = sr_session_new(ctx, session)) != SR_OK) { g_key_file_free(kf); return ret; } total_channels = 0; error = NULL; ret = SR_OK; file_has_logic = FALSE; sections = g_key_file_get_groups(kf, NULL); for (i = 0; sections[i] && ret == SR_OK; i++) { if (!strcmp(sections[i], "global")) /* nothing really interesting in here yet */ continue; if (!strncmp(sections[i], "device ", 7)) { /* device section */ sdi = NULL; keys = g_key_file_get_keys(kf, sections[i], NULL, NULL); /* File contains analog data if there are analog channels. */ total_analog = g_key_file_get_integer(kf, sections[i], "total analog", &error); if (total_analog > 0 && !error) sdi = sr_session_prepare_sdi(filename, session); g_clear_error(&error); /* File contains logic data if a capturefile is set. */ val = g_key_file_get_string(kf, sections[i], "capturefile", &error); if (val && !error) { if (!sdi) sdi = sr_session_prepare_sdi(filename, session); sr_config_set(sdi, NULL, SR_CONF_CAPTUREFILE, g_variant_new_string(val)); g_free(val); file_has_logic = TRUE; } g_clear_error(&error); for (j = 0; keys[j]; j++) { if (!strcmp(keys[j], "samplerate")) { val = g_key_file_get_string(kf, sections[i], keys[j], &error); if (!sdi || !val || sr_parse_sizestring(val, &tmp_u64) != SR_OK) { g_free(val); ret = SR_ERR_DATA; break; } g_free(val); sr_config_set(sdi, NULL, SR_CONF_SAMPLERATE, g_variant_new_uint64(tmp_u64)); } else if (!strcmp(keys[j], "unitsize") && file_has_logic) { unitsize = g_key_file_get_integer(kf, sections[i], keys[j], &error); if (!sdi || unitsize <= 0 || error) { ret = SR_ERR_DATA; break; } sr_config_set(sdi, NULL, SR_CONF_CAPTURE_UNITSIZE, g_variant_new_uint64(unitsize)); } else if (!strcmp(keys[j], "total probes")) { total_channels = g_key_file_get_integer(kf, sections[i], keys[j], &error); if (!sdi || total_channels < 0 || error) { ret = SR_ERR_DATA; break; } sr_config_set(sdi, NULL, SR_CONF_NUM_LOGIC_CHANNELS, g_variant_new_int32(total_channels)); for (k = 0; k < total_channels; k++) { g_snprintf(channelname, sizeof(channelname), "%d", k); sr_channel_new(sdi, k, SR_CHANNEL_LOGIC, FALSE, channelname); } } else if (!strcmp(keys[j], "total analog")) { total_analog = g_key_file_get_integer(kf, sections[i], keys[j], &error); if (!sdi || total_analog < 0 || error) { ret = SR_ERR_DATA; break; } sr_config_set(sdi, NULL, SR_CONF_NUM_ANALOG_CHANNELS, g_variant_new_int32(total_analog)); for (k = total_channels; k < (total_channels + total_analog); k++) { g_snprintf(channelname, sizeof(channelname), "%d", k); sr_channel_new(sdi, k, SR_CHANNEL_ANALOG, FALSE, channelname); } } else if (!strncmp(keys[j], "probe", 5)) { tmp_u64 = g_ascii_strtoull(keys[j] + 5, NULL, 10); if (!sdi || tmp_u64 == 0 || tmp_u64 > G_MAXINT) { ret = SR_ERR_DATA; break; } ch = g_slist_nth_data(sdi->channels, tmp_u64 - 1); if (!ch) { ret = SR_ERR_DATA; break; } val = g_key_file_get_string(kf, sections[i], keys[j], &error); if (!val) { ret = SR_ERR_DATA; break; } /* sr_session_save() */ sr_dev_channel_name_set(ch, val); g_free(val); sr_dev_channel_enable(ch, TRUE); } else if (!strncmp(keys[j], "analog", 6)) { tmp_u64 = g_ascii_strtoull(keys[j]+6, NULL, 10); if (!sdi || tmp_u64 == 0 || tmp_u64 > G_MAXINT) { ret = SR_ERR_DATA; break; } ch = NULL; for (l = sdi->channels; l; l = l->next) { ch = l->data; if ((guint64)ch->index == tmp_u64 - 1) break; else ch = NULL; } if (!ch) { ret = SR_ERR_DATA; break; } val = g_key_file_get_string(kf, sections[i], keys[j], &error); if (!val) { ret = SR_ERR_DATA; break; } /* sr_session_save() */ sr_dev_channel_name_set(ch, val); g_free(val); sr_dev_channel_enable(ch, TRUE); } } g_strfreev(keys); } } g_strfreev(sections); g_key_file_free(kf); if (error) { sr_err("Failed to parse metadata: %s", error->message); g_error_free(error); } return ret; }
bool GetCompressedFiles(std::string ZipName, std::vector<std::string>* pFileNames, std::vector<std::vector<char> >* data, std::string* pError) { #ifdef WIN32 HZIP hz = OpenZip(ZipName.c_str(),0); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} ZIPENTRY ze; if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} int NumFiles = ze.index; //set up returns for data... data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;} int NumDesiredFiles = pFileNames->size(); for (int j=0; j<NumDesiredFiles; j++){ if ((*pFileNames)[j].compare(ze.name)==0){ //if this is one of the file's we're looking for int size = ze.unc_size; (*data)[j].resize(size+1); //or clear... if (UnzipItem(hz, i, &((*data)[j].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[j][size] = '\0'; } } } if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #else //Mac/Linux Zip read code int err; struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} int NumFiles = zip_get_num_entries(hz,0); if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} //set up returns for data... data->resize(NumFiles); for (uint i=0; i<NumFiles; i++){ struct zip_file * zfile = zip_fopen_index(hz, i, 0); int NumDesiredFiles = pFileNames->size(); const char * entryname = zip_get_name(hz, i, 0); struct zip_stat stat; err = zip_stat_index(hz, i, 0, &stat); for (int j=0; j<NumDesiredFiles; j++){ if ((*pFileNames)[j].compare(entryname)==0){ //if this is one of the file's we're looking for int size = stat.size; (*data)[j].resize(size+1); //or clear... if (zip_fread(zfile, &((*data)[j].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[j][size] = '\0'; } } zip_fclose(zfile); } if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #endif }
static VALUE zipruby_archive_s_open_buffer(int argc, VALUE *argv, VALUE self) { VALUE buffer, flags, comp_level; VALUE archive; struct zipruby_archive *p_archive; void *data = NULL; int len = 0, i_flags = 0; int errorp; int i_comp_level = Z_BEST_COMPRESSION; int buffer_is_temporary = 0; rb_scan_args(argc, argv, "03", &buffer, &flags, &comp_level); if (FIXNUM_P(buffer) && NIL_P(comp_level)) { comp_level = flags; flags = buffer; buffer = Qnil; } if (!NIL_P(flags)) { i_flags = NUM2INT(flags); } if (!NIL_P(comp_level)) { i_comp_level = NUM2INT(comp_level); if (i_comp_level != Z_DEFAULT_COMPRESSION && i_comp_level != Z_NO_COMPRESSION && (i_comp_level < Z_BEST_SPEED || Z_BEST_COMPRESSION < i_comp_level)) { rb_raise(rb_eArgError, "Wrong compression level %d", i_comp_level); } } if (i_flags & ZIP_CREATE) { if (!NIL_P(buffer)) { Check_Type(buffer, T_STRING); } else { buffer = rb_str_new("", 0); buffer_is_temporary = 1; } i_flags = (i_flags | ZIP_TRUNCATE); } else if (TYPE(buffer) == T_STRING) { data = RSTRING_PTR(buffer); len = RSTRING_LEN(buffer); } else if (rb_obj_is_instance_of(buffer, rb_cProc)) { data = (void *) buffer; len = -1; } else { rb_raise(rb_eTypeError, "wrong argument type %s (expected String or Proc)", rb_class2name(CLASS_OF(buffer))); } archive = rb_funcall(Archive, rb_intern("new"), 0); Data_Get_Struct(archive, struct zipruby_archive, p_archive); if ((p_archive->tmpfilnam = zipruby_tmpnam(data, len)) == NULL) { rb_raise(Error, "Open archive failed: Failed to create temporary file"); } if ((p_archive->archive = zip_open(p_archive->tmpfilnam, i_flags, &errorp)) == NULL) { char errstr[ERRSTR_BUFSIZE]; zip_error_to_str(errstr, ERRSTR_BUFSIZE, errorp, errno); rb_raise(Error, "Open archive failed: %s", errstr); } // p_archive->archive->comp_level = i_comp_level; p_archive->path = rb_str_new2(p_archive->tmpfilnam); p_archive->flags = i_flags; p_archive->buffer = buffer; p_archive->sources = rb_ary_new(); if (rb_block_given_p()) { VALUE retval; int status; retval = rb_protect(rb_yield, archive, &status); zipruby_archive_close(archive); if (status != 0) { rb_jump_tag(status); } return buffer_is_temporary ? buffer : retval; } else { return archive; } }
bool UncompressAllFiles(std::string ZipName, std::vector<std::string>* pFileNames, std::vector<std::vector<char> >* data, std::string* pError) { #ifdef WIN32 HZIP hz = OpenZip(ZipName.c_str(),0); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} ZIPENTRY ze; if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} int NumFiles = ze.index; //set up returns for the number of files... pFileNames->resize(NumFiles); data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;} int size = ze.unc_size; (*data)[i].resize(size+1); if (UnzipItem(hz, i, &((*data)[i].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[i][size] = '\0'; (*pFileNames)[i] = ze.name; } if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #else //Mac/Linux Zip read code int err; struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} int NumFiles = zip_get_num_entries(hz,0); if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} //set up returns for the number of files... pFileNames->resize(NumFiles); data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ struct zip_stat stat; err = zip_stat_index(hz, i, 0, &stat); int size = stat.size; (*data)[i].resize(size+1); struct zip_file * zfile = zip_fopen_index(hz, i, 0); if (zip_fread(zfile, &((*data)[i].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[i][size] = '\0'; (*pFileNames)[i] = zip_get_name(hz, i, 0); } if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #endif }
int extract_to_cache(const char *archive, const char *cache_path) { struct zip *ziparchive; struct zip_file *zipfile; struct zip_stat zipstat; char buf[4096]; int err; int i, len; int fd; int dirname_len; long long sum; char *full_path; char *dir_name; Stat localfile; utimbuf modified; android_printf("unzip: Preparing to cache. This could take a while..."); if ((ziparchive = zip_open(archive, 0, &err)) == NULL) { zip_error_to_str(buf, sizeof(buf), err, errno); android_printf("unzip error: can't open archive %s/n",archive); return 1; } mkpath(cache_path); for (i = 0; i < zip_get_num_entries(ziparchive, 0); i++) { if (zip_stat_index(ziparchive, i, 0, &zipstat) != 0) { android_printf("unzip error: can't open entry: %i/n",i); continue; } if(strncmp (zipstat.name,"assets/",7) != 0) continue; modified.modtime = modified.actime = zipstat.mtime; full_path = (char*)malloc( sizeof(char*) * (strlen(cache_path) + 1 + strlen(zipstat.name) + 1)); sprintf(full_path, "%s/%s",cache_path,zipstat.name); if (zipstat.name[strlen(zipstat.name) - 1] == '/') { mkpath(full_path); free(full_path); continue; } zipfile = zip_fopen_index(ziparchive, i, 0); if (!zipfile) { android_printf("unzip error: can't open index"); free(full_path); continue; } if (stat(full_path, &localfile) != 0) { dirname_len = strrchr(zipstat.name,'/') - zipstat.name; dir_name = (char*)malloc( sizeof(char*) * (strlen(cache_path) + 1 + dirname_len + 1)); strncpy(dir_name, full_path, strlen(cache_path) + dirname_len + 1); dir_name[strlen(cache_path) + dirname_len + 1] = '\0'; mkpath(dir_name); free(dir_name); } else if (localfile.st_mtime == zipstat.mtime) { free(full_path); continue; } fd = open(full_path, O_RDWR | O_TRUNC | O_CREAT, 0644); if(fd < 0) { android_printf("unzip error: could not open %s",full_path); free(full_path); continue; } sum = 0; while (sum != zipstat.size) { len = zip_fread(zipfile, buf, 4096); if (len < 0) { android_printf("unzip error: no data in %s",full_path); free(full_path); continue; } write(fd, buf, len); sum += len; } close(fd); zip_fclose(zipfile); if (stat(full_path, &localfile) == 0) { // save the zip time. this way we know for certain if we need to refresh. utime(full_path, &modified); } else { android_printf("unzip error: failed to extract %s",full_path); } free(full_path); } if (zip_close(ziparchive) == -1) android_printf("unzip error: can't close zip archive `%s'/n", archive); return 0; }
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected) { static const char errPrefix[] = "divelog.de-upload:"; if (!amount_selected) { report_error(tr("no dives were selected").toUtf8()); return false; } xsltStylesheetPtr xslt = NULL; struct zip *zip; xslt = get_stylesheet("divelogs-export.xslt"); if (!xslt) { qDebug() << errPrefix << "missing stylesheet"; return false; } int error_code; zip = zip_open(QFile::encodeName(tempfile), ZIP_CREATE, &error_code); if (!zip) { char buffer[1024]; zip_error_to_str(buffer, sizeof buffer, error_code, errno); report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer); return false; } /* walk the dive list in chronological order */ for (int i = 0; i < dive_table.nr; i++) { FILE *f; char filename[PATH_MAX]; int streamsize; char *membuf; xmlDoc *transformed; struct zip_source *s; /* * Get the i'th dive in XML format so we can process it. * We need to save to a file before we can reload it back into memory... */ struct dive *dive = get_dive(i); if (!dive) continue; if (selected && !dive->selected) continue; f = tmpfile(); if (!f) { report_error(tr("cannot create temporary file: %s").toUtf8(), qt_error_string().toUtf8().data()); goto error_close_zip; } save_dive(f, dive); fseek(f, 0, SEEK_END); streamsize = ftell(f); rewind(f); membuf = (char *)malloc(streamsize + 1); if (!membuf || (streamsize = fread(membuf, streamsize, 1, f)) == 0) { report_error(tr("internal error: %s").toUtf8(), qt_error_string().toUtf8().data()); fclose(f); free((void *)membuf); goto error_close_zip; } membuf[streamsize] = 0; fclose(f); /* * Parse the memory buffer into XML document and * transform it to divelogs.de format, finally dumping * the XML into a character buffer. */ xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0); if (!doc) { qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!"; report_error(tr("internal error").toUtf8()); free((void *)membuf); goto error_close_zip; } free((void *)membuf); transformed = xsltApplyStylesheet(xslt, doc, NULL); xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize); xmlFreeDoc(doc); xmlFreeDoc(transformed); /* * Save the XML document into a zip file. */ snprintf(filename, PATH_MAX, "%d.xml", i + 1); s = zip_source_buffer(zip, membuf, streamsize, 1); if (s) { int64_t ret = zip_add(zip, filename, s); if (ret == -1) qDebug() << errPrefix << "failed to include dive:" << i; } } zip_close(zip); xsltFreeStylesheet(xslt); return true; error_close_zip: zip_close(zip); QFile::remove(tempfile); xsltFreeStylesheet(xslt); return false; }
static int merge_zip(struct zip *za, const char *tname, const char *sname) { struct zip *zs; struct zip_source *source; int i, idx, err; char errstr[1024]; const char *fname; if ((zs=zip_open(sname, 0, &err)) == NULL) { zip_error_to_str(errstr, sizeof(errstr), err, errno); fprintf(stderr, "%s: cannot open zip archive `%s': %s\n", prg, sname, errstr); return -1; } for (i=0; i<zip_get_num_files(zs); i++) { fname = zip_get_name(zs, i, 0); if ((idx=zip_name_locate(za, fname, name_flags)) != -1) { switch (confirm_replace(za, tname, idx, zs, sname, i)) { case 0: break; case 1: if ((source=zip_source_zip(za, zs, i, 0, 0, 0)) == NULL || zip_replace(za, idx, source) < 0) { zip_source_free(source); fprintf(stderr, "%s: cannot replace `%s' in `%s': %s\n", prg, fname, tname, zip_strerror(za)); return -1; } break; case -1: zip_close(zs); return -1; default: fprintf(stderr, "%s: internal error: " "unexpected return code from confirm (%d)\n", prg, err); zip_close(zs); return -1; } } else { if ((source=zip_source_zip(za, zs, i, 0, 0, 0)) == NULL || zip_add(za, fname, source) < 0) { zip_source_free(source); fprintf(stderr, "%s: cannot add `%s' to `%s': %s\n", prg, fname, tname, zip_strerror(za)); zip_close(zs); return -1; } } } zip_close(zs); return 0; }
void main_window::on_save_mission() { if (m_filename.empty()) { on_save_as_mission(); return; } zip_t *zip = zip_open(m_filename.c_str(), ZIP_DEFAULT_COMPRESSION_LEVEL, 0); if (!zip) { alert("Unable to save mission " + m_filename); return; } std::string str = "<!--Open Horizon mission-->\n"; str += "<mission location=\"" + m_location + "\">\n"; auto &p = m_scene_view->get_player(); str += "\t<player "; str += "x=\"" + std::to_string(p.pos.x) + "\" "; str += "y=\"" + std::to_string(p.pos.y + p.y) + "\" "; str += "z=\"" + std::to_string(p.pos.z) + "\" "; str += "yaw=\"" + std::to_string(p.yaw.get_deg()) + "\" "; str += "editor_y=\"" + std::to_string(p.y) + "\" "; str += ">\n"; str += "\t\t<attribute "; for (auto &a: p.attributes) { if (!a.second.empty()) str += a.first + "=\"" + a.second + "\" "; } str += "/>\n"; str += "\t</player>\n"; for (auto &o: m_scene_view->get_objects()) { str += "\n\t<object "; str += "name=\"" + o.name + "\" "; str += "id=\"" + o.id + "\" "; str += "active=\"" + to_string(o.active) + "\" "; str += "x=\"" + std::to_string(o.pos.x) + "\" "; str += "y=\"" + std::to_string(o.pos.y + o.y) + "\" "; str += "z=\"" + std::to_string(o.pos.z) + "\" "; str += "yaw=\"" + std::to_string(o.yaw.get_deg()) + "\" "; str += "editor_y=\"" + std::to_string(o.y) + "\" "; str += ">\n"; str += "\t\t<attribute "; for (auto &a: o.attributes) { if (!a.second.empty()) str += a.first + "=\"" + a.second + "\" "; } str += "/>\n"; str += "\t</object>\n"; } for (auto &z: m_scene_view->get_zones()) { str += "\n\t<zone "; str += "name=\"" + z.name + "\" "; str += "active=\"" + to_string(z.active) + "\" "; str += "x=\"" + std::to_string(z.pos.x) + "\" "; str += "y=\"" + std::to_string(z.pos.y) + "\" "; str += "z=\"" + std::to_string(z.pos.z) + "\" "; str += "radius=\"" + std::to_string(z.radius) + "\" "; str += ">\n"; str += "\t\t<attribute "; for (auto &a: z.attributes) { if (!a.second.empty()) str += a.first + "=\"" + a.second + "\" "; } str += "/>\n"; str += "\t</zone>\n"; } for (auto &pth: m_scene_view->get_paths()) { str += "\n\t<path "; str += "name=\"" + pth.name + "\" "; str += ">\n"; for (auto &p: pth.points) { str += "\t\t<point "; str += "x=\"" + std::to_string(p.x) + "\" "; str += "y=\"" + std::to_string(p.y + p.w) + "\" "; str += "z=\"" + std::to_string(p.z) + "\" "; str += "editor_y=\"" + std::to_string(p.w) + "\" "; str += "/>\n"; } str += "\t</path>\n"; } str += "</mission>\n"; zip_entry_open(zip, "objects.xml"); zip_entry_write(zip, str.c_str(), str.length()); zip_entry_close(zip); std::string script = to_str(m_script_edit->toPlainText()); zip_entry_open(zip, "script.lua"); zip_entry_write(zip, script.c_str(), script.size()); zip_entry_close(zip); std::string info = "<!--Open Horizon mission info-->\n"; info += "<info "; info += "name=\"" + std::string(to_str(m_mission_title->text())) + "\">\n"; info += "\t<author name=\"" + std::string(to_str(m_mission_author->text())) + "\" "; info += "email=\"" + std::string(to_str(m_mission_email->text())) + "\"/>\n"; info += "\t<description>"; info += to_str(m_mission_description->toPlainText()); info += "</description>\n"; info += "</info>\n"; zip_entry_open(zip, "info.xml"); zip_entry_write(zip, info.c_str(), info.size()); zip_entry_close(zip); zip_close(zip); }
struct zip *subsurface_zip_open_readonly(const char *path, int flags, int *errorp) { return zip_open(path, flags, errorp); }
static int php_zip_ops_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */ { struct zip_stat sb; const char *path = stream->orig_path; size_t path_len = strlen(stream->orig_path); char file_dirname[MAXPATHLEN]; struct zip *za; char *fragment; size_t fragment_len; int err; zend_string *file_basename; fragment = strchr(path, '#'); if (!fragment) { return -1; } if (strncasecmp("zip://", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return -1; } path_len = strlen(path); if (path_len >= MAXPATHLEN) { return -1; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\0'; file_basename = php_basename((char *)path, path_len - fragment_len, NULL, 0); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { zend_string_release(file_basename); return -1; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { memset(ssb, 0, sizeof(php_stream_statbuf)); if (zip_stat(za, fragment, ZIP_FL_NOCASE, &sb) != 0) { zip_close(za); zend_string_release(file_basename); return -1; } zip_close(za); if (path[path_len-1] != '/') { ssb->sb.st_size = sb.size; ssb->sb.st_mode |= S_IFREG; /* regular file */ } else { ssb->sb.st_size = 0; ssb->sb.st_mode |= S_IFDIR; /* regular directory */ } ssb->sb.st_mtime = sb.mtime; ssb->sb.st_atime = sb.mtime; ssb->sb.st_ctime = sb.mtime; ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; ssb->sb.st_blocks = -1; #endif ssb->sb.st_ino = -1; } zend_string_release(file_basename); return 0; }
bool QgsZipUtils::unzip( const QString &zipFilename, const QString &dir, QStringList &files ) { files.clear(); if ( !QFileInfo::exists( zipFilename ) ) { QgsMessageLog::logMessage( QObject::tr( "Error zip file does not exist: '%1'" ).arg( zipFilename ) ); return false; } else if ( zipFilename.isEmpty() ) { QgsMessageLog::logMessage( QObject::tr( "Error zip filename is empty" ) ); return false; } else if ( !QDir( dir ).exists( dir ) ) { QgsMessageLog::logMessage( QObject::tr( "Error output dir does not exist: '%1'" ).arg( dir ) ); return false; } else if ( !QFileInfo( dir ).isDir() ) { QgsMessageLog::logMessage( QObject::tr( "Error output dir is not a directory: '%1'" ).arg( dir ) ); return false; } else if ( !QFileInfo( dir ).isWritable() ) { QgsMessageLog::logMessage( QObject::tr( "Error output dir is not writable: '%1'" ).arg( dir ) ); return false; } int rc = 0; const QByteArray fileNamePtr = zipFilename.toUtf8(); struct zip *z = zip_open( fileNamePtr.constData(), ZIP_CHECKCONS, &rc ); if ( rc == ZIP_ER_OK && z ) { int count = zip_get_num_files( z ); if ( count != -1 ) { struct zip_stat stat; for ( int i = 0; i < count; i++ ) { zip_stat_index( z, i, 0, &stat ); size_t len = stat.size; struct zip_file *file = zip_fopen_index( z, i, 0 ); std::unique_ptr< char[] > buf( new char[len] ); if ( zip_fread( file, buf.get(), len ) != -1 ) { QString fileName( stat.name ); QFileInfo newFile( QDir( dir ), fileName ); // Create path for a new file if it does not exist. if ( !newFile.absoluteDir().exists() ) { if ( !QDir( dir ).mkpath( newFile.absolutePath() ) ) QgsMessageLog::logMessage( QObject::tr( "Failed to create a subdirectory %1/%2" ).arg( dir ).arg( fileName ) ); } QFile outFile( newFile.absoluteFilePath() ); if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { QgsMessageLog::logMessage( QObject::tr( "Could not write to %1" ).arg( newFile.absoluteFilePath() ) ); } else { outFile.write( buf.get(), len ); } zip_fclose( file ); files.append( newFile.absoluteFilePath() ); } else { zip_fclose( file ); QgsMessageLog::logMessage( QObject::tr( "Error reading file: '%1'" ).arg( zip_strerror( z ) ) ); return false; } } } else { zip_close( z ); QgsMessageLog::logMessage( QObject::tr( "Error getting files: '%1'" ).arg( zip_strerror( z ) ) ); return false; } zip_close( z ); } else { QgsMessageLog::logMessage( QObject::tr( "Error opening zip archive: '%1' (Error code: %2)" ).arg( z ? zip_strerror( z ) : zipFilename, rc ) ); return false; } return true; }
static int zip_create(const struct sr_output *o) { struct out_context *outc; struct sr_channel *ch; FILE *meta; struct zip *zipfile; struct zip_source *versrc, *metasrc; GVariant *gvar; GSList *l; int tmpfile, ret; char version[1], metafile[32], *s; outc = o->priv; if (outc->samplerate == 0) { if (sr_config_get(o->sdi->driver, o->sdi, NULL, SR_CONF_SAMPLERATE, &gvar) == SR_OK) { outc->samplerate = g_variant_get_uint64(gvar); g_variant_unref(gvar); } } /* Quietly delete it first, libzip wants replace ops otherwise. */ unlink(outc->filename); if (!(zipfile = zip_open(outc->filename, ZIP_CREATE, &ret))) return SR_ERR; /* "version" */ version[0] = '2'; if (!(versrc = zip_source_buffer(zipfile, version, 1, 0))) return SR_ERR; if (zip_add(zipfile, "version", versrc) == -1) { sr_info("Error saving version into zipfile: %s.", zip_strerror(zipfile)); return SR_ERR; } /* init "metadata" */ strcpy(metafile, "sigrok-meta-XXXXXX"); if ((tmpfile = g_mkstemp(metafile)) == -1) return SR_ERR; close(tmpfile); meta = g_fopen(metafile, "wb"); fprintf(meta, "[global]\n"); fprintf(meta, "sigrok version = %s\n", SR_PACKAGE_VERSION_STRING); fprintf(meta, "[device 1]\ncapturefile = logic-1\n"); fprintf(meta, "total probes = %d\n", g_slist_length(o->sdi->channels)); s = sr_samplerate_string(outc->samplerate); fprintf(meta, "samplerate = %s\n", s); g_free(s); for (l = o->sdi->channels; l; l = l->next) { ch = l->data; if (ch->type != SR_CHANNEL_LOGIC) continue; if (!ch->enabled) continue; fprintf(meta, "probe%d = %s\n", ch->index + 1, ch->name); } fclose(meta); if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) { unlink(metafile); return SR_ERR; } if (zip_add(zipfile, "metadata", metasrc) == -1) { unlink(metafile); return SR_ERR; } if ((ret = zip_close(zipfile)) == -1) { sr_info("Error saving zipfile: %s.", zip_strerror(zipfile)); unlink(metafile); return SR_ERR; } unlink(metafile); return SR_OK; }