Example #1
0
bool ThemeLoader::extractTarGz( const string &tarFile, const string &rootDir )
{
    TAR *t;
#if defined( HAVE_LIBTAR_H )
    tartype_t gztype = { (openfunc_t) gzopen_frontend,
                         (closefunc_t) gzclose_frontend,
                         (readfunc_t) gzread_frontend,
                         (writefunc_t) gzwrite_frontend };

    if( tar_open( &t, (char *)tarFile.c_str(), &gztype, O_RDONLY, 0,
                  TAR_GNU ) == -1 )
#else
    if( tar_open( &t, (char *)tarFile.c_str(), O_RDONLY ) == -1 )
#endif
    {
        return false;
    }

    if( tar_extract_all( t, (char *)rootDir.c_str() ) != 0 )
    {
        tar_close( t );
        return false;
    }

    if( tar_close( t ) != 0 )
    {
        return false;
    }

    return true;
}
Example #2
0
static int
create(char *tarfile, char *rootdir, libtar_list_t *l)
{
  TAR *t;
  char *pathname;
  char buf[TAR_MAXPATHLEN];
  libtar_listptr_t lp;

  if (tar_open(&t, tarfile,
#ifdef HAVE_LIBZ
         (use_zlib ? &gztype : NULL),
#else
         NULL,
#endif
         O_WRONLY | O_CREAT, 0644,
         (verbose ? TAR_VERBOSE : 0)
         | (use_gnu ? TAR_GNU : 0)) == -1)
  {
    fprintf(stderr, "tar_open(): %s\n", strerror(errno));
    return -1;
  }

  libtar_listptr_reset(&lp);
  while (libtar_list_next(l, &lp) != 0)
  {
    pathname = (char *)libtar_listptr_data(&lp);
    if (pathname[0] != '/' && rootdir != NULL)
      snprintf(buf, sizeof(buf), "%s/%s", rootdir, pathname);
    else
      strlcpy(buf, pathname, sizeof(buf));
    if (tar_append_tree(t, buf, pathname) != 0)
    {
      fprintf(stderr,
        "tar_append_tree(\"%s\", \"%s\"): %s\n", buf,
        pathname, strerror(errno));
      tar_close(t);
      return -1;
    }
  }

  if (tar_append_eof(t) != 0)
  {
    fprintf(stderr, "tar_append_eof(): %s\n", strerror(errno));
    tar_close(t);
    return -1;
  }

  if (tar_close(t) != 0)
  {
    fprintf(stderr, "tar_close(): %s\n", strerror(errno));
    return -1;
  }

  return 0;
}
Example #3
0
int main(int ac, const char *av[])
{
	struct rlimit r;
	unsigned count, i;
	char *s;
	TAR *t;

	if (ac != 2)
		error(1, 0, "exactly two arguments expected");

	if (getrlimit(RLIMIT_STACK, &r))
		error(1, errno, "getrlimit RLIMIT_STACK");

	count = r.rlim_cur / 3 + 1;
	if (!(s = malloc(count * 3 + 1)))
		error(1, errno, "malloc: %u", count * 3 + 1);

	for (i = 0; i < count; ++i)
		memcpy(s + i * 3, "../", 3);
	s[count * 3] = '\0';

	if (tar_open(&t, av[1], NULL, O_WRONLY|O_CREAT, 0644, TAR_GNU))
		error(1, errno, "tar_open: %s", av[1]);

	if (tar_append_file(t, "/dev/null", s))
		error(1, errno, "tar_append_file: %s", av[1]);

	if (tar_close(t))
		error(1, errno, "tar_close");

	return 0;
}
Example #4
0
/**
  Archive a tar or tar.gz archive in \arg tarfile, from the path in \a srcpath.
  If \a verbose is true, echo a line on stdout for each file archived.
  The libtar and libz implementations are used.  If the filename \a tarfile
  ends with the characters "gz" then gz stream i/o is used for storing the tar.
  If the \arg gzip is true, then gz will be used regardless of the filename.
  Otherwise the file is created as a normal .tar archive.  The return result is
  true if the operation succeeded.
*/
bool targz_archive_all( const QString &tarfile, const QString &srcpath, bool gzip, bool verbose )
{
    QByteArray pathnameArr = tarfile.toLocal8Bit();
    char *pathname = pathnameArr.data();
    QByteArray prefixArr = srcpath.toLocal8Bit();
    char *prefix = prefixArr.data();

    TAR *tarHandle;

    int options = TAR_GNU;
    if ( verbose ) options |= TAR_VERBOSE;

    int filemode = 0;  // only care about this if creating files (ie untar)

    tartype_t *arctype = 0;

    if ( gzip || tarfile.endsWith( "gz" )) arctype = &zlibtype;

    int result = tar_open( &tarHandle, pathname, arctype, O_WRONLY, filemode, options);

    if ( result < 0 )
    {
        qWarning( "error opening tar file %s: %s", pathname, strerror(errno) );
        return false;
    }

    result = tar_append_tree( tarHandle, prefix, prefix );

    if ( result < 0 )
        qWarning( "error archiving to tar file %s: %s", pathname, strerror(errno) );

    tar_close( tarHandle );
    return ( result >= 0 );
}
Example #5
0
int main(int argc, char **argv)
{
	int ret;
	if(argc < 3) {
		fprintf(stderr, "Usage: %s old new [patch]\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	t = NULL;

	if(argc >= 4) {
		if(!strcmp(argv[3], "-"))
			ret = tar_fdopen(&t, 1, "stdout", NULL, O_WRONLY|O_CREAT, 0644, TAR_GNU/*|TAR_VERBOSE*/);
		else
			ret = tar_open(&t, argv[3], NULL, O_WRONLY|O_CREAT, 0644, TAR_GNU/*|TAR_VERBOSE*/);
		if(ret != 0) {
			fprintf(stderr, "%d\n", ret);
			perror("tar_open");
		}
	}

	base1 = argv[1];
	base2 = argv[2];
	cmpdir(argv[1], argv[2]);

	if(t) {
		tar_append_eof(t);
		tar_close(t);
	}

	return 0;
}
Example #6
0
static int setup_unix_environment(const char* tarfile) {
  // Extra tar achive from http filesystem.
  if (tarfile) {
    int ret;
    TAR* tar;
    char filename[PATH_MAX];
    strcpy(filename, "/mnt/http/");
    strcat(filename, tarfile);
    ret = tar_open(&tar, filename, NULL, O_RDONLY, 0, 0);
    if (ret) {
      printf("error opening %s\n", filename);
      return 1;
    }

    ret = tar_extract_all(tar, "/");
    if (ret) {
      printf("error extracting %s\n", filename);
      return 1;
    }

    ret = tar_close(tar);
    assert(ret == 0);
  }

  // Setup environment variables
  setenv("HOME", "/home", 1);
  setenv("PATH", "/bin", 1);
  setenv("USER", "user", 1);
  setenv("LOGNAME", "user", 1);

  setlocale(LC_CTYPE, "");
  return 0;
}
Example #7
0
static int setup_unix_environment(const char* tarfile) {
  // Extra tar achive from http filesystem.
  if (tarfile) {
    int ret;
    TAR* tar;
    char filename[PATH_MAX];
    strcpy(filename, "/mnt/http/");
    strcat(filename, tarfile);
    ret = tar_open(&tar, filename, NULL, O_RDONLY, 0, 0);
    if (ret) {
      printf("error opening %s\n", filename);
      return 1;
    }

    ret = tar_extract_all(tar, "/");
    if (ret) {
      // TODO(petewil): Remove next line before shipping
      printf("errno is %d\n", errno);
      printf("error extracting %s\n", filename);
      return 1;
    }

    ret = tar_close(tar);
    assert(ret == 0);
  }

  return 0;
}
Example #8
0
static int
list(char *tarfile)
{
  TAR *t;
  int i;

  if (tar_open(&t, tarfile,
#ifdef HAVE_LIBZ
         (use_zlib ? &gztype : NULL),
#else
         NULL,
#endif
         O_RDONLY, 0,
         (verbose ? TAR_VERBOSE : 0)
         | (use_gnu ? TAR_GNU : 0)) == -1)
  {
    fprintf(stderr, "tar_open(): %s\n", strerror(errno));
    return -1;
  }

  while ((i = th_read(t)) == 0)
  {
    th_print_long_ls(t);
#ifdef DEBUG
    th_print(t);
#endif
    if (TH_ISREG(t) && tar_skip_regfile(t) != 0)
    {
      fprintf(stderr, "tar_skip_regfile(): %s\n",
        strerror(errno));
      return -1;
    }
  }

#ifdef DEBUG
  printf("th_read() returned %d\n", i);
  printf("EOF mark encountered after %ld bytes\n",
# ifdef HAVE_LIBZ
         (use_zlib
    ? gzseek((gzFile) t->fd, 0, SEEK_CUR)
    :
# endif
         lseek(t->fd, 0, SEEK_CUR)
# ifdef HAVE_LIBZ
         )
# endif
         );
#endif

  if (tar_close(t) != 0)
  {
    fprintf(stderr, "tar_close(): %s\n", strerror(errno));
    return -1;
  }
  (void)i;

  return 0;
}
Example #9
0
/* \internal
   Checks whether a tar file is valid.
   A valid tar file does not contains files
   that start with ./ or contain ..

   This is intended to prevent malicious packages
   placing binaries outside of the sandbox directory
*/
bool check_tar_valid( const QString &tarfile )
{
    TAR *tarHandle = get_tar_ptr( tarfile );

    bool ret=true;
    QString filename;
    int i;
    while ( (i = th_read(tarHandle)) == 0)
    {
        filename = th_get_pathname( tarHandle );

        if ( !filename.startsWith("./") || filename.contains( "..") )
        {
            ret = false;
            qWarning() << "check_tar_valid:- tar contains invalid file path: "
                << filename << "\nAll paths must begin with ./ and not contain .."  ;
            break;
        }
        else if ( TH_ISBLK(tarHandle) || TH_ISCHR(tarHandle) )
        {
            ret = false;
            qWarning() << "check_tar_valid:-tar invalid, contains device special file:"
                << filename;
            break;
        }
        else if ( TH_ISLNK(tarHandle) )
        {
            ret = false;
            qWarning() << "check_tar_valid:-tar invalid, contains hard link:"
                       << filename;
            break;
        } else if (TH_ISSYM(tarHandle) )
        {
            QString target;
            if ((tarHandle->options & TAR_GNU) && tarHandle->th_buf.gnu_longlink != NULL)
                target = tarHandle->th_buf.gnu_longlink;
            else
                target = tarHandle->th_buf.linkname;
            if ( target.startsWith("/") || target.contains( "..") )
            {
                ret = false;
                qWarning() << "check_tar_valid:tar invalid, contains symlink whose target"
                           << (target.startsWith("/")?"is an absolute path.":"references "
                              "a parent directory.")
                           << "Link:" << filename << "Target:" << target;
                break;
            }
        }


        if( TH_ISREG(tarHandle) )
            tar_skip_regfile(tarHandle);
    }

    tar_close( tarHandle );
    return ret;
}
Example #10
0
/**
  Extract a tar or tar.gz archive in \arg tarfile, to the path in \a destpath.
  If \a verbose is true, echo a line on stdout for each file extracted.
  The libtar and libz implementations are used.  The file \a tarfile is tested
  for the magic number indicating a gzip file, and if present gz stream i/o is
  used, otherwise the file is assumed to be a normal .tar archive.  Note that
  the file extension is ignored since many files such as package format files,
  use other extensions.  The return result is true if the operation succeeded.
*/
bool targz_extract_all( const QString &tarfile, const QString &destpath, bool verbose )
{
    QByteArray pathnameArr = tarfile.toLocal8Bit();
    char *pathname = pathnameArr.data();
    QByteArray prefixArr = destpath.toLocal8Bit();
    char *prefix = destpath.isEmpty() ? 0 : prefixArr.data();

    TAR *tarHandle;

    int options = TAR_GNU;
    if ( verbose ) options |= TAR_VERBOSE;

    int filemode = 0;  // only care about this if creating files (ie untar)

    tartype_t *arctype = 0;

    {
        // QFile and stream go away at end of scope
        QFile tfs( tarfile );
        if ( !tfs.exists() )
        {
            qWarning( "Targz_extract_all: file %s doesnt exist", pathname );
            return false;
        }
        tfs.open(QIODevice::ReadOnly);
        QDataStream tarbytes( &tfs );
        quint8 b1, b2;

        // if the first two bytes are the magic numbers for a gzip format
        // file, use the above zlib wrapped i/o function pointers, otherwise
        // assume normal uncompressed tar format (default)
        tarbytes >> b1 >> b2;
        if ( b1 == 0x1f && b2 == 0x8b ) arctype = &zlibtype;
    }

    int result = tar_open( &tarHandle, pathname, arctype, O_RDONLY, filemode, options);

    if ( result < 0 )
    {
        qWarning( "error opening tar file %s: %s", pathname, strerror(errno) );
        return false;
    }

    result = tar_extract_all( tarHandle, prefix );

    if ( result < 0 )
        qWarning( "error extracting tar file %s: %s", pathname, strerror(errno) );

    tar_close( tarHandle );
    return ( result >= 0 );
}
int
util_tar_extract(const char *tar_filename, const char* index_file, const char* out_dir)
{
	TAR *tar = NULL;

	int ret = tar_open(&tar, tar_filename, &gztype, O_RDONLY, 0, TAR_GNU);
	if (ret != 0) {
		ERROR_ERRNO("Fail to open tarfile: %s\n", tar_filename);
		return ret;
	}
	//ret = tar_extract_all(tar, tar_prefix);
	while (th_read(tar) == 0) {
		char *archive_filename = th_get_pathname(tar);
		char *out_filename = mem_printf("%s/%s", out_dir, archive_filename);

		char *mode = mem_alloc0(4*sizeof(char));
		int_to_oct(th_get_mode(tar), mode, 4*sizeof(char));
		uid_t uid = th_get_uid(tar);
		gid_t gid = th_get_gid(tar);

		INFO("Writing file %s to %s", archive_filename, out_filename);
		if (TH_ISCHR(tar)) {
			// writing file attributes to index file (TODO use hashmap to handle duplicates)
			file_printf_append(index_file, "%s c %s %d %d %d %d\n",
				archive_filename, mode, uid, gid,
				th_get_devmajor(tar),
				th_get_devminor(tar));
		} else if (TH_ISBLK(tar)) {
			// writing file attributes to index file (TODO use hashmap to handle duplicates)
			file_printf_append(index_file, "%s b %s %d %d %d %d\n",
				archive_filename, mode, uid, gid,
				th_get_devmajor(tar),
				th_get_devminor(tar));
		} else {
			if (tar_extract_file(tar, out_filename) != 0) {
				INFO_ERRNO("Skipping file: %s", archive_filename);
			} else {
				// writing file attributes to index file (TODO use hashmap to handle duplicates)
				file_printf_append(index_file, "%s m %s %d %d\n",
					archive_filename, mode, uid, gid);
			}
		}

		mem_free(mode);
		mem_free(archive_filename);
		mem_free(out_filename);
	}

	ret |= tar_close(tar);
	return ret;
}
Example #12
0
static int tarupthelist(char *tarfile, char *rootdir, libtar_list_t *l)
{
    TAR *t;
    char *pathname;
    char buf[TAR_MAXPATHLEN];

    if (tar_open(&t, tarfile, NULL, O_WRONLY | O_CREAT, 0644, (use_gnu ? TAR_GNU : 0)) == -1) {
        fprintf(stderr, "tar_open(): %s\n", strerror(errno));
        return -1;
    }

    libtar_listptr_t lp;
    libtar_listptr_reset(&lp);
    while (libtar_list_next(l, &lp) != 0) {
        pathname = (char *)libtar_listptr_data(&lp);
        if (pathname[0] != '/' && rootdir != NULL)
            snprintf(buf, sizeof(buf), "%s/%s", rootdir, pathname);
        else
            strncpy(buf, pathname, sizeof(buf));
        if (tar_append_tree(t, buf, pathname) != 0) {
            fprintf(stderr, "tar_append_tree(\"%s\", \"%s\"): %s\n", buf, pathname, strerror(errno));
            tar_close(t);
            return -1;
        }
    }

    if (tar_append_eof(t) != 0) {
        fprintf(stderr, "tar_append_eof(): %s\n", strerror(errno));
        tar_close(t);
        return -1;
    }

    if (tar_close(t) != 0) {
        fprintf(stderr, "tar_close(): %s\n", strerror(errno));
        return -1;
    }
    return 0;
}
Example #13
0
qlonglong targz_archive_size( const QString &tarfile )
{
    TAR *tarHandle = get_tar_ptr( tarfile );

    qlonglong size = 0;
    int i;
    while ((i = th_read(tarHandle)) == 0)
    {
        size += th_get_size(tarHandle);
        if( TH_ISREG(tarHandle) )
            tar_skip_regfile(tarHandle);
    }

    tar_close( tarHandle );
    return size;
}
Example #14
0
static int sandbox_close(void *fpctx,void *handle)
{
	int	i;
	sb_handle *h = handle;

	tar_close(h->t);
	free(h->tt);

	for (i=0; h->file_names; i++) free(h->file_names[i]);
	free(h->file_names);
	
	free(h);

	printf("sandbox_close() called\n");

	return 0;
}
Example #15
0
static int
extract(char *tarfile, char *rootdir)
{
  TAR *t;

#ifdef DEBUG
  puts("opening tarfile...");
#endif
  if (tar_open(&t, tarfile,
#ifdef HAVE_LIBZ
         (use_zlib ? &gztype : NULL),
#else
         NULL,
#endif
         O_RDONLY, 0,
         (verbose ? TAR_VERBOSE : 0)
         | (use_gnu ? TAR_GNU : 0)) == -1)
  {
    fprintf(stderr, "tar_open(): %s\n", strerror(errno));
    return -1;
  }

#ifdef DEBUG
  puts("extracting tarfile...");
#endif
  if (tar_extract_all(t, rootdir) != 0)
  {
    fprintf(stderr, "tar_extract_all(): %s\n", strerror(errno));
    return -1;
  }

#ifdef DEBUG
  puts("closing tarfile...");
#endif
  if (tar_close(t) != 0)
  {
    fprintf(stderr, "tar_close(): %s\n", strerror(errno));
    return -1;
  }

  return 0;
}
Example #16
0
int eclnacl_main(int argc, char **argv) {
  umount("/");
  mount("foo", "/", "memfs", 0, NULL);
  mount("./", "/mnt/tars", "httpfs", 0, NULL);

  mkdir("/home", 0777);

  /* Setup home directory to a known location. */
  setenv("HOME", "/", 1);
  /* Blank out USER and LOGNAME. */
  setenv("USER", "", 1);
  setenv("LOGNAME", "", 1);

  printf("Extracting: %s ...\n", "/mnt/tars/" DATA_FILE);
  TAR* tar;
  int ret = tar_open(&tar, "/mnt/tars/" DATA_FILE, NULL, O_RDONLY, 0, 0);
  if(!ret)
  {
    perror("tar_open");
  }

  ret = tar_extract_all(tar, "/");
  if(!ret)
  {
    perror("tar_extract_all");
  }
  printf("Extracting done\n");

  ret = tar_close(tar);
  if(!ret)
  {
    perror("tar_close");
  }

  return ecl_main(argc, argv);
}
Example #17
0
bool Drumkit::install( const QString& path )
{
	_INFOLOG( QString( "Install drumkit %1" ).arg( path ) );
#ifdef H2CORE_HAVE_LIBARCHIVE
	int r;
	struct archive* arch;
	struct archive_entry* entry;

	arch = archive_read_new();

#if ARCHIVE_VERSION_NUMBER < 3000000
	archive_read_support_compression_all( arch );
#else
	archive_read_support_filter_all( arch );
#endif

	archive_read_support_format_all( arch );

#if ARCHIVE_VERSION_NUMBER < 3000000
	if ( ( r = archive_read_open_file( arch, path.toLocal8Bit(), 10240 ) ) ) {
#else
	if ( ( r = archive_read_open_filename( arch, path.toLocal8Bit(), 10240 ) ) ) {
#endif
		_ERRORLOG( QString( "archive_read_open_file() [%1] %2" ).arg( archive_errno( arch ) ).arg( archive_error_string( arch ) ) );
		archive_read_close( arch );

		#if ARCHIVE_VERSION_NUMBER < 3000000
			archive_read_finish( arch );
		#else
			archive_read_free( arch );
		#endif

		return false;
	}
	bool ret = true;
	QString dk_dir = Filesystem::usr_drumkits_dir() + "/";
	while ( ( r = archive_read_next_header( arch, &entry ) ) != ARCHIVE_EOF ) {
		if ( r != ARCHIVE_OK ) {
			_ERRORLOG( QString( "archive_read_next_header() [%1] %2" ).arg( archive_errno( arch ) ).arg( archive_error_string( arch ) ) );
			ret = false;
			break;
		}
		QString np = dk_dir + archive_entry_pathname( entry );

		QByteArray newpath = np.toLocal8Bit();

		archive_entry_set_pathname( entry, newpath.data() );
		r = archive_read_extract( arch, entry, 0 );
		if ( r == ARCHIVE_WARN ) {
			_WARNINGLOG( QString( "archive_read_extract() [%1] %2" ).arg( archive_errno( arch ) ).arg( archive_error_string( arch ) ) );
		} else if ( r != ARCHIVE_OK ) {
			_ERRORLOG( QString( "archive_read_extract() [%1] %2" ).arg( archive_errno( arch ) ).arg( archive_error_string( arch ) ) );
			ret = false;
			break;
		}
	}
	archive_read_close( arch );

	#if ARCHIVE_VERSION_NUMBER < 3000000
		archive_read_finish( arch );
	#else
		archive_read_free( arch );
	#endif

	return ret;
#else // H2CORE_HAVE_LIBARCHIVE
#ifndef WIN32
	// GUNZIP
	QString gzd_name = path.left( path.indexOf( "." ) ) + ".tar";
	FILE* gzd_file = fopen( gzd_name.toLocal8Bit(), "wb" );
	gzFile gzip_file = gzopen( path.toLocal8Bit(), "rb" );
	if ( !gzip_file ) {
		_ERRORLOG( QString( "Error reading drumkit file: %1" ).arg( path ) );
		gzclose( gzip_file );
		fclose( gzd_file );
		return false;
	}
	uchar buf[4096];
	while ( gzread( gzip_file, buf, 4096 ) > 0 ) {
		fwrite( buf, sizeof( uchar ), 4096, gzd_file );
	}
	gzclose( gzip_file );
	fclose( gzd_file );
	// UNTAR
	TAR* tar_file;

	QByteArray tar_path = gzd_name.toLocal8Bit();

	if ( tar_open( &tar_file, tar_path.data(), NULL, O_RDONLY, 0,  TAR_GNU ) == -1 ) {
		_ERRORLOG( QString( "tar_open(): %1" ).arg( QString::fromLocal8Bit( strerror( errno ) ) ) );
		return false;
	}
	bool ret = true;
	char dst_dir[1024];
	QString dk_dir = Filesystem::usr_drumkits_dir() + "/";
	strncpy( dst_dir, dk_dir.toLocal8Bit(), 1024 );
	if ( tar_extract_all( tar_file, dst_dir ) != 0 ) {
		_ERRORLOG( QString( "tar_extract_all(): %1" ).arg( QString::fromLocal8Bit( strerror( errno ) ) ) );
		ret = false;
	}
	if ( tar_close( tar_file ) != 0 ) {
		_ERRORLOG( QString( "tar_close(): %1" ).arg( QString::fromLocal8Bit( strerror( errno ) ) ) );
		ret = false;
	}
	return ret;
#else // WIN32
	_ERRORLOG( "WIN32 NOT IMPLEMENTED" );
	return false;
#endif
#endif
}

};
Example #18
0
int mpk_package_packmpk(struct mpk_pkginfo *pkg, const char *srcdir,
    const char *outdir)
{
    TAR *tar;
    BZFILE *bz2;
    FILE *tbz2_file;
    int tar_fd;
    int bzerr;
    char src[PATH_MAX + 1];
    char dst[PATH_MAX + 1];
    char tar_fpath[PATH_MAX + 1];
    char tbz2_fpath[PATH_MAX + 1];
    unsigned char buffer[CHUNKSIZE];
    int size;
    struct mpk_file *file;

    /* create tar */

    sprintf(tar_fpath, "/tmp/%s_files.tar", pkg->name);
    if (access(tar_fpath, F_OK) == 0)
        if (unlink(tar_fpath) != 0)
            goto err0;

    if (tar_open(&tar, tar_fpath, NULL, O_WRONLY|O_CREAT, 0644, 0) != 0)
        goto err0;

    for (file = pkg->tool.lh_first; file; file = file->items.le_next) {
        sprintf(src, "%s/tool/%s", srcdir, file->name);
        sprintf(dst, "tool/%s", file->name);
        if (tar_append_tree(tar, src, dst) != 0)
            goto err2;
    }

    for (file = pkg->data.lh_first; file; file = file->items.le_next) {
        if (file->type == MPK_FILE_TYPE_R || file->type == MPK_FILE_TYPE_EXE
                || file->type == MPK_FILE_TYPE_W
                || file->type == MPK_FILE_TYPE_S) {
            sprintf(src, "%s/data/%s", srcdir, file->name);
            sprintf(dst, "data/%s", file->name);
            if (tar_append_tree(tar, src, dst) != 0)
                goto err2;
        }
    }

    sprintf(src, "%s/manifest.txt", srcdir);
    if (tar_append_file(tar, src, "manifest.txt") != 0)
        goto err2;

    tar_close(tar);


    /* compress using bz2 */

    int version_str_len = mpk_version_serializedsize(&pkg->version);
    char *version_str;
    if (!(version_str = malloc(version_str_len + 1)))
        goto err2;
    if (mpk_version_serialize(version_str, NULL, version_str_len, &pkg->version)
            != MPK_SUCCESS) {
        free(version_str);
        goto err2;
    }
    version_str[version_str_len] = 0;

    sprintf(tbz2_fpath, "%s/%s-%s.mpk", outdir, pkg->name, version_str);
    free(version_str);
    printf("path:%s\n", tbz2_fpath);

    if ((tar_fd = open(tar_fpath, O_RDONLY)) == -1)
        goto err1;

    if ((tbz2_file = fopen(tbz2_fpath, "wb")) == NULL)
        goto err3;
    bz2 = BZ2_bzWriteOpen(&bzerr, tbz2_file, 9, 0, 30);
    if (bzerr != BZ_OK)
        goto err4;

    while ((size = read(tar_fd, buffer, CHUNKSIZE)) > 0)
        BZ2_bzWrite(&bzerr, bz2, buffer, size);
    BZ2_bzWriteClose(&bzerr, bz2, 0, NULL, NULL);
    fclose(tbz2_file);
    close(tar_fd);
    if (bzerr != BZ_OK || size < 0)
        goto err1;

    if (unlink(tar_fpath) != 0)
        goto err0;

    return MPK_SUCCESS;

err4:
    fclose(tbz2_file);
err3:
    close(tar_fd);
    goto err1;
err2:
    tar_close(tar);
err1:
    unlink(tar_fpath);
err0:
    return MPK_FAILURE;
}
Example #19
0
int mpk_package_unpackmpk(const char *package_file, char *outdir)
{
    FILE *tbz2_file, *tar_file;
    const char *tar_fpath = "/tmp/mpk-temp.tar";
    BZFILE *bz2;
    int bzerr;
    unsigned char buf[CHUNKSIZE];
    size_t n;
    TAR *tar;

    if (!package_file || !outdir)
        return MPK_FAILURE;

    if (!(tar_file = fopen(tar_fpath, "w")))
        return MPK_FAILURE;

    if (!(tbz2_file = fopen(package_file, "r"))) {
        syslog(LOG_ERR, "could not open file: %s", package_file);
        fclose(tar_file);
        return MPK_FAILURE;
    }

    /* decompress bz2 */

    bz2 = BZ2_bzReadOpen(&bzerr, tbz2_file, 0, 0, NULL, 0);
    if (bzerr != BZ_OK) {
        fclose(tbz2_file);
        fclose(tar_file);
        return MPK_FAILURE;
    }
    while (1) {
        n = BZ2_bzRead(&bzerr, bz2, buf, CHUNKSIZE);
        if (bzerr != BZ_OK && bzerr != BZ_STREAM_END) {
            fclose(tar_file);
            unlink(tar_fpath);
            BZ2_bzReadClose(&bzerr, bz2);
            fclose(tbz2_file);
            return MPK_FAILURE;
        }

        if (fwrite(buf, 1, n, tar_file) != n) {
            fclose(tar_file);
            unlink(tar_fpath);
            BZ2_bzReadClose(&bzerr, bz2);
            fclose(tbz2_file);
            return MPK_FAILURE;
        }

        if (bzerr == BZ_STREAM_END)
            break;
    }

    BZ2_bzReadClose(&bzerr, bz2);
    fclose(tbz2_file);
    fclose(tar_file);

    /* create output directory */

    if (mkdir(outdir, 0700) != 0) {
        syslog(LOG_ERR, "mkdir failed: %s", strerror(errno));
        unlink(tar_fpath);
        return MPK_FAILURE;
    }

    /* unpack tar */

    if (tar_open(&tar, tar_fpath, NULL, O_RDONLY, 0644, 0) != 0) {
        rmdir(outdir);
        unlink(tar_fpath);
        return MPK_FAILURE;
    }

    if (tar_extract_all(tar, outdir) != 0) {
        syslog(LOG_ERR, "tar_extract_all() failed: %s", strerror(errno));
        tar_close(tar);
        rmdir(outdir);
        unlink(tar_fpath);
        return MPK_FAILURE;
    }
    tar_close(tar);
    if (unlink(tar_fpath) != 0)
        return MPK_FAILURE;

    return MPK_SUCCESS;
}
Example #20
0
static int create_and_upload_archive(
                const char *dump_dir_name,
                map_string_t *settings)
{
    int result = 1; /* error */

    pid_t child;
    TAR* tar = NULL;
    const char* errmsg = NULL;
    char* tempfile = NULL;

    struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
    if (!dd)
        xfunc_die(); /* error msg is already logged by dd_opendir */

    /* Gzipping e.g. 0.5gig coredump takes a while. Let client know what we are doing */
    log(_("Compressing data"));

//TODO:
//Encrypt = yes
//ArchiveType = .tar.bz2
//ExcludeFiles = foo,bar*,b*z
    const char* opt = getenv("Upload_URL");
    if (!opt)
        opt = get_map_string_item_or_empty(settings, "URL");
    char *url = opt[0] != '\0' ? xstrdup(opt) : ask_url(_("Please enter a URL (scp, ftp, etc.) where the problem data is to be exported:"));

    /* Create a child gzip which will compress the data */
    /* SELinux guys are not happy with /tmp, using /var/run/abrt */
    /* Reverted back to /tmp for ABRT2 */
    /* Changed again to /var/tmp because of Fedora feature tmp-on-tmpfs */
    tempfile = concat_path_basename(LARGE_DATA_TMP_DIR, dump_dir_name);
    tempfile = append_to_malloced_string(tempfile, ".tar.gz");

    int pipe_from_parent_to_child[2];
    xpipe(pipe_from_parent_to_child);
    child = vfork();
    if (child == 0)
    {
        /* child */
        close(pipe_from_parent_to_child[1]);
        xmove_fd(pipe_from_parent_to_child[0], 0);
        xmove_fd(xopen3(tempfile, O_WRONLY | O_CREAT | O_EXCL, 0600), 1);
        execlp("gzip", "gzip", NULL);
        perror_msg_and_die("Can't execute '%s'", "gzip");
    }
    close(pipe_from_parent_to_child[0]);

    /* If child died (say, in xopen), then parent might get SIGPIPE.
     * We want to properly unlock dd, therefore we must not die on SIGPIPE:
     */
    signal(SIGPIPE, SIG_IGN);

    /* Create tar writer object */
    if (tar_fdopen(&tar, pipe_from_parent_to_child[1], tempfile,
                /*fileops:(standard)*/ NULL, O_WRONLY | O_CREAT, 0644, TAR_GNU) != 0)
    {
        errmsg = "Can't create temporary file in "LARGE_DATA_TMP_DIR;
        goto ret;
    }

    /* Write data to the tarball */
    {
        string_vector_ptr_t exclude_from_report = get_global_always_excluded_elements();
        dd_init_next_file(dd);
        char *short_name, *full_name;
        while (dd_get_next_file(dd, &short_name, &full_name))
        {
            if (exclude_from_report && is_in_string_list(short_name, (const_string_vector_const_ptr_t)exclude_from_report))
                goto next;

            // dd_get_next_file guarantees that it's a REG:
            //struct stat stbuf;
            //if (stat(full_name, &stbuf) != 0)
            // || !S_ISREG(stbuf.st_mode)
            //) {
            //     goto next;
            //}
            if (tar_append_file(tar, full_name, short_name) != 0)
            {
                errmsg = "Can't create temporary file in "LARGE_DATA_TMP_DIR;
                free(short_name);
                free(full_name);
                goto ret;
            }
 next:
            free(short_name);
            free(full_name);
        }
    }
    dd_close(dd);
    dd = NULL;

    /* Close tar writer... */
    if (tar_append_eof(tar) != 0 || tar_close(tar) != 0)
    {
        errmsg = "Can't create temporary file in "LARGE_DATA_TMP_DIR;
        goto ret;
    }
    tar = NULL;
    /* ...and check that gzip child finished successfully */
    int status;
    safe_waitpid(child, &status, 0);
    child = -1;
    if (status != 0)
    {
        /* We assume the error was out-of-disk-space or out-of-quota */
        errmsg = "Can't create temporary file in "LARGE_DATA_TMP_DIR;
        goto ret;
    }

    /* Upload the tarball */
    /* Upload from /tmp to /tmp + deletion -> BAD, exclude this possibility */
    if (url && url[0] && strcmp(url, "file://"LARGE_DATA_TMP_DIR"/") != 0)
    {
        post_state_t *state = new_post_state(POST_WANT_ERROR_MSG);
        state->username = getenv("Upload_Username");
        char *password_inp = NULL;
        if (state->username != NULL && state->username[0] != '\0')
        {
            /* Load Password only if Username is configured, it doesn't make */
            /* much sense to load Password without Username. */
            state->password = getenv("Upload_Password");
            if (state->password == NULL)
            {
                /* Be permissive and nice, ask only once and don't check */
                /* the result. User can dismiss this prompt but the upload */
                /* may work somehow??? */
                char *msg = xasprintf(_("Please enter password for uploading:"), state->username);
                state->password = password_inp = ask_password(msg);
                free(msg);
            }
        }

        char *remote_name = upload_file_ext(state, url, tempfile, UPLOAD_FILE_HANDLE_ACCESS_DENIALS);

        result = (remote_name == NULL); /* error if NULL */
        free(remote_name);
        free(password_inp);
        free_post_state(state);
        /* cleanup code will delete tempfile */
    }
    else
    {
        result = 0; /* success */
        log(_("Archive is created: '%s'"), tempfile);
        free(tempfile);
        tempfile = NULL;
    }

 ret:
    free(url);
    dd_close(dd);
    if (tar)
        tar_close(tar);
    /* close(pipe_from_parent_to_child[1]); - tar_close() does it itself */
    if (child > 0)
        safe_waitpid(child, NULL, 0);
    if (tempfile)
    {
        unlink(tempfile);
        free(tempfile);
    }
    if (errmsg)
        error_msg_and_die("%s", errmsg);

    return result;
}
Example #21
0
int					/* O - 0 = success, 1 = fail */
make_deb(const char     *prodname,	/* I - Product short name */
         const char     *directory,	/* I - Directory for distribution files */
         const char     *platname,	/* I - Platform name */
         dist_t         *dist,		/* I - Distribution information */
	 struct utsname *platform)	/* I - Platform information */
{
  int		i;			/* Looping var */
  tarf_t	*tarfile;		/* Distribution tar file */
  char		name[1024],		/* Full product name */
		filename[1024];		/* File to archive */


  if (make_subpackage(prodname, directory, platname, dist, platform, NULL))
    return (1);

  for (i = 0; i < dist->num_subpackages; i ++)
    if (make_subpackage(prodname, directory, platname, dist, platform,
                        dist->subpackages[i]))
      return (1);

 /*
  * Build a compressed tar file to hold all of the subpackages...
  */

  if (dist->num_subpackages)
  {
   /*
    * Figure out the full name of the distribution...
    */

    if (dist->release[0])
      snprintf(name, sizeof(name), "%s-%s-%s", prodname, dist->version,
               dist->release);
    else
      snprintf(name, sizeof(name), "%s-%s", prodname, dist->version);

    if (platname[0])
    {
      strlcat(name, "-", sizeof(name));
      strlcat(name, platname, sizeof(name));
    }

   /*
    * Create a compressed tar file...
    */

    snprintf(filename, sizeof(filename), "%s/%s.deb.tgz", directory, name);

    if ((tarfile = tar_open(filename, 1)) == NULL)
      return (1);

   /*
    * Archive the main package and subpackages...
    */

    if (tar_package(tarfile, "deb", prodname, directory, platname, dist, NULL))
    {
      tar_close(tarfile);
      return (1);
    }

    for (i = 0; i < dist->num_subpackages; i ++)
    {
      if (tar_package(tarfile, "deb", prodname, directory, platname, dist,
                      dist->subpackages[i]))
      {
	tar_close(tarfile);
	return (1);
      }
    }
    
    tar_close(tarfile);
  }

 /*
  * Remove temporary files...
  */

  if (!KeepFiles && dist->num_subpackages)
  {
    if (Verbosity)
      puts("Removing temporary distribution files...");

   /*
    * Remove .deb files since they are now in a .tgz file...
    */

    unlink_package("deb", prodname, directory, platname, dist, NULL);

    for (i = 0; i < dist->num_subpackages; i ++)
      unlink_package("deb", prodname, directory, platname, dist,
                     dist->subpackages[i]);
  }

  return (0);
}
Example #22
0
int					/* O - 0 = success, 1 = fail */
make_rpm(int            format,		/* I - Subformat */
         const char     *prodname,	/* I - Product short name */
         const char     *directory,	/* I - Directory for distribution files */
         const char     *platname,	/* I - Platform name */
         dist_t         *dist,		/* I - Distribution information */
	 struct utsname *platform,	/* I - Platform information */
         const char     *setup,		/* I - Setup GUI image */
         const char     *types)		/* I - Setup GUI install types */
{
  int		i;			/* Looping var */
  FILE		*fp;			/* Spec file */
  tarf_t	*tarfile;		/* Distribution tar file */
  char		specname[1024];		/* Spec filename */
  char		name[1024],		/* Product filename */
		filename[1024];		/* Destination filename */
  file_t	*file;			/* Current distribution file */
  char		absdir[1024];		/* Absolute directory */
  char		rpmdir[1024];		/* RPMDIR env var */
  char		release[256];		/* Release: number */
  const char	*build_option;		/* Additional rpmbuild option */


  if (Verbosity)
    puts("Creating RPM distribution...");

  if (directory[0] != '/')
  {
    char	current[1024];		/* Current directory */


    getcwd(current, sizeof(current));

    snprintf(absdir, sizeof(absdir), "%s/%s", current, directory);
  }
  else
    strlcpy(absdir, directory, sizeof(absdir));

 /*
  * Write the spec file for RPM...
  */

  if (Verbosity)
    puts("Creating spec file...");

  snprintf(specname, sizeof(specname), "%s/%s.spec", directory, prodname);

  if ((fp = fopen(specname, "w")) == NULL)
  {
    fprintf(stderr, "epm: Unable to create spec file \"%s\" - %s\n", specname,
            strerror(errno));
    return (1);
  }

  if (dist->release[0])
    strlcpy(release, dist->release, sizeof(release));
  else
    strlcpy(release, "0", sizeof(release));

  fprintf(fp, "Name: %s\n", prodname);
  fprintf(fp, "Version: %s\n", dist->version);
  if (dist->epoch)
    fprintf(fp, "Epoch: %d\n", dist->epoch);
  fprintf(fp, "Release: %s\n", release);
  fprintf(fp, "License: %s\n", dist->copyright);
  fprintf(fp, "Packager: %s\n", dist->packager);
  fprintf(fp, "Vendor: %s\n", dist->vendor);

  if (format == PACKAGE_LSB || format == PACKAGE_LSB_SIGNED)
    fputs("Requires: lsb >= 3.0\n", fp);

 /*
  * Tell RPM to put the distributions in the output directory...
  */

#ifdef EPM_RPMTOPDIR
  fprintf(fp, "%%define _topdir %s\n", absdir);
  strcpy(rpmdir, absdir);
#else
  if (getenv("RPMDIR"))
    strlcpy(rpmdir, getenv("RPMDIR"), sizeof(rpmdir));
  else if (!access("/usr/src/redhat", 0))
    strcpy(rpmdir, "/usr/src/redhat");
  else if (!access("/usr/src/Mandrake", 0))
    strcpy(rpmdir, "/usr/src/Mandrake");
  else
    strcpy(rpmdir, "/usr/src/RPM");
#endif /* EPM_RPMTOPDIR */

  snprintf(filename, sizeof(filename), "%s/RPMS", directory);

  make_directory(filename, 0777, getuid(), getgid());

  snprintf(filename, sizeof(filename), "%s/rpms", directory);
  symlink("RPMS", filename);

  if (!strcmp(platform->machine, "intel"))
    snprintf(filename, sizeof(filename), "%s/RPMS/i386", directory);
  else if (!strcmp(platform->machine, "ppc"))
    snprintf(filename, sizeof(filename), "%s/RPMS/powerpc", directory);
  else
    snprintf(filename, sizeof(filename), "%s/RPMS/%s", directory,
             platform->machine);

  make_directory(filename, 0777, getuid(), getgid());

 /*
  * Now list all of the subpackages...
  */

  write_spec(format, prodname, dist, fp, NULL);
  for (i = 0; i < dist->num_subpackages; i ++)
    write_spec(format, prodname, dist, fp, dist->subpackages[i]);

 /*
  * Close the spec file...
  */

  fclose(fp);

 /*
  * Copy the files over...
  */

  if (Verbosity)
    puts("Copying temporary distribution files...");

  for (i = dist->num_files, file = dist->files; i > 0; i --, file ++)
  {
   /*
    * Copy the file or make the directory or make the symlink as needed...
    */

    switch (tolower(file->type))
    {
      case 'c' :
      case 'f' :
          snprintf(filename, sizeof(filename), "%s/buildroot%s", directory, file->dst);

	  if (Verbosity > 1)
	    printf("%s -> %s...\n", file->src, filename);

	  if (copy_file(filename, file->src, 0, -1, -1))
	    return (1);
          break;
      case 'i' :
          if (format == PACKAGE_LSB || format == PACKAGE_LSB_SIGNED)
	    snprintf(filename, sizeof(filename), "%s/buildroot/etc/init.d/%s",
		     directory, file->dst);
          else
	    snprintf(filename, sizeof(filename), "%s/buildroot%s/init.d/%s",
		     directory, SoftwareDir, file->dst);

	  if (Verbosity > 1)
	    printf("%s -> %s...\n", file->src, filename);

	  if (copy_file(filename, file->src, 0, -1, -1))
	    return (1);
          break;
      case 'd' :
          snprintf(filename, sizeof(filename), "%s/buildroot%s", directory, file->dst);

	  if (Verbosity > 1)
	    printf("Directory %s...\n", filename);

          make_directory(filename, 0755, -1, -1);
          break;
      case 'l' :
          snprintf(filename, sizeof(filename), "%s/buildroot%s", directory, file->dst);

	  if (Verbosity > 1)
	    printf("%s -> %s...\n", file->src, filename);

          make_link(filename, file->src);
          break;
    }
  }

 /*
  * Build the distribution from the spec file...
  */

  if (Verbosity)
    puts("Building RPM binary distribution...");

  if (format == PACKAGE_LSB_SIGNED || format == PACKAGE_RPM_SIGNED)
    build_option = "-signed ";
  else
    build_option = "";

  if (!strcmp(platform->machine, "intel"))
  {
    if (run_command(NULL, EPM_RPMBUILD " -bb --buildroot \"%s/buildroot\" "
                          EPM_RPMARCH "i386 %s%s", absdir, build_option,
			  specname))
      return (1);
  }
  else if (!strcmp(platform->machine, "ppc"))
  {
    if (run_command(NULL, EPM_RPMBUILD " -bb --buildroot \"%s/buildroot\" "
                          EPM_RPMARCH "powerpc %s%s", absdir, build_option,
			  specname))
      return (1);
  }
  else if (run_command(NULL, EPM_RPMBUILD " -bb --buildroot \"%s/buildroot\" "
                       EPM_RPMARCH "%s %s%s", absdir, platform->machine,
		       build_option, specname))
    return (1);

 /*
  * Move the RPMs to the local directory and rename the RPMs using the
  * product name specified by the user...
  */

  move_rpms(prodname, directory, platname, dist, platform, rpmdir, NULL,
            release);

  for (i = 0; i < dist->num_subpackages; i ++)
    move_rpms(prodname, directory, platname, dist, platform, rpmdir,
              dist->subpackages[i], release);

 /*
  * Build a compressed tar file to hold all of the subpackages...
  */

  if (dist->num_subpackages || setup)
  {
   /*
    * Figure out the full name of the distribution...
    */

    if (dist->release[0])
      snprintf(name, sizeof(name), "%s-%s-%s", prodname, dist->version,
               dist->release);
    else
      snprintf(name, sizeof(name), "%s-%s", prodname, dist->version);

    if (platname[0])
    {
      strlcat(name, "-", sizeof(name));
      strlcat(name, platname, sizeof(name));
    }

   /*
    * Create a compressed tar file...
    */

    snprintf(filename, sizeof(filename), "%s/%s.rpm.tgz", directory, name);

    if ((tarfile = tar_open(filename, 1)) == NULL)
      return (1);

   /*
    * Archive the setup and uninst GUIs and their data files...
    */

    if (setup)
    {
     /*
      * Include the ESP Software Installation Wizard (setup)...
      */

      const char	*setup_img;	/* Setup image name */
      struct stat	srcstat;	/* File information */


      if (stat(SetupProgram, &srcstat))
      {
	fprintf(stderr, "epm: Unable to stat GUI setup program %s - %s\n",
		SetupProgram, strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (tar_header(tarfile, TAR_NORMAL, 0555, srcstat.st_size,
	             srcstat.st_mtime, "root", "root", "setup", NULL) < 0)
      {
	fprintf(stderr, "epm: Error writing file header - %s\n",
		strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (tar_file(tarfile, SetupProgram) < 0)
      {
	fprintf(stderr, "epm: Error writing file data for setup -\n    %s\n",
		strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (Verbosity)
	printf("    %7.0fk setup\n", (srcstat.st_size + 1023) / 1024.0);

     /*
      * And the image file...
      */

      stat(setup, &srcstat);

      if (strlen(setup) > 4 && !strcmp(setup + strlen(setup) - 4, ".gif"))
	setup_img = "setup.gif";
      else
	setup_img = "setup.xpm";

      if (tar_header(tarfile, TAR_NORMAL, 0444, srcstat.st_size,
	             srcstat.st_mtime, "root", "root", setup_img, NULL) < 0)
      {
	fprintf(stderr, "epm: Error writing file header - %s\n",
		strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (tar_file(tarfile, setup) < 0)
      {
	fprintf(stderr, "epm: Error writing file data for %s -\n    %s\n",
		setup_img, strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (Verbosity)
	printf("    %7.0fk %s\n", (srcstat.st_size + 1023) / 1024.0, setup_img);

     /*
      * And the types file...
      */

      if (types)
      {
	stat(types, &srcstat);

	if (tar_header(tarfile, TAR_NORMAL, 0444, srcstat.st_size,
		       srcstat.st_mtime, "root", "root", types, NULL) < 0)
	{
	  fprintf(stderr, "epm: Error writing file header - %s\n",
		  strerror(errno));
          tar_close(tarfile);
	  return (-1);
	}

	if (tar_file(tarfile, types) < 0)
	{
	  fprintf(stderr, "epm: Error writing file data for setup.types -\n    %s\n",
		  strerror(errno));
          tar_close(tarfile);
	  return (-1);
	}

	if (Verbosity)
          printf("    %7.0fk setup.types\n", (srcstat.st_size + 1023) / 1024.0);
      }

     /*
      * Include the ESP Software Removal Wizard (uninst)...
      */

      if (stat(UninstProgram, &srcstat))
      {
	fprintf(stderr, "epm: Unable to stat GUI uninstall program %s - %s\n",
		UninstProgram, strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (tar_header(tarfile, TAR_NORMAL, 0555, srcstat.st_size,
	             srcstat.st_mtime, "root", "root", "uninst", NULL) < 0)
      {
	fprintf(stderr, "epm: Error writing file header - %s\n",
		strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (tar_file(tarfile, UninstProgram) < 0)
      {
	fprintf(stderr, "epm: Error writing file data for uninst -\n    %s\n",
		strerror(errno));
	tar_close(tarfile);
	return (-1);
      }

      if (Verbosity)
	printf("    %7.0fk uninst\n", (srcstat.st_size + 1023) / 1024.0);
    }

   /*
    * Archive the main package and subpackages...
    */

    if (tar_package(tarfile, "rpm", prodname, directory, platname, dist, NULL))
    {
      tar_close(tarfile);
      return (1);
    }

    for (i = 0; i < dist->num_subpackages; i ++)
    {
      if (tar_package(tarfile, "rpm", prodname, directory, platname, dist,
                      dist->subpackages[i]))
      {
	tar_close(tarfile);
	return (1);
      }
    }
    
    tar_close(tarfile);
  }

 /*
  * Remove temporary files...
  */

  if (!KeepFiles)
  {
    if (Verbosity)
      puts("Removing temporary distribution files...");

    snprintf(filename, sizeof(filename), "%s/RPMS", directory);
    unlink_directory(filename);

    snprintf(filename, sizeof(filename), "%s/rpms", directory);
    unlink(filename);

    snprintf(filename, sizeof(filename), "%s/buildroot", directory);
    unlink_directory(filename);

    unlink(specname);

    if (dist->num_subpackages)
    {
     /*
      * Remove .rpm files since they are now in a .tgz file...
      */

      unlink_package("rpm", prodname, directory, platname, dist, NULL);

      for (i = 0; i < dist->num_subpackages; i ++)
	unlink_package("rpm", prodname, directory, platname, dist,
                       dist->subpackages[i]);
    }
  }

  return (0);
}
Example #23
0
ResponseCode UpdateRepoTagOfTarball(std::string pathTarball, std::string repo, std::string tag, std::string &idImage) {
  TAR *tar = NULL;
  int ret = 0;
  int th_found = 0;
  int exitcode = 0;
//  char tmp_filepath[] = P_tmpdir "/libtar-tmpfile-XXXXXX";
  //gen path to upload image
  char* tmp_imagepath = tempnam (FileUtils::GetPathDir(pathTarball).c_str(), "imageDirTmp_");
  std::string pathTmpDir = tmp_imagepath;
  free(tmp_imagepath);
  std::cout << "path tmp dir: " << pathTmpDir << std::endl;

  int tmp_fd = -1;

  ret = tar_open(&tar, (char*)pathTarball.c_str(), NULL, O_RDONLY, 0, 0);
  if (ret != 0) {
	fprintf(stdout, "Fail to open file: %s\n", pathTarball.c_str());
//	return FILE_ACTION_ERROR;
	exitcode = 2;
  }
	if (exitcode == 0) {
		if (tar_extract_all(tar, (char*)pathTmpDir.c_str()) != 0) {
            fprintf(stderr, "Fail to extract file: %s\n", pathTarball.c_str());
			exitcode = 2;
		}
	}

	if (exitcode == 0) {
		ret = tar_close(tar);
		if (ret != 0) {
			perror("Failed to close tar file.");
			exitcode = 2;
		}
		tar = NULL;
	}

  //Modify repository file
  if (exitcode == 0) {
	char buf[BUFSIZ];
	ssize_t n_buf = 0;
	FILE *tmpfile = NULL;

	std::ifstream in((pathTmpDir + "/" + REPOSITORIES_FILE).c_str(), std::ios::binary);
	std::string info((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());

	JSONNode n;
	try
	{
		n = libjson::parse(info);
	} catch(const std::invalid_argument& e) {
		std::cerr << "Invalid argument: " << e.what() << '\n';
//		return FILE_ACTION_ERROR;
		exitcode = 1;
	}
	if(exitcode == 0){
		JSONNode::const_iterator i = n.begin();
		//if (i != n.end() && i -> name() == TAG_SERVICE_STR && i -> type() != JSON_ARRAY && i -> type() != JSON_NODE)
		if (i != n.end() && i -> type() == JSON_NODE){
			JSONNode tag_id_node = i->as_node();
			i = tag_id_node.begin();
			if (i != n.end() && i -> type() != JSON_ARRAY && i -> type() != JSON_NODE){
				idImage = i->as_string();
			}else{
				std::cout << "Tarball format error.\n";
		//		return FILE_ACTION_ERROR;
				exitcode = 1;
			}
		}
	}else{
		std::cout << "Tarball format error.\n";
//			return FILE_ACTION_ERROR;
		exitcode = 1;
		}
	}

	if(exitcode == 0){
		JSONNode newRepoNode(JSON_NODE);
		newRepoNode.set_name(repo);
		newRepoNode.push_back(JSONNode(tag, idImage));

		JSONNode newNode;
		newNode.push_back(newRepoNode);
		std::string content = newNode.write();

		FILE * pFile;

		if (exitcode == 0) {
			pFile = fopen ((pathTmpDir + "/" + REPOSITORIES_FILE).c_str() , "w");
			if (pFile == NULL) {
			   printf("Error opening file %s\n", (pathTmpDir + "/" + REPOSITORIES_FILE).c_str());
		//	   return FILE_ACTION_ERROR;
			   exitcode = 1;
			}
		}

		if (exitcode == 0) {
			fwrite (content.c_str() , sizeof(char), content.size(), pFile);
			fclose (pFile);
			printf("content tmp file: %s\n", content.c_str());
		}
	}

	if (exitcode == 0) {
		remove (pathTarball.c_str());
		ret = tar_open(&tar, (char*)pathTarball.c_str(), NULL, O_WRONLY | O_CREAT, 0600, 0);
		if (ret != 0) {
		  fprintf(stderr, "Fail to open file: %s\n", pathTarball.c_str());
		//	  return FILE_ACTION_ERROR;
		  exitcode = 2;
		}

		if (exitcode == 0) {
			if (tar_append_tree(tar, (char*)pathTmpDir.c_str(), "") != 0) {
			  fprintf(stderr, "Fail to compress file: %s\n", pathTarball.c_str());
		//		  return FILE_ACTION_ERROR;
			  exitcode = 2;
			}
		}

		if (exitcode == 0) {
			ret = tar_close(tar);
			if (ret != 0) {
				perror("Failed to close tar file.");
				exitcode = 2;
			} else {
				tar = NULL;
			}
		}
	}
	std::cout << "delete_folder_tree: " << pathTmpDir.c_str() << std::endl;
	if (FileUtils::delete_folder_tree(pathTmpDir.c_str())) {
		fprintf(stderr, "Fail to delete temp dir: %s\n", pathTmpDir.c_str());
	}

	if (exitcode == 0) {
		return FILE_ACTION_SUCCESS;
	} else if (exitcode == 1) {
		return FILE_ACTION_ERROR;
	} else {
		return DATA_ERROR;
	}
}