Exemplo n.º 1
0
static VALUE zipruby_archive_add_file(int argc, VALUE *argv, VALUE self) {
  VALUE name, fname;
  struct zipruby_archive *p_archive;
  struct zip_source *zsource;

  rb_scan_args(argc, argv, "11", &name, &fname);

  if (NIL_P(fname)) {
    fname = name;
    name = Qnil;
  }

  Check_Type(fname, T_STRING);

  if (NIL_P(name)) {
    name = rb_funcall(rb_cFile, rb_intern("basename"), 1, fname);
  }

  Check_Type(name, T_STRING);
  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);

  if ((zsource = zip_source_file(p_archive->archive, RSTRING_PTR(fname), 0, -1)) == NULL) {
    rb_raise(Error, "Add file failed - %s: %s", RSTRING_PTR(name), zip_strerror(p_archive->archive));
  }

  if (zip_add(p_archive->archive, RSTRING_PTR(name), zsource) == -1) {
    zip_source_free(zsource);
    zip_unchange_all(p_archive->archive);
    zip_unchange_archive(p_archive->archive);
    rb_raise(Error, "Add file failed - %s: %s", RSTRING_PTR(name), zip_strerror(p_archive->archive));
  }

  return Qnil;
}
Exemplo n.º 2
0
static int
add_file(int argc, char *argv[]) {
    zip_source_t *zs;
    zip_uint64_t start = strtoull(argv[2], NULL, 10);
    zip_int64_t len = strtoll(argv[3], NULL, 10);

    if (strcmp(argv[1], "/dev/stdin") == 0) {
	if ((zs=zip_source_filep(za, stdin, start, len)) == NULL) {
	    fprintf(stderr, "can't create zip_source from stdin: %s\n", zip_strerror(za));
	    return -1;
	}
    } else {
	if ((zs=zip_source_file(za, argv[1], start, len)) == NULL) {
	    fprintf(stderr, "can't create zip_source from file: %s\n", zip_strerror(za));
	    return -1;
	}
    }

    if (zip_add(za, argv[0], zs) == -1) {
	zip_source_free(zs);
	fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za));
	return -1;
    }
    return 0;
}
bool add_to_zip(const char *archive, const char *file, const char *name)
{
  struct zip *za;
  struct zip_source *zs;
  int err;

  if ((za=zip_open(archive, ZIP_CREATE, &err)) == NULL) {
    return false;
  }

  if ((zs=zip_source_file(za, file, 0, -1)) == NULL) {
    return false;
  }

  if (zip_add(za, name, zs) == -1) {
    zip_source_free(zs);
    return false;
  }

  if (zip_close(za) == -1) {
    return false;
  }

  return true;
}
Exemplo n.º 4
0
bool QgsZipUtils::zip( const QString &zipFilename, const QStringList &files )
{
  if ( zipFilename.isEmpty() )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error zip filename is empty" ) );
    return false;
  }

  int rc = 0;
  const QByteArray fileNamePtr = zipFilename.toUtf8();
  struct zip *z = zip_open( fileNamePtr.constData(), ZIP_CREATE, &rc );

  if ( rc == ZIP_ER_OK && z )
  {
    for ( const auto &file : files )
    {
      QFileInfo fileInfo( file );
      if ( !fileInfo.exists() )
      {
        QgsMessageLog::logMessage( QObject::tr( "Error input file does not exist: '%1'" ).arg( file ) );
        zip_close( z );
        return false;
      }

      const QByteArray fileNamePtr = file.toUtf8();
      zip_source *src = zip_source_file( z, fileNamePtr.constData(), 0, 0 );
      if ( src )
      {
        const QByteArray fileInfoPtr = fileInfo.fileName().toUtf8();
#if LIBZIP_VERSION_MAJOR < 1
        int rc = ( int ) zip_add( z, fileInfoPtr.constData(), src );
#else
        int rc = ( int ) zip_file_add( z, fileInfoPtr.constData(), src, 0 );
#endif
        if ( rc == -1 )
        {
          QgsMessageLog::logMessage( QObject::tr( "Error adding file '%1': %2" ).arg( file, zip_strerror( z ) ) );
          zip_close( z );
          return false;
        }
      }
      else
      {
        QgsMessageLog::logMessage( QObject::tr( "Error creating data source '%1': %2" ).arg( file, zip_strerror( z ) ) );
        zip_close( z );
        return false;
      }
    }

    zip_close( z );
  }
  else
  {
    QgsMessageLog::logMessage( QObject::tr( "Error creating zip archive '%1': %2" ).arg( zipFilename, zip_strerror( z ) ) );
    return false;
  }

  return true;
}
Exemplo n.º 5
0
bool CompressFiles(std::string ZipName, std::vector<std::string>* pFilePaths, std::string* pError) //pointer to a vector of filepath strings to zip into location of ZipName (also a filepath)
{
#ifdef WIN32

	HZIP hz = CreateZip(ZipName.c_str(),0);
	if (!hz){if (pError) *pError += "Could not create ZIP archive. Aborting\n"; return false;}

	int NumFiles = pFilePaths->size();
	for (int i=0; i<NumFiles; i++){
		std::string ThisFilePath = (*pFilePaths)[i];

		//extract file name (without path)
		int StartName = ThisFilePath.find_last_of('/')+1;
		int EndName = ThisFilePath.size();
		std::string Name = ThisFilePath.substr(StartName, EndName-StartName);

		//remove .tmp from end if it exists...
		std::string Last4 = Name.substr(Name.size()-4, 4);
		if (Last4.compare(".tmp")==0) Name = Name.substr(0, Name.size()-4);

		if(ZipAdd(hz, Name.c_str(), ThisFilePath.c_str()) != ZR_OK){if (pError) *pError += ("Could not add file to ZIP archive. Aborting.\n"); return false;}
	}

	if(CloseZip(hz) != ZR_OK){if (pError) *pError += ("Could not close ZIP archive. Aborting.\n"); return false;}

	return true;
#else
	//Mac/Linux Zip write code
	remove(ZipName.c_str());
	int err;
	struct zip * hz = zip_open(ZipName.c_str(), ZIP_CREATE, &err);
	if (!hz){if (pError) *pError += "Could not create ZIP archive. Aborting\n"; return false;}

	int NumFiles = pFilePaths->size();
	for (int i=0; i<NumFiles; i++){
		std::string ThisFilePath = (*pFilePaths)[i];

		//extract file name (without path)
		int StartName = ThisFilePath.find_last_of('/')+1;
		int EndName = ThisFilePath.size();
		std::string Name = ThisFilePath.substr(StartName, EndName-StartName);

		//remove .tmp from end if it exists...
		std::string Last4 = Name.substr(Name.size()-4, 4);
		if (Last4.compare(".tmp")==0) Name = Name.substr(0, Name.size()-4);

		struct zip_source * source =
		  zip_source_file(hz, ThisFilePath.c_str(), 0, 0);

		if(source == NULL || zip_add(hz, Name.c_str(), source) == -1){if (pError) *pError += ("Could not add file to ZIP archive. Aborting.\n"); return false;}
	}
	if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;}
	return true;
#endif
}
Exemplo n.º 6
0
/* zipfile.addFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Add_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();

    zip_int64_t len;
    if (args[3]->IsUndefined())
      len = -1;
    else
      len = args[3]->Int32Value();

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while adding file " << name << " to zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }
 
    int ret = zip_add(zf->archive, archive_file.c_str(), source); 
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while adding file " << name << " to zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    zf->GetNames();

    return Undefined();
}
Exemplo n.º 7
0
static struct zip_source* S_create_source_file(lua_State* L, struct zip* ar) {
    const char*        fname = luaL_checkstring(L, 4);
    int                start = lua_gettop(L) < 5 ? 0  : luaL_checkint(L, 5);
    int                len   = lua_gettop(L) < 6 ? -1 : luaL_checkint(L, 6);
    struct zip_source* src   = zip_source_file(ar, fname, start, len);

    if ( NULL != src ) return src;

    lua_pushstring(L, zip_strerror(ar));
    lua_error(L);
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
    const char *archive;
    const char *file;
    const char *name;
    struct zip *za;
    struct zip_source *zs;
    char buf[100];
    int err;

    prg = argv[0];

    if (argc != 3) {
	fprintf(stderr, "usage: %s archive file\n", prg);
	return 1;
    }

    archive = argv[1];
    file = argv[2];
    
    if ((za=zip_open(archive, ZIP_CREATE, &err)) == NULL) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "%s: can't open zip archive %s: %s\n", prg,
		archive, buf);
	return 1;
    }

    if ((zs=zip_source_file(za, file, 0, -1)) == NULL) {
	fprintf(stderr, "%s: error creating file source for `%s': %s\n", prg,
		file, zip_strerror(za));
	return 1;
    }

    if ((name=strrchr(file, '/')) == NULL)
	name = file;

    if (zip_add(za, name, zs) == -1) {
	zip_source_free(zs);
	fprintf(stderr, "%s: can't add file `%s': %s\n", prg,
		file, zip_strerror(za));
	return 1;
    }

    if (zip_close(za) == -1) {
	fprintf(stderr, "%s: can't close zip archive `%s'\n", prg,
		archive);
	return 1;
    }

    return 0;
}
Exemplo n.º 9
0
int main()
{
	int err = 0;
	int ret = 0;
	struct zip *z = NULL;
	struct zip_source *s = NULL;

	if ((z = zip_open("./first.zip", ZIP_CREATE | ZIP_EXCL, &err)) == NULL) {
		fprintf(stderr, "ERROR: zip_open(): [%s]\n", zip_strerror(z));
	}

	s = zip_source_file(z, "zip.c", 0, -1);
	if(s != NULL) {
		if ((ret = zip_add(z, "zip.c", s)) < 0) {
			fprintf(stderr, "ERROR: zip_add(): [%s]\n", zip_strerror(z));
			zip_source_free(s);
		}
	} else {
		fprintf(stderr, "ERROR: zip_source_file(): [%s]\n", zip_strerror(z));
		zip_source_free(s);
	}


	s = zip_source_file(z, "unzip.c", 0, -1);
	if(s != NULL) {
		zip_add(z, "unzip.c", s);
	} else {
		fprintf(stderr, "ERROR: zip_source_file(): [%s]\n", zip_strerror(z));
		zip_source_free(s);
	}
	char strerr[1024];
	if ((err = zip_close(z)) < 0) {
		fprintf(stderr, "ERROR: zip_close(): [%s]\n", zip_strerror(z));
	}

	return 0;
}
Exemplo n.º 10
0
void Zipper::_AddFile(uv_work_t *req)
{
    closure_t *closure = static_cast<closure_t *>(req->data);

    struct zip_source *source = zip_source_file(closure->za, closure->path.c_str(), 0, 0);
    if (zip_add(closure->za, closure->name.c_str(), source) < 0) {
        std::stringstream s;
        s << "Cannot prepare file for add to zip: '" << closure->path << "'\n";
        closure->error = true;
        closure->error_name = s.str();
        zip_source_free(source);
    }

    if (zip_close(closure->za) < 0) {
        std::stringstream s;
        s << "Cannot add file to zip: '" << closure->path << "' (" << zip_strerror(closure->za) << ")\n";
        closure->error = true;
        closure->error_name = s.str();
    }
}
Exemplo n.º 11
0
static YogVal
compress(YogEnv* env, YogVal self, YogVal pkg, YogVal args, YogVal kw, YogVal block)
{
    SAVE_ARGS5(env, self, pkg, args, kw, block);
    YogVal path = YUNDEF;
    YogVal files = YUNDEF;
    PUSH_LOCALS2(env, path, files);
    YogCArg params[] = { { "path", &path }, { "*", &files }, { NULL, NULL } };
    YogGetArgs_parse_args(env, "compress", params, args, kw);
    if (!IS_PTR(path) || (BASIC_OBJ_TYPE(path) != TYPE_STRING)) {
        YogError_raise_TypeError(env, "path must be String");
    }

    struct zip* archive = open_zip(env, pkg, path, ZIP_CREATE);
    int n = zip_get_num_files(archive);
    int i;
    for (i = 0; i < n; i++) {
        if (zip_delete(archive, i) != 0) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
    }
    uint_t size = YogArray_size(env, files);
    uint_t j;
    for (j = 0; j < size; j++) {
        YogHandle* name = VAL2HDL(env, YogArray_at(env, files, j));
        YogMisc_check_String(env, name, "Filename");
        YogVal bin = YogString_to_bin_in_default_encoding(env, name);
        const char* fname = BINARY_CSTR(bin);
        struct zip_source* source = zip_source_file(archive, fname, 0, 0);
        if (source == NULL) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
        if (zip_add(archive, fname, source) < 0) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
    }
    close_zip(env, pkg, archive);

    RETURN(env, YNIL);
}
Exemplo n.º 12
0
static VALUE zipruby_archive_replace_file(int argc, VALUE* argv, VALUE self) {
  struct zipruby_archive *p_archive;
  struct zip_source *zsource;
  VALUE index, fname, flags;
  int i_index, i_flags = 0;

  rb_scan_args(argc, argv, "21", &index, &fname, &flags);

  if (TYPE(index) != T_STRING && !FIXNUM_P(index)) {
    rb_raise(rb_eTypeError, "wrong argument type %s (expected Fixnum or String)", rb_class2name(CLASS_OF(index)));
  }

  if (!NIL_P(flags)) {
    i_flags = NUM2INT(flags);
  }

  Check_Type(fname, T_STRING);
  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);

  if (FIXNUM_P(index)) {
    i_index = NUM2INT(index);
  } else if ((i_index = zip_name_locate(p_archive->archive, RSTRING_PTR(index), i_flags)) == -1) {
    rb_raise(Error, "Replace file failed - %s: Archive does not contain a file", RSTRING_PTR(index));
  }

  if ((zsource = zip_source_file(p_archive->archive, RSTRING_PTR(fname), 0, -1)) == NULL) {
    rb_raise(Error, "Replace file failed at %d: %s", i_index, zip_strerror(p_archive->archive));
  }

  if (zip_replace(p_archive->archive, i_index, zsource) == -1) {
    zip_source_free(zsource);
    zip_unchange_all(p_archive->archive);
    zip_unchange_archive(p_archive->archive);
    rb_raise(Error, "Replace file failed at %d: %s", i_index, zip_strerror(p_archive->archive));
  }

  return Qnil;
}
Exemplo n.º 13
0
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;
}
Exemplo n.º 14
0
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, 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", PACKAGE_VERSION);
	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;
}
Exemplo n.º 15
0
static int zip_append(const struct sr_output *o, unsigned char *buf,
		int unitsize, int length)
{
	struct out_context *outc;
	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];

	outc = o->priv;
	if (!(archive = zip_open(outc->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, length, 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;
}
Exemplo n.º 16
0
/* zipfile.replaceFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Replace_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();
    
    zip_int64_t len; 
    if (args[3]->IsUndefined()) 
      len = -1; 
    else 
      len = args[3]->Int32Value();

    int idx = -1;
    
    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), archive_file);
    if (it!=zf->names.end()) {
        idx = distance(zf->names.begin(), it);
    }

    if (idx == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << archive_file << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    int ret = zip_replace(zf->archive, idx, source);        
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
Exemplo n.º 17
0
bool zipobject::addFile(const QString& filePath,const QString& inZipPath){
    TEST_ZIP;
    zip_source* source = zip_source_file(m_zip,getCharPtr(filePath),0,0);
    zip_add(m_zip,getCharPtr(inZipPath),source);
    return true;
}
Exemplo n.º 18
0
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();
}
Exemplo n.º 19
0
/**
 * 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;
}
Exemplo n.º 20
0
/**
 * 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;
}
Exemplo n.º 21
0
int session_save(char *filename)
{
	GSList *l, *d;
	struct device *device;
	struct datastore *ds;
	struct zip *zipfile;
	struct zip_source *src;
	int bufcnt, devcnt, tmpfile, ret, error;
	char version[1], rawname[16], metafile[32], *buf;

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);

	if (!(zipfile = zip_open(filename, ZIP_CREATE, &error)))
		return SIGROK_ERR;

	/* Version */
	version[0] = '1';
	if (!(src = zip_source_buffer(zipfile, version, 1, 0)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "version", src) == -1) {
		g_message("error saving version into zipfile: %s",
			  zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	/* Metadata */
	strcpy(metafile, "sigrok-meta-XXXXXX");
	if ((tmpfile = g_mkstemp(metafile)) == -1)
		return SIGROK_ERR;
	close(tmpfile);
	make_metadata(metafile);
	if (!(src = zip_source_file(zipfile, metafile, 0, -1)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "metadata", src) == -1)
		return SIGROK_ERR;
	unlink(metafile);

	/* Raw */
	devcnt = 1;
	for (l = session->devices; l; l = l->next) {
		device = l->data;
		ds = device->datastore;
		if (ds) {
			buf = malloc(ds->num_units * ds->ds_unitsize +
				   DATASTORE_CHUNKSIZE);
			bufcnt = 0;
			for (d = ds->chunklist; d; d = d->next) {
				memcpy(buf + bufcnt, d->data,
				       DATASTORE_CHUNKSIZE);
				bufcnt += DATASTORE_CHUNKSIZE;
			}
			if (!(src = zip_source_buffer(zipfile, buf,
				       ds->num_units * ds->ds_unitsize, TRUE)))
				return SIGROK_ERR;
			snprintf(rawname, 15, "raw-%d", devcnt);
			if (zip_add(zipfile, rawname, src) == -1)
				return SIGROK_ERR;
		}
		devcnt++;
	}

	if ((ret = zip_close(zipfile)) == -1) {
		g_message("error saving zipfile: %s", zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	return SIGROK_OK;
}
Exemplo n.º 22
0
int sr_session_save(const char *filename)
{
	GSList *l, *p, *d;
	FILE *meta;
	struct sr_device *device;
	struct sr_probe *probe;
	struct sr_datastore *ds;
	struct zip *zipfile;
	struct zip_source *versrc, *metasrc, *logicsrc;
	int bufcnt, devcnt, tmpfile, ret, error, probecnt;
	uint64_t samplerate;
	char version[1], rawname[16], metafile[32], *buf, *s;

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);
	if (!(zipfile = zip_open(filename, ZIP_CREATE, &error)))
		return SR_ERR;

	/* "version" */
	version[0] = '1';
	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);
	/* TODO: save protocol decoders used */

	/* all datastores in all devices */
	devcnt = 1;
	for (l = session->devices; l; l = l->next) {
		device = l->data;
		/* metadata */
		fprintf(meta, "[device %d]\n", devcnt);
		if (device->plugin)
			fprintf(meta, "driver = %s\n", device->plugin->name);

		ds = device->datastore;
		if (ds) {
			/* metadata */
			fprintf(meta, "capturefile = logic-%d\n", devcnt);
			fprintf(meta, "unitsize = %d\n", ds->ds_unitsize);
			fprintf(meta, "total probes = %d\n", g_slist_length(device->probes));
			if (sr_device_has_hwcap(device, SR_HWCAP_SAMPLERATE)) {
				samplerate = *((uint64_t *) device->plugin->get_device_info(
						device->plugin_index, SR_DI_CUR_SAMPLERATE));
				s = sr_samplerate_string(samplerate);
				fprintf(meta, "samplerate = %s\n", s);
				free(s);
			}
			probecnt = 1;
			for (p = device->probes; p; p = p->next) {
				probe = p->data;
				if (probe->enabled) {
					if (probe->name)
						fprintf(meta, "probe%d = %s\n", probecnt, probe->name);
					if (probe->trigger)
						fprintf(meta, " trigger%d = %s\n", probecnt, probe->trigger);
					probecnt++;
				}
			}

			/* dump datastore into logic-n */
			buf = malloc(ds->num_units * ds->ds_unitsize +
				   DATASTORE_CHUNKSIZE);
			bufcnt = 0;
			for (d = ds->chunklist; d; d = d->next) {
				memcpy(buf + bufcnt, d->data,
				       DATASTORE_CHUNKSIZE);
				bufcnt += DATASTORE_CHUNKSIZE;
			}
			if (!(logicsrc = zip_source_buffer(zipfile, buf,
				       ds->num_units * ds->ds_unitsize, TRUE)))
				return SR_ERR;
			snprintf(rawname, 15, "logic-%d", devcnt);
			if (zip_add(zipfile, rawname, logicsrc) == -1)
				return SR_ERR;
		}
		devcnt++;
	}
	fclose(meta);

	if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1)))
		return SR_ERR;
	if (zip_add(zipfile, "metadata", 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;
}