Esempio n. 1
0
int main(int argc, char *argv[])
{
	if (argc < 2) {
		printf("usage: %s <size> <pos> > tmpfile.1 \n", argv[0]);
		return 0;
	}

	int size = atoi(argv[1]);
	int pos = atoi(argv[2]);

	unsigned char *p = (unsigned char *)malloc(size);
	unsigned char *t = (unsigned char *)malloc(size);

	memset(p, 0, size);

	//p[pos] |= (1 << 5);

	int n;

	n = gzip((char *)t, size, (char *)p, size);

	write(STDOUT_FILENO, t, n);

	return 0;
}
Esempio n. 2
0
static int do_zip(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	unsigned long src, dst;
	unsigned long src_len, dst_len = ~0UL;

	switch (argc) {
		case 5:
			dst_len = simple_strtoul(argv[4], NULL, 16);
			/* fall through */
		case 4:
			src = simple_strtoul(argv[1], NULL, 16);
			src_len = simple_strtoul(argv[2], NULL, 16);
			dst = simple_strtoul(argv[3], NULL, 16);
			break;
		default:
			return cmd_usage(cmdtp);
	}

	if (gzip((void *) dst, &dst_len, (void *) src, src_len) != 0)
		return 1;

	printf("Compressed size: %ld = 0x%lX\n", dst_len, dst_len);
	env_set_hex("filesize", dst_len);

	return 0;
}
Esempio n. 3
0
File: test.cpp Progetto: acat/emule
void GzipFile(const char *in, const char *out, int deflate_level)
{
//	FileSource(in, true, new Gzip(new FileSink(out), deflate_level));

	// use a filter graph to compare decompressed data with original
	//
	// Source ----> Gzip ------> Sink
	//    \           |
	//	    \       Gunzip
	//		  \       |
	//		    \     v
	//		      > ComparisonFilter 
			   
	EqualityComparisonFilter comparison;

	Gunzip gunzip(new ChannelSwitch(comparison, "0"));
	gunzip.SetAutoSignalPropagation(0);

	FileSink sink(out);

	ChannelSwitch *cs;
	Gzip gzip(cs = new ChannelSwitch(sink), deflate_level);
	cs->AddDefaultRoute(gunzip);

	cs = new ChannelSwitch(gzip);
	cs->AddDefaultRoute(comparison, "1");
	FileSource source(in, true, cs);

	comparison.ChannelMessageSeriesEnd("0");
	comparison.ChannelMessageSeriesEnd("1");
}
Esempio n. 4
0
void ATPAssetMigrator::saveEntityServerFile() {
    // show a dialog to ask the user where they want to save the file
    QString saveName = QFileDialog::getSaveFileName(_dialogParent, "Save Migrated Entities File");
    
    QFile saveFile { saveName };
    
    if (saveFile.open(QIODevice::WriteOnly)) {
        QJsonObject rootObject;
        rootObject[ENTITIES_OBJECT_KEY] = _entitiesArray;
        
        QJsonDocument newDocument { rootObject };
        QByteArray jsonDataForFile;
        
        if (gzip(newDocument.toJson(), jsonDataForFile, -1)) {
            
            saveFile.write(jsonDataForFile);
            saveFile.close();
            
            QMessageBox::information(_dialogParent, "Success",
                                     QString("Your new entities file has been saved at %1").arg(saveName));
        } else {
            QMessageBox::warning(_dialogParent, "Error", "Could not gzip JSON data for new entities file.");
        }
    
    } else {
        QMessageBox::warning(_dialogParent, "Error",
                             QString("Could not open file at %1 to write new entities file to.").arg(saveName));
    }
}
Esempio n. 5
0
bool GzipDecompress(const butil::IOBuf& data, google::protobuf::Message* msg) {
    butil::IOBufAsZeroCopyInputStream wrapper(data);
    google::protobuf::io::GzipInputStream gzip(
            &wrapper, google::protobuf::io::GzipInputStream::GZIP);
    if (!ParsePbFromZeroCopyStream(msg, &gzip)) {
        LogError(gzip);
        return false;
    }
    return true;
}
Esempio n. 6
0
uLong oz_util_main (int argc, char *argv[])

{
  int fc;
  OZ_IO_fs_create fs_create;
  OZ_IO_fs_open fs_open;
  uLong sts;

  if (argc > 0) pn = argv[0];
  if (argc != 3) {
    oz_sys_io_fs_printf (oz_util_h_error, "usage: %s <input> <output>\n", pn);
    return (OZ_MISSINGPARAM);
  }

  fc = GZIP_FUNC_DUMMY;
  if (strcasecmp (pn, "gzip") == 0) fc = GZIP_FUNC_COMPRESS;
  if (strcasecmp (pn, "gunzip") == 0) fc = GZIP_FUNC_EXPAND;
  if (fc == GZIP_FUNC_DUMMY) {
    oz_sys_io_fs_printf (oz_util_h_error, "%s: program name must be gzip or gunzip\n", pn);
    return (OZ_BADPARAM);
  }

  input_file = argv[1];
  memset (&fs_open, 0, sizeof fs_open);
  fs_open.name     = input_file;
  fs_open.lockmode = OZ_LOCKMODE_PR;
  sts = oz_sys_io_fs_open (sizeof fs_open, &fs_open, 0, &h_in);
  if (sts != OZ_SUCCESS) {
    oz_sys_io_fs_printf (oz_util_h_error, "%s: error %u opening input file %s\n", pn, sts, input_file);
    return (sts);
  }

  output_file = argv[2];
  memset (&fs_create, 0, sizeof fs_create);
  fs_create.name     = output_file;
  fs_create.lockmode = OZ_LOCKMODE_PW;
  sts = oz_sys_io_fs_create (sizeof fs_create, &fs_create, 0, &h_out);
  if (sts != OZ_SUCCESS) {
    oz_sys_io_fs_printf (oz_util_h_error, "%s: error %u creating output file %s\n", pn, sts, output_file);
    return (sts);
  }

  exstat = OZ_SUCCESS;
  gzip (readroutine, writeroutine, errorroutine, mallocroutine, freeroutine, NULL, fc, 6);

  if (exstat == OZ_SUCCESS) {
    sts = oz_sys_io (OZ_PROCMODE_KNL, h_out, 0, OZ_IO_FS_CLOSE, 0, NULL);
    if (sts != OZ_SUCCESS) {
      oz_sys_io_fs_printf (oz_util_h_error, "%s: error %u closing output file %s\n", pn, sts, output_file);
      exstat = sts;
    }
  }

  return (exstat);
}
Esempio n. 7
0
bool GzipCompress(const google::protobuf::Message& msg, butil::IOBuf* buf) {
    butil::IOBufAsZeroCopyOutputStream wrapper(buf);
    google::protobuf::io::GzipOutputStream::Options gzip_opt;
    gzip_opt.format = google::protobuf::io::GzipOutputStream::GZIP;
    google::protobuf::io::GzipOutputStream gzip(&wrapper, gzip_opt);
    if (!msg.SerializeToZeroCopyStream(&gzip)) {
        LogError(gzip);
        return false;
    }
    return gzip.Close();
}
void GzipString( const RString &sIn, RString &sOut )
{
	/* Gzip it. */
	RageFileObjMem mem;
	RageFileObjGzip gzip( &mem );
	gzip.Start();
	gzip.Write( sIn );
	gzip.Finish();

	sOut = mem.GetString();
}
Esempio n. 9
0
// gzip data
BYTE *cpp_gzip(BYTE *pData, int nLen, int& nCompressedLen) {

	string zipped;
	Gzip gzip(new StringSink(zipped),5);    // 1 is fast, 9 is slow
	gzip.Put(pData, nLen);
	gzip.MessageEnd();

	nCompressedLen = (int) zipped.length();
	PBYTE pCompressed = (PBYTE) malloc(nCompressedLen+1);
	memcpy(pCompressed,zipped.data(),nCompressedLen);

	return pCompressed;
}
static int compress_using_gzip(void *in, unsigned long in_size,
			       void *out, unsigned long out_max,
			       unsigned long *out_size)
{
	int ret;
	unsigned long inout_size = out_max;

	ret = gzip(out, &inout_size, in, in_size);
	if (out_size)
		*out_size = inout_size;

	return ret;
}
Esempio n. 11
0
//gzip
int test_GzipByMem()
{
	char plainText[]="Plain text here";
	CA2GZIP gzip(plainText,strlen(plainText));
	// do compressing here;
	LPGZIP pgzip=gzip.pgzip; // pgzip is zipped data pointer,
	// you can use it directly
	int len=gzip.Length; // Length is length of zipped
	// data;

	CGZIP2A plain(pgzip,len); // do uncompressing here

	char *pplain=plain.psz; // psz is plain data pointer
	int aLen=plain.Length; // Length is length of unzipped
	// data.
	return 0;
}
Esempio n. 12
0
void ThemeManager::exportTheme()
{
	QListWidgetItem* item = m_themes->currentItem();
	if (!item) {
		return;
	}

	// Find export file name
	QSettings settings;
	QString path = settings.value("ThemeManager/Location").toString();
	if (path.isEmpty() || !QFile::exists(path)) {
		path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
	}
	path = path + "/" + item->text() + ".fwtz";
	QString filename = QFileDialog::getSaveFileName(this, tr("Export Theme"), path, tr("Themes (%1)").arg("*.fwtz"), 0, QFileDialog::DontResolveSymlinks);
	if (filename.isEmpty()) {
		return;
	}
	if (!filename.endsWith(".fwtz")) {
		filename += ".fwtz";
	}
	settings.setValue("ThemeManager/Location", QFileInfo(filename).absolutePath());

	// Copy theme
	QFile::remove(filename);
	QFile::copy(Theme::filePath(item->data(Qt::UserRole).toString()), filename);

	// Store image in export file
	{
		QSettings theme_ini(filename, QSettings::IniFormat);
		theme_ini.remove("Background/Image");

		QString image = theme_ini.value("Background/ImageFile").toString();
		if (!image.isEmpty()) {
			QFile file(Theme::path() + "/Images/" + image);
			if (file.open(QFile::ReadOnly)) {
				theme_ini.setValue("Data/Image", file.readAll().toBase64());
				file.close();
			}
		}
	}

	// Compress theme
	gzip(filename);
}
Esempio n. 13
0
void Window::shareGame() {
	QString filename = QFileDialog::getSaveFileName(window(),
			tr("Export Game"),
			QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
			tr("Tanglet Games (*.tanglet)"));
	if (!filename.isEmpty()) {
		if (!filename.endsWith(".tanglet")) {
			filename += ".tanglet";
		}

		// Share game
		{
			QSettings settings;
			QSettings game(filename, QSettings::IniFormat);
			game.setValue("Game/Version", 2);
			game.setValue("Game/Size", settings.value("Current/Size"));
			game.setValue("Game/Density", settings.value("Current/Density"));
			game.setValue("Game/Minimum", settings.value("Current/Minimum"));
			game.setValue("Game/TimerMode", settings.value("Current/TimerMode"));
			game.setValue("Game/Letters", settings.value("Current/Letters"));
			game.setValue("Game/Language", settings.value("Current/Language"));
			game.setValue("Game/Dictionary", settings.value("Current/Dictionary"));
			game.setValue("Game/Dice", settings.value("Current/Dice"));
			game.setValue("Game/Words", settings.value("Current/Words"));

			if (game.value("Game/Language").toInt() == 0) {
				QFile file(game.value("Game/Dice").toString());
				if (file.open(QFile::ReadOnly)) {
					QByteArray data = file.readAll();
					file.close();
					game.setValue("Game/Dice", data.toBase64());
				}

				file.setFileName(game.value("Game/Words").toString());
				if (file.open(QFile::ReadOnly)) {
					QByteArray data = file.readAll();
					file.close();
					game.setValue("Game/Words", data.toBase64());
				}
			}
		}
		gzip(filename);
	}
}
Esempio n. 14
0
File: gzip.c Progetto: aahud/harvey
void
main(int argc, char *argv[])
{
	int i, ok, stdout;

	level = 6;
	stdout = 0;
	ARGBEGIN{
	case 'D':
		debug++;
		break;
	case 'v':
		verbose++;
		break;
	case 'c':
		stdout = 1;
		break;
	case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		level = ARGC() - '0';
		break;
	default:
		usage();
		break;
	}ARGEND

	crctab = mkcrctab(GZCRCPOLY);
	ok = deflateinit();
	if(ok != FlateOk)
		sysfatal("deflateinit failed: %s", flateerr(ok));

	if(argc == 0){
		Binit(&bout, 1, OWRITE);
		ok = gzip(nil, time(0), 0, &bout);
		Bterm(&bout);
	}else{
		ok = 1;
		for(i = 0; i < argc; i++)
			ok &= gzipf(argv[i], stdout);
	}
	exits(ok ? nil: "errors");
}
Esempio n. 15
0
void MagnatuneService::ReloadDatabaseFinished() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

  app_->task_manager()->SetTaskFinished(load_database_task_id_);
  load_database_task_id_ = 0;

  if (reply->error() != QNetworkReply::NoError) {
    // TODO: Error handling
    qLog(Error) << reply->errorString();
    return;
  }

  if (root_->hasChildren()) root_->removeRows(0, root_->rowCount());

  // The XML file is compressed
  QtIOCompressor gzip(reply);
  gzip.setStreamFormat(QtIOCompressor::GzipFormat);
  if (!gzip.open(QIODevice::ReadOnly)) {
    qLog(Warning) << "Error opening gzip stream";
    return;
  }

  // Remove all existing songs in the database
  library_backend_->DeleteAll();

  // Parse the XML we got from Magnatune
  QXmlStreamReader reader(&gzip);
  SongList songs;
  while (!reader.atEnd()) {
    reader.readNext();

    if (reader.tokenType() == QXmlStreamReader::StartElement &&
        reader.name() == "Track") {
      songs << ReadTrack(reader);
    }
  }

  // Add the songs to the database
  library_backend_->AddOrUpdateSongs(songs);
  library_model_->Reset();
}
Esempio n. 16
0
      /// <summary>Opens a stream for writing</summary>
      /// <param name="filename">Optional: Name of file within GZip archive, if desired</param>
      /// <returns></returns>
      /// <exception cref="Logic::GZipException">Unable to inititalise stream</exception>
      /// <exception cref="Logic::IOException">Unable to create file</exception>
      StreamPtr  XFileInfo::OpenWrite(const wstring& filename) const
      {
         // Ensure physical
         if (Source == FileSource::Catalog)
            throw InvalidOperationException(HERE, L"Catalog based files are read-only");

         // basic file stream
         StreamPtr s(new FileStream(FullPath, FileMode::CreateAlways, FileAccess::Write));

         // PCK: Wrap in GZip compression stream
         if (FullPath.HasExtension(L".pck") || FullPath.HasExtension(L".zip"))
         {
            shared_ptr<GZipStream> gzip(new GZipStream(s, GZipStream::Operation::Compression));

            // Set filename within archive
            gzip->SetFileName(!filename.empty() ? filename : FullPath.RemoveExtension().FileName);
            return gzip;
         }

         // Return stream
         return s;
      }
Esempio n. 17
0
void *
save_crashdump(void *arg)
{
	struct mic_info *mic = (struct mic_info *)arg;
	struct mpssd_info *mpssdi = (struct mpssd_info *)mic->data;
	int cdfd = -1;
	int procfd = -1;
	void *addr = NULL;
	ssize_t bytes;
	ssize_t total_bytes = 0;
	ssize_t dirlimit;
	ssize_t diractual;
	struct tm *tm = NULL;
	char pathname[PATH_MAX];
	time_t t;
	pid_t pid1 = 0;
	char *state;
	char *save;
	struct stat sbuf;
	struct statvfs vbuf;
	int err;

	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

	if ((dirlimit = atoi(CD_LIMIT) * (1024 * 1024 * 1024ULL)) == 0) {
		mpsslog(PWARN, "%s: [SaveCrashDump] Dump disabled\n", mic->name);
		goto reboot;
	}

	if (stat(CD_DIR, &sbuf) < 0) {
		if (mkdir(CD_DIR, 0755) < 0) {
			mpsslog(PWARN, "%s: [SaveCrashDump] Avborted - create directory %s failed: %s\n",
					mic->name, CD_DIR, strerror(errno));
			goto reboot;
		}

		diractual = dirlimit;
	} else {	/* Check size of crash directory with configured limits */
		if ((diractual = get_dir_size(mic, CD_DIR)) < 0) {
			mpsslog(PINFO, "%s: [SaveCrashDump] Avborted - get directory %s size failed: %s\n",
					mic->name, CD_DIR, strerror(errno));
			goto reboot;
		}
	}

	if (diractual > dirlimit) {
		mpsslog(PINFO, "%s: [SaveCrashDump] Avborted - %s current size 0x%lx configured limit 0x%lx\n",
			mic->name, CD_DIR, diractual, dirlimit);
		goto reboot;
	}

	/* Open core dump file with time details embedded in file name */
	time(&t);
	if ((tm = localtime(&t)) == 0) {
		mpsslog(PERROR, "%s: [SaveCrashdump] Aborted - get system date failed\n", mic->name);
		goto reboot;
	}

	/* Create crash directories if not done already */
	snprintf(pathname, PATH_MAX - 1, "%s/%s", CD_DIR, mic->name);
	if (mkdir(pathname, 0755) && errno != EEXIST) {
		mpsslog(PERROR, "%s: [SaveCrashDump] Aborted - create directory %s failed %s\n",
					mic->name, pathname, strerror(errno));
		goto reboot;
	}

	if (statvfs(pathname, &vbuf) < 0) {
		mpsslog(PERROR, "%s: [SaveCrashDump] Aborted - cannot read free disk size of %s: %s\n",
					mic->name, pathname, strerror(errno));
		goto reboot;
	}

	if (CD_MIN_DISK > (vbuf.f_bsize * vbuf.f_bfree)) {
		mpsslog(PERROR, "%s: [SaveCrashDump] Aborted - free disk space less than required 32Gb\n", mic->name);
		goto reboot;
	}

	/* Open vmcore entry for crashed card */
	snprintf(pathname, PATH_MAX - 1, "/proc/mic_vmcore/%s", mic->name);
	if ((procfd = open(pathname, O_RDONLY)) < 0) {
		mpsslog(PERROR, "%s: [SaveCrashdump] Aborted - open %s failed: %s\n",
					mic->name, pathname, strerror(errno));
		goto reboot;
	}

	snprintf(pathname, PATH_MAX - 1, "%s/%s/vmcore-%d-%d-%d-%d:%d:%d", CD_DIR, mic->name,
			tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
			tm->tm_hour, tm->tm_min, tm->tm_sec);

	if ((cdfd = open(pathname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)) < 0) {
		mpsslog(PERROR, "%s: [SaveCrashDump] Aborted - open %s failed %s\n",
					mic->name, pathname, strerror(errno));
		goto cleanup1;
	}

	mpsslog(PINFO, "%s: [SaveCrashDump] Capturing uOS kernel crash dump\n", mic->name);

	/* Read from the proc entry and write to the core dump file */
	do {
		if (lseek(cdfd, CD_READ_CHUNK, SEEK_CUR) < 0) {
			mpsslog(PERROR, "%s: [SaveCrashDump] Aborted lseek failed %s\n", mic->name, strerror(errno));
			remove(pathname);
			goto cleanup2;
		}

		bytes = write(cdfd, "", 1);
		if (bytes != 1) {
			mpsslog(PERROR, "%s: [SaveCrashDump] Aborted write failed %s\n", mic->name, strerror(errno));
			remove(pathname);
			goto cleanup2;
		}

		if ((addr = mmap(NULL, CD_READ_CHUNK, PROT_READ|PROT_WRITE,
					MAP_SHARED, cdfd, total_bytes)) == MAP_FAILED) {
			mpsslog(PERROR, "%s: [SaveCrasdDump] Aborted mmap failed %s\n", mic->name, strerror(errno));
			remove(pathname);
			goto cleanup2;
		}

		if ((bytes = read(procfd, addr, CD_READ_CHUNK)) < 0) {
			mpsslog(PERROR, "%s: [SaveCrashDump] Aborted read failed %s\n", mic->name, strerror(errno));
			remove(pathname);
			munmap(addr, CD_READ_CHUNK);
			goto cleanup2;
		}

		total_bytes += bytes;
		munmap(addr, CD_READ_CHUNK);
		if (ftruncate(cdfd, total_bytes + 1) < 0) {
			mpsslog(PERROR, "%s: [SaveCrashDump] Aborted ftruncate failed %s\n", mic->name, strerror(errno));
			remove(pathname);
			goto cleanup2;
		}
	} while (bytes == CD_READ_CHUNK);

	mpsslog(PNORM, "%s: [SaveCrashDump] Completed raw dump size 0x%lx\n", mic->name, total_bytes);
	mpsslog(PNORM, "%s: [SaveCrashDump] Gzip started\n", mic->name);
	pid1 = gzip(pathname); /* Initiate compression of the file and reset MIC in parallel */


cleanup2:
	close(cdfd);

cleanup1:
	close(procfd);

reboot:
	if ((err = mpss_setsysfs(mic->name, "state", "reset:force")) != 0) {
		mpsslog(PINFO, "%s: [SaveCrashDump] Failed to set state sysfs - cannot reset: %s\n",
				mic->name, strerror(err));
		goto done;
	}

	if ((state = mpss_readsysfs(mic->name, "state")) == NULL) {
		mpsslog(PINFO, "%s: [SaveCrashDump] Failed to read state sysfs - state of reset unknown\n", mic->name);
		goto done;
	}

	while (strcmp(state, "ready") && strcmp(state, "reset failed")) {
		if (!strcmp(state, "online") || !strcmp(state, "booting")) {
			mpsslog(PINFO, "%s: [SaveCrashDump] External entity has already rebooted card\n", mic->name);
			free(state);
			goto done;
		}

		mpsslog(PINFO, "%s: [SaveCrashDump] Waiting for reset\n", mic->name);
		sleep(2);
		save = state;

		if ((state = mpss_readsysfs(mic->name, "state")) == NULL) {
			mpsslog(PWARN, "%s: [SaveCrashDump] wait for ready failed to read state sysfs - try again\n",
					mic->name);
			state = save;
		} else {
			free(save);
		}
	}

	if (strcmp(state, "ready")) {
		mpsslog(PERROR, "%s: [SaveCrashDump] Failed to reset card.  Aborting reboot\n", mic->name);
		free(state);
		goto done;
	}

	if (pid1 && (pid1 < 0 || ((waitpid(pid1, NULL, 0)) < 0)))
		remove(pathname);

	if (autoreboot(mic)) {
		while (pthread_mutex_lock(&start_lock) != 0);
		start_count++;
		while (pthread_mutex_lock(&mpssdi->pth_lock) != 0);
		pthread_create(&mpssdi->boot_pth, NULL, boot_mic, mic);
		while (pthread_mutex_unlock(&mpssdi->pth_lock) != 0);
		while (pthread_mutex_unlock(&start_lock) != 0);
	}
done:
	pthread_exit(NULL);
}
Esempio n. 18
0
void Cdlg_make_torrent::OnSave()
{
	if (!UpdateData())
		return;
	m_name.TrimRight(" ");
	m_tracker.TrimRight(" ");
	CFileDialog dlg(false, "torrent", m_name + ".torrent", OFN_ENABLESIZING | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST, "Torrents|*.torrent|", this);
	if (IDOK != dlg.DoModal())
		return;
	CWaitCursor wc;
	AfxGetApp()->WriteProfileString(m_strRegStore, "tracker", m_tracker);
	AfxGetApp()->WriteProfileString(m_strRegStore, "trackers", m_trackers);
	AfxGetApp()->WriteProfileInt(m_strRegStore, "use_merkle", m_use_merkle);
	int cb_piece = 1 << 20;
	if (!m_use_merkle)
	{
		long long cb_total = 0;
		for (t_map::const_iterator i = m_map.begin(); i != m_map.end(); i++)
			cb_total += i->second.size;
		cb_piece = 256 << 10;
		while (cb_total / cb_piece > 4 << 10)
			cb_piece <<= 1;
	}
	typedef std::set<std::string> t_set;
	t_set set;
	for (t_map::const_iterator i = m_map.begin(); i != m_map.end(); i++)
		set.insert(i->second.name);
	Cbvalue files;
	std::string pieces;
	Cvirtual_binary d;
	byte* w = d.write_start(cb_piece);
	for (t_set::const_iterator i = set.begin(); i != set.end(); i++)
	{
		int f = open(i->c_str(), _O_BINARY | _O_RDONLY);
		if (!f)
			continue;
		long long cb_f = 0;
		std::string merkle_hash;
		int cb_d;
		if (m_use_merkle)
		{
			typedef std::map<int, std::string> t_map;

			t_map map;
			char d[1025];
			while (cb_d = read(f, d + 1, 1024))
			{
				if (cb_d < 0)
					break;
				*d = 0;
				std::string h = Csha1(const_memory_range(d, cb_d + 1)).read();
				*d = 1;
				int i;
				for (i = 0; map.find(i) != map.end(); i++)
				{
					memcpy(d + 1, map.find(i)->second.c_str(), 20);
					memcpy(d + 21, h.c_str(), 20);
					h = Csha1(const_memory_range(d, 41)).read();
					map.erase(i);
				}
				map[i] = h;
				cb_f += cb_d;
			}
			*d = 1;
			while (map.size() > 1)
			{
				memcpy(d + 21, map.begin()->second.c_str(), 20);
				map.erase(map.begin());
				memcpy(d + 1, map.begin()->second.c_str(), 20);
				map.erase(map.begin());
				map[0] = Csha1(const_memory_range(d, 41)).read();
			}
			if (!map.empty())
				merkle_hash = map.begin()->second;
		}
		else
		{
			while (cb_d = read(f, w, d.end() - w))
			{
				if (cb_d < 0)
					break;
				w += cb_d;
				if (w == d.end())
				{
					pieces += Csha1(const_memory_range(d, w - d)).read();
					w = d.data_edit();
				}
				cb_f += cb_d;
			}
		}
		close(f);
		files.l(merkle_hash.empty()
			? Cbvalue().d(bts_length, cb_f).d(bts_path, Cbvalue().l(base_name(*i)))
			: Cbvalue().d(bts_merkle_hash, merkle_hash).d(bts_length, cb_f).d(bts_path, Cbvalue().l(base_name(*i))));
	}
	if (w != d)
		pieces += Csha1(const_memory_range(d, w - d)).read();
	Cbvalue info;
	info.d(bts_piece_length, cb_piece);
	if (!pieces.empty())
		info.d(bts_pieces, pieces);
	if (m_map.size() == 1)
	{
		if (m_use_merkle)
			info.d(bts_merkle_hash, files.l().front()[bts_merkle_hash]);
		info.d(bts_length, files.l().front()[bts_length]);
		info.d(bts_name, files.l().front()[bts_path].l().front());
	}
	else
	{
		info.d(bts_files, files);
		info.d(bts_name, static_cast<std::string>(m_name));
	}
	Cbvalue torrent;
	torrent.d(bts_announce, static_cast<std::string>(m_tracker));
	if (!m_trackers.IsEmpty())
		torrent.d(bts_announce_list, parse_trackers(static_cast<std::string>(m_trackers)));
	torrent.d(bts_info, info);
	Cvirtual_binary s = torrent.read();
	if (m_use_merkle)
		s = gzip(s);
	s.save(static_cast<std::string>(dlg.GetPathName()));
	m_torrent_fname = dlg.GetPathName();
	EndDialog(IDOK);
}
Esempio n. 19
0
int main(int argc, char* argv[])
{


	stream::zip::GZIP gzip(stream::zip::OPEN_FOR_COMPRESS);

	io::Blob<unsigned char> buffer;

	gzip.Init();

	FILE* file = fopen("C:\\pru.gz","wb");
	buffer = gzip.Update((unsigned char*)"Hoal chavalote",13);
	fwrite(buffer.get(),buffer.length(),1,file);
	buffer = gzip.Finish();
	fwrite(buffer.get(),buffer.length(),1,file);

	fclose(file);

	/*stream::zip::GZOutputStream fileOut("C:\\pru.gz");

	fileOut.write((unsigned char*)"Hoal chavalote",14);

	fileOut.close();*/



	/*io::Blob<char> buff = stream::util::FileUtil::File2Buffer("C:\\pru.gz");

	stream::zip::GZIP gzip2(stream::zip::OPEN_FOR_UNCOMPRESS);

	gzip2.Init();
	
	buffer = gzip2.Update((unsigned char*)buff.get(),buff.length()-10);
	buffer = gzip2.Update((unsigned char*)buff.get()+buff.length()-10,10);
	buffer = gzip2.Finish();*/


	io::FileInputStream fileIn("c:\\pru.gz");

	zip::GZIPInputStream gz(zip::OPEN_FOR_UNCOMPRESS,&fileIn);

	while(gz.available())
	{
		/*unsigned char buffer4[100];
		int readed = gz.read(buffer4,100);*/
		int c = gz.read();
	}



	/*

	CoInitialize(NULL);

	LiteLog* log = util::LiteLog::getInstance();
	
	
	
	log->traceOn("CON|HOla consola|5","Prueba");
	log->trace(string("CON|HOla consola|5"));


	std::string va = SystemInfo::getIEVersion();

	std::string s = SystemInfo::readRegistryString("HKEY_CURRENT_USER\\Software\\HermesWeb\\Configuracion\\PathDocs");
	try
	{
		auto_ptr<Connection> connection = Connection::createConnection("DSN=BakeMail");

		auto_ptr<PreparedStatement> statement = connection->prepareStatement("SELECT * FROM servers WHERE id_server >= ?");

		statement->setLong(1,3);


		auto_ptr<ResultSet> result = statement->executeQuery();

		result->moveFirst();

		while(!result->eof())
		{
			cout << result->getString("server") << endl;
			cout << result->getString("port") << endl;
			cout << result->getString("user") << endl;
			cout << result->getString("password") << endl;
			cout << result->getString("check2") << endl << endl;

			result->moveNext();
		}

		result->close();


		auto_ptr<PreparedStatement> statement2 = connection->prepareStatement("INSERT INTO servers VALUES('','servidor','puerto','usuario','password12','not check')");

		statement2->execute();


		auto_ptr<PreparedStatement> statement3 = connection->prepareStatement("INSERT INTO servers VALUES('','servidor','?','usuario','password12','not check')");
		for(int i = 30 ; i < 32 ; i++)
		{
			statement3->setLong(1,i);

			statement3->execute();
		}


		connection->close();
	}catch(exceptions::StreamException* e)
	{
		cout << e->what() << endl;
	}

	CoUninitialize();*/
	return 0;
}
Esempio n. 20
0
int main(int argc, char* argv[])
{
	time_t t = time(NULL);
	if (argc < 2)
	{
		std::cerr << "Usage: " << argv[0] << " <file> <tracker> [--v1]" << std::endl;
		return 1;
	}
	std::string tracker = argc >= 3 ? argv[2] : "udp://localhost:2710";
	bool use_merkle = argc >= 4 ? strcmp(argv[3], "--v1") : true; // set to false for a non-merkle torrent
	insert(argv[1]);
	// use 1 mbyte pieces by default
	int cb_piece = 1 << 20;
	if (!use_merkle)
	{
		// find optimal piece size for a non-merkle torrent
		long long cb_total = 0;
		for (t_map::const_iterator i = g_map.begin(); i != g_map.end(); i++)
			cb_total += i->second.size;
		cb_piece = 256 << 10;
		while (cb_total / cb_piece > 4 << 10)
			cb_piece <<= 1;
	}
	Cbvalue files;
	std::string pieces;
	Cvirtual_binary d;
	byte* w = d.write_start(cb_piece);
	for (t_map::const_iterator i = g_map.begin(); i != g_map.end(); i++)
	{
		int f = open(i->second.name.c_str(), O_BINARY | O_RDONLY);
		if (!f)
			continue;
		long long cb_f = 0;
		std::string merkle_hash;
		int cb_d;
		if (use_merkle)
		{
			// calculate merkle root hash as explained in XBT Make Merkle Tree.cpp
			typedef std::map<int, std::string> t_map;

			t_map map;
			char d[1025];
			while (cb_d = read(f, d + 1, 1024))
			{
				if (cb_d < 0)
					break;
				*d = 0;
				std::string h = Csha1(const_memory_range(d, cb_d + 1)).read();
				*d = 1;
				int i;
				for (i = 0; map.find(i) != map.end(); i++)
				{
					memcpy(d + 1, map.find(i)->second.c_str(), 20);
					memcpy(d + 21, h.c_str(), 20);
					h = Csha1(const_memory_range(d, 41)).read();
					map.erase(i);
				}
				map[i] = h;
				cb_f += cb_d;
			}
			*d = 1;
			while (map.size() > 1)
			{
				memcpy(d + 21, map.begin()->second.c_str(), 20);
				map.erase(map.begin());
				memcpy(d + 1, map.begin()->second.c_str(), 20);
				map.erase(map.begin());
				map[0] = Csha1(const_memory_range(d, 41)).read();
			}
			if (!map.empty())
				merkle_hash = map.begin()->second;
		}
		else
		{
			// calculate piece hashes
			while (cb_d = read(f, w, d.data_end() - w))
			{
				if (cb_d < 0)
					break;
				w += cb_d;
				if (w == d.data_end())
				{
					pieces += Csha1(const_memory_range(d, w - d)).read();
					w = d.data_edit();
				}
				cb_f += cb_d;
			}
		}
		close(f);
		// add file to files key
		files.l(merkle_hash.empty()
			? Cbvalue().d(bts_length, cb_f).d(bts_path, Cbvalue().l(base_name(i->second.name)))
			: Cbvalue().d(bts_merkle_hash, merkle_hash).d(bts_length, cb_f).d(bts_path, Cbvalue().l(base_name(i->second.name))));
	}
	if (w != d)
		pieces += Csha1(const_memory_range(d, w - d)).read();
	Cbvalue info;
	info.d(bts_piece_length, cb_piece);
	if (!pieces.empty())
		info.d(bts_pieces, pieces);
	if (g_map.size() == 1)
	{
		// single-file torrent
		if (use_merkle)
			info.d(bts_merkle_hash, files.l().front().d(bts_merkle_hash));
		info.d(bts_length, files.l().front().d(bts_length));
		info.d(bts_name, files.l().front().d(bts_path).l().front());
	}
	else
	{
		// multi-file torrent
		info.d(bts_files, files);
		info.d(bts_name, g_name);
	}
	Cbvalue torrent;
	torrent.d(bts_announce, tracker);
	torrent.d(bts_info, info);
	Cvirtual_binary s = torrent.read();
	if (use_merkle)
		s = gzip(s);
	s.save(g_name + ".torrent");
	std::cout << time(NULL) - t << " s" << std::endl;
	return 0;
}
Esempio n. 21
0
File: gzip.c Progetto: aahud/harvey
static int
gzipf(char *file, int stdout)
{
	Dir *dir;
	char ofile[256], *f, *s;
	int ifd, ofd, ok;

	ifd = open(file, OREAD);
	if(ifd < 0){
		fprint(2, "gzip: can't open %s: %r\n", file);
		return 0;
	}
	dir = dirfstat(ifd);
	if(dir == nil){
		fprint(2, "gzip: can't stat %s: %r\n", file);
		close(ifd);
		return 0;
	}
	if(dir->mode & DMDIR){
		fprint(2, "gzip: can't compress a directory\n");
		close(ifd);
		free(dir);
		return 0;
	}

	if(stdout){
		ofd = 1;
		strcpy(ofile, "<stdout>");
	}else{
		f = strrchr(file, '/');
		if(f != nil)
			f++;
		else
			f = file;
		s = strrchr(f, '.');
		if(s != nil && s != ofile && strcmp(s, ".tar") == 0){
			*s = '\0';
			snprint(ofile, sizeof(ofile), "%s.tgz", f);
		}else
			snprint(ofile, sizeof(ofile), "%s.gz", f);
		ofd = create(ofile, OWRITE, 0666);
		if(ofd < 0){
			fprint(2, "gzip: can't open %s: %r\n", ofile);
			close(ifd);
			return 0;
		}
	}

	if(verbose)
		fprint(2, "compressing %s to %s\n", file, ofile);

	Binit(&bout, ofd, OWRITE);
	ok = gzip(file, dir->mtime, ifd, &bout);
	if(!ok || Bflush(&bout) < 0){
		fprint(2, "gzip: error writing %s: %r\n", ofile);
		if(!stdout)
			remove(ofile);
	}
	Bterm(&bout);
	free(dir);
	close(ifd);
	close(ofd);
	return ok;
}
Esempio n. 22
0
uint8_t Options::compression() const
{
    if (bzip2()) return 3;
    if (gzip()) return 2;
    return 1;
}