Exemplo n.º 1
0
int archinfo_show_fshead(cdico *dicofshead, int fsid)
{
    char magic[FSA_SIZEOF_MAGIC+1];
    char fsbuf[FSA_MAX_FSNAMELEN];
    u64 temp64;
    u64 fsbytestotal;
    u64 fsbytesused;
    char buffer[256];
    char fslabel[256];
    char fsuuid[256];
    char fsorigdev[256];
    
    // init
    memset(magic, 0, sizeof(magic));
    
    if (!dicofshead)
    {   errprintf("dicofshead is null\n");
        return -1;
    }
    
    if (dico_get_data(dicofshead, 0, FSYSHEADKEY_FILESYSTEM, fsbuf, sizeof(fsbuf), NULL)!=0)
    {   errprintf("cannot find FSYSHEADKEY_FILESYSTEM in filesystem-header\n");
        return -1;
    }

    if (dico_get_u64(dicofshead, 0, FSYSHEADKEY_BYTESTOTAL, &fsbytestotal)!=0)
    {   errprintf("cannot find FSYSHEADKEY_BYTESTOTAL in filesystem-header\n");
        return -1;
    }
    
    if (dico_get_u64(dicofshead, 0, FSYSHEADKEY_BYTESUSED, &fsbytesused)!=0)
    {   errprintf("cannot find FSYSHEADKEY_BYTESUSED in filesystem-header\n");
        return -1;
    }
    
    if (dico_get_string(dicofshead, 0, FSYSHEADKEY_FSLABEL, fslabel, sizeof(fslabel))<0)
        snprintf(fslabel, sizeof(fslabel), "<none>");
    
    if (dico_get_string(dicofshead, 0, FSYSHEADKEY_ORIGDEV, fsorigdev, sizeof(fsorigdev))<0)
        snprintf(fsorigdev, sizeof(fsorigdev), "<unknown>");
    
    // filesystem uuid: maybe an ntfs uuid or an unix uuid
    snprintf(fsuuid, sizeof(fsuuid), "<none>");
    if (dico_get_u64(dicofshead, 0, FSYSHEADKEY_NTFSUUID, &temp64)==0)
        snprintf(fsuuid, sizeof(fsuuid), "%016llX", (long long unsigned int)temp64);
    else if (dico_get_string(dicofshead, 0, FSYSHEADKEY_FSUUID, buffer, sizeof(buffer))==0 && strlen(buffer)==36)
        snprintf(fsuuid, sizeof(fsuuid), "%s", buffer);
    
    msgprintf(MSG_FORCE, "===================== filesystem information ====================\n");
    msgprintf(MSG_FORCE, "Filesystem id in archive: \t%ld\n", (long)fsid);
    msgprintf(MSG_FORCE, "Filesystem format: \t\t%s\n", fsbuf);
    msgprintf(MSG_FORCE, "Filesystem label: \t\t%s\n", fslabel);
    msgprintf(MSG_FORCE, "Filesystem uuid: \t\t%s\n", fsuuid);
    msgprintf(MSG_FORCE, "Original device: \t\t%s\n", fsorigdev);
    msgprintf(MSG_FORCE, "Original filesystem size: \t%s (%lld bytes)\n", format_size(fsbytestotal, buffer, sizeof(buffer), 'h'), (long long)fsbytestotal);
    msgprintf(MSG_FORCE, "Space used in filesystem: \t%s (%lld bytes)\n", format_size(fsbytesused, buffer, sizeof(buffer), 'h'), (long long)fsbytesused);
    msgprintf(MSG_FORCE, "\n");
    
    return 0;
}
Exemplo n.º 2
0
QString PacketList::allPacketComments()
{
    guint32 framenum;
    frame_data *fdata;
    QString buf_str;

    if (!cap_file_) return buf_str;

    for (framenum = 1; framenum <= cap_file_->count ; framenum++) {
        fdata = frame_data_sequence_find(cap_file_->frames, framenum);

        char *pkt_comment = cf_get_comment(cap_file_, fdata);

        if (pkt_comment) {
            buf_str.append(QString(tr("Frame %1: %2 \n\n")).arg(framenum).arg(pkt_comment));
            g_free(pkt_comment);
        }
        if (buf_str.length() > max_comments_to_fetch_) {
            buf_str.append(QString(tr("[ Comment text exceeds %1. Stopping. ]"))
                           .arg(format_size(max_comments_to_fetch_, format_size_unit_bytes|format_size_prefix_si)));
            return buf_str;
        }
    }
    return buf_str;
}
Exemplo n.º 3
0
static void
display_size(size_t v)
{
	char *s = format_size(v);
	printf("%15s", s);
	free(s);
}
Exemplo n.º 4
0
static gboolean
check_install_space (RCYouTransaction *transaction, GError **err)
{
    gsize block_size;
    gsize avail_blocks;
    struct statvfs vfs_info;

    if (!transaction->total_install_size)
        return TRUE;

    if (statvfs("/", &vfs_info)) {
        g_set_error (err, RC_YOU_TRANSACTION_ERROR_DOMAIN,
                     RC_YOU_TRANSACTION_ERROR_DISKSPACE,
                     "Unable to get disk space info for /");
        return FALSE;
    }

    block_size = vfs_info.f_frsize;
    avail_blocks = vfs_info.f_bavail;

    if (transaction->total_install_size / block_size + 1 > avail_blocks) {
        g_set_error (err, RC_YOU_TRANSACTION_ERROR_DOMAIN,
                     RC_YOU_TRANSACTION_ERROR_DISKSPACE,
                     "Insufficient disk space: %s needed in /",
                     format_size (transaction->total_install_size));

        return FALSE;
    }

    return TRUE;
} /*  check_install_space */
Exemplo n.º 5
0
void FileSetDialog::addFile(fileset_entry *entry) {
    QString created;
    QString modified;
    QString dir_name;
    QString elided_dir_name;
    QTreeWidgetItem *entry_item;
    gchar *size_str;

    if (!entry) {
        setWindowTitle(wsApp->windowTitleString(tr("No files in Set")));
        fs_ui_->directoryLabel->setText(tr("No capture loaded"));
        fs_ui_->directoryLabel->setEnabled(false);
        return;
    }

    created = nameToDate(entry->name);
    if(created.length() < 1) {
        /* if this file doesn't follow the file set pattern, */
        /* use the creation time of that file */
        /* http://en.wikipedia.org/wiki/ISO_8601 */
        created = QDateTime::fromTime_t(entry->ctime).toLocalTime().toString("yyyy-MM-dd HH:mm:ss");
    }

    modified = QDateTime::fromTime_t(entry->mtime).toLocalTime().toString("yyyy-MM-dd HH:mm:ss");

    size_str = format_size(entry->size, format_size_unit_bytes|format_size_prefix_si);

    entry_item = new QTreeWidgetItem(fs_ui_->fileSetTree);
    entry_item->setToolTip(0, QString(tr("Open this capture file")));
    entry_item->setData(0, Qt::UserRole, qVariantFromValue(entry));

    entry_item->setText(0, entry->name);
    entry_item->setText(1, created);
    entry_item->setText(2, modified);
    entry_item->setText(3, size_str);
    g_free(size_str);
    // Not perfect but better than nothing.
    entry_item->setTextAlignment(3, Qt::AlignRight);

    setWindowTitle(wsApp->windowTitleString(tr("%1 File%2 in Set")
                                            .arg(fs_ui_->fileSetTree->topLevelItemCount())
                                            .arg(plurality(fs_ui_->fileSetTree->topLevelItemCount(), "", "s"))));

    dir_name = fileset_get_dirname();
    fs_ui_->directoryLabel->setText(dir_name);
    fs_ui_->directoryLabel->setUrl(QUrl::fromLocalFile(dir_name).toString());
    fs_ui_->directoryLabel->setEnabled(true);

    if(entry->current) {
        fs_ui_->fileSetTree->setCurrentItem(entry_item);
    }

    if (close_button_)
        close_button_->setEnabled(true);

    fs_ui_->fileSetTree->addTopLevelItem(entry_item);
    for (int i = 0; i < fs_ui_->fileSetTree->columnCount(); i++)
        fs_ui_->fileSetTree->resizeColumnToContents(i);
    fs_ui_->fileSetTree->setFocus();
}
Exemplo n.º 6
0
void MainWindow::refreshDone()
{
        enableGUI();

        ui->comboDrive->clear();
        for (int i = 0;i < refreshThread->devices.size();i++)
        {
                Device dev = refreshThread->devices.at(i);
                
                //Device must be at least 512Mb, and don't show devices with size greater than 10Gb
                //It prevent to list computer's own disk drive and mess up with the system
                if ((dev.pdevice->length * dev.pdevice->sector_size) > 10 * GIBIBYTE)
                        continue;
                if ((dev.pdevice->length * dev.pdevice->sector_size) < 475 * MEBIBYTE)
                        continue;

                QString it = dev.pdevice->path;
                it += " - " + dev.model + " (" + format_size(dev.pdevice->length, dev.pdevice->sector_size) + ")";
                ui->comboDrive->addItem(it, QVariant(QString(dev.pdevice->path)));
        }

        if (refreshThread)
        {
                delete refreshThread;
                refreshThread = NULL;
        }
}
Exemplo n.º 7
0
// Sum and display the total stats for all cache dirs.
void
stats_summary(void)
{
	assert(conf);

	struct counters *counters = counters_init(STATS_END);
	time_t last_updated;
	stats_collect(counters, &last_updated);

	printf("cache directory                     %s\n", conf->cache_dir);
	printf("primary config                      %s\n",
	       primary_config_path ? primary_config_path : "");
	printf("secondary config      (readonly)    %s\n",
	       secondary_config_path ? secondary_config_path : "");
	if (last_updated > 0) {
		struct tm *tm = localtime(&last_updated);
		char timestamp[100];
		strftime(timestamp, sizeof(timestamp), "%c", tm);
		printf("stats updated                       %s\n", timestamp);
	}

	// ...and display them.
	for (int i = 0; stats_info[i].message; i++) {
		enum stats stat = stats_info[i].stat;

		if (stats_info[i].flags & FLAG_NEVER) {
			continue;
		}
		if (counters->data[stat] == 0 && !(stats_info[i].flags & FLAG_ALWAYS)) {
			continue;
		}

		char *value;
		if (stats_info[i].format_fn) {
			value = stats_info[i].format_fn(counters->data[stat]);
		} else {
			value = format("%8u", counters->data[stat]);
		}
		if (value) {
			printf("%-31s %s\n", stats_info[i].message, value);
			free(value);
		}

		if (stat == STATS_TOCACHE) {
			double percent = stats_hit_rate(counters);
			printf("cache hit rate                    %6.2f %%\n", percent);
		}
	}

	if (conf->max_files != 0) {
		printf("max files                       %8u\n", conf->max_files);
	}
	if (conf->max_size != 0) {
		char *value = format_size(conf->max_size);
		printf("max cache size                  %s\n", value);
		free(value);
	}

	counters_free(counters);
}
Exemplo n.º 8
0
gchar *mount_get_fs_size(const gchar *dir)
{
  int ok=FALSE;

#if defined(HAVE_STATVFS)
    struct statvfs buf;
#elif defined(HAVE_STATFS)
    struct statfs buf;
#endif
    unsigned long long total, used, avail;
    gdouble fused;
    gchar *str;
    gchar *tmp1, *tmp2;

#if defined(HAVE_STATVFS)
    ok=statvfs(dir, &buf)==0;
#elif defined(HAVE_STATFS)
    ok=statfs(dir, &buf)==0;
#endif
    if(!ok)
	    return NULL;

#if defined(HAVE_STATVFS)
    total=buf.f_frsize*(unsigned long long) buf.f_blocks;
    used=buf.f_frsize*(unsigned long long) (buf.f_blocks-buf.f_bfree);
    avail=buf.f_frsize*(unsigned long long) buf.f_bavail;
#elif defined(HAVE_STATFS)
    total=buf.f_bsize*(unsigned long long) buf.f_blocks;
    used=buf.f_bsize*(unsigned long long) (buf.f_blocks-buf.f_bfree);
    avail=buf.f_bsize*(unsigned long long) buf.f_bavail;
#endif
    if(total>0)
	    fused=100.*(total-used)/((gdouble) total);
    else
	    fused=0.0;

    tmp1=g_strdup(format_size(total));
    tmp2=g_strdup(format_size(used));
    str=g_strdup_printf(_("%s total, %s used, %s free (%.1f %%)"),
			tmp1, tmp2, format_size(avail), fused);

    g_free(tmp1);
    g_free(tmp2);

    return str;
}
Exemplo n.º 9
0
static void
print_stats(rcid_type_t stat_type)
{
	col_t *col;
	char size[6];
	char limit[6];
	char rss[6];
	char nproc[6];
	char paged_att[6];
	char paged_eff[6];
	char paged_att_avg[6];
	char paged_eff_avg[6];
	static int count = 0;

	/*
	 * Print a header once every 20 times if we're only displaying reports
	 * for one collection (10 times if -g is used).  Print a header every
	 * interval otherwise.
	 */
	if (count == 0 || ncol != 1)
		(void) printf("%6s %-15s %5s %5s %5s %5s %5s %5s %5s %5s\n",
		    "id", (stat_type == RCIDT_PROJECT ?  "project" : "zone"),
		    "nproc", "vm", "rss", "cap",
		    "at", "avgat", "pg", "avgpg");
	if (++count >= 20 || (count >= 10 && global != 0) || ncol != 1)
		count = 0;

	for (col = col_head; col != NULL; col = col->col_next) {
		if (col->col_id.rcid_type != stat_type)
			continue;

		if (col->col_paged_att == 0)
			(void) strlcpy(nproc, "-", sizeof (nproc));
		else
			(void) snprintf(nproc, sizeof (nproc), "%lld",
			    col->col_nproc);
		format_size(size, col->col_vmsize, 6);
		format_size(rss, col->col_rsssize, 6);
		format_size(limit, col->col_rsslimit, 6);
		format_size(paged_att, col->col_paged_att, 6);
		format_size(paged_eff, col->col_paged_eff, 6);
		format_size(paged_att_avg, col->col_paged_att_avg, 6);
		format_size(paged_eff_avg, col->col_paged_eff_avg, 6);
		(void) printf("%6lld %-15s %5s %5s %5s %5s %5s %5s %5s %5s\n",
		    col->col_id.rcid_val, col->col_name,
		    nproc,
		    size, rss, limit,
		    paged_att, paged_att_avg,
		    paged_eff, paged_eff_avg);
	}
	if (global)
		(void) printf(gettext("physical memory utilization: %3u%%   "
		    "cap enforcement threshold: %3u%%\n"), hdr.rs_pressure_cur,
		    hdr.rs_pressure_cap);
}
Exemplo n.º 10
0
Texture* load_uncompressed_pvr_from_memory(
	const void* data, size_t num_bytes,
	TexParams params, std::string debug_name)
{
	PvrHeader* header = (PvrHeader*)data;
	CHECK_F(strncmp(header->pvr_tag, "PVR!", 4) == 0, "Not a .pvr file");

	uint32_t flags = header->flags;
	uint32_t format_flag = flags & 0xFF;

	const uint8_t* data_start = (const uint8_t*)data + sizeof(PvrHeader);

	ImageFormat format = ImageFormat::BGRA32;
	if (format_flag == kA8) {
		format = ImageFormat::Alpha8;
	} else {
		CHECK_F(format_flag == kBGRA8888, "PVR: kBGRA8888 (%x) expected, got %x", kBGRA8888, format_flag);
	}

	Size size{header->width, header->height};

	CHECK_GT_F(header->mipmap_count, 0);

	if (params.filter == TexFilter::Mipmapped && !supports_mipmaps_for(size)) {
		params.filter = TexFilter::Linear;
	}

#if 0
	return new Texture(data_start, size, format, params, std::move(debug_name));
#else
	if (params.filter == TexFilter::Nearest || params.filter == TexFilter::Linear) {
		return new Texture(data_start, size, format, params, std::move(debug_name));
	} else if (header->mipmap_count == 1) {
		params.filter = TexFilter::Linear;
		return new Texture(data_start, size, format, params, std::move(debug_name));
	} else {
		params.filter = TexFilter::Mipmapped;
		auto tex = new Texture(nullptr, size, format, params, std::move(debug_name));

		auto bytes_per_pixel = format_size(format);

		for (unsigned level=0; level<header->mipmap_count; ++level) {
			tex->set_mip_data(data_start, size, level);

			data_start += size.x * size.y * bytes_per_pixel;
			size.x = std::max(1u, size.x/2);
			size.y = std::max(1u, size.y/2);
		}
		return tex;
	}
#endif
}
Exemplo n.º 11
0
static void
update_preview_cb (GtkFileChooser *chooser)
{
  gchar *filename = gtk_file_chooser_get_preview_filename (chooser);
  gboolean have_preview = FALSE;
  
  if (filename)
    {
      GdkPixbuf *pixbuf;
      GError *error = NULL;

      pixbuf = my_new_from_file_at_size (filename, 128, 128, &error);
      if (pixbuf)
	{
	  gtk_image_set_from_pixbuf (GTK_IMAGE (preview_image), pixbuf);
	  g_object_unref (pixbuf);
	  gtk_widget_show (preview_image);
	  gtk_widget_hide (preview_label);
	  have_preview = TRUE;
	}
      else
	{
	  struct stat buf;
	  if (g_stat (filename, &buf) == 0)
	    {
	      gchar *preview_text;
	      gchar *size_str;
	      gchar *modified_time;
	      
	      size_str = format_size (buf.st_size);
	      modified_time = format_time (buf.st_mtime);
	      
	      preview_text = g_strdup_printf ("<i>Modified:</i>\t%s\n"
					      "<i>Size:</i>\t%s\n",
					      modified_time,
					      size_str);
	      gtk_label_set_markup (GTK_LABEL (preview_label), preview_text);
	      g_free (modified_time);
	      g_free (size_str);
	      g_free (preview_text);
	      
	      gtk_widget_hide (preview_image);
	      gtk_widget_show (preview_label);
	      have_preview = TRUE;
	    }
	}
      
      g_free (filename);
    }

  gtk_file_chooser_set_preview_widget_active (chooser, have_preview);
}
Exemplo n.º 12
0
int write_file(const uint8_t *data, size_t length, const struct extract_options *options,
               const char *filename, size_t offset, const char *ext, char *pathbuf, size_t pathbuflen)
{
	double sz = 0;
	const char *sz_unit = NULL;
	snprintf(pathbuf, pathbuflen, "%s%c%s_%08"PRIzx".%s",
		options->outdir, PATH_SEP, filename, offset, ext);
	
	if (length < options->minsize)
	{
		if (!options->quiet)
		{
			sz_unit = format_size(length, &sz);
			fprintf(stderr, "Skipped too small (%g %s) %s\n", sz, sz_unit, pathbuf);
		}

		return 0;
	}
	else if (length > options->maxsize)
	{
		if (!options->quiet)
		{
			sz_unit = format_size(length, &sz);
			fprintf(stderr, "Skipped too large (%g %s) %s\n", sz, sz_unit, pathbuf);
		}

		return 0;
	}

	double slice_size = 0;
	const char *slice_unit = format_size(length, &slice_size);
	printf("Writing %g %s to %s\n", slice_size, slice_unit, pathbuf);

	if (options->simulate)
		return 1;

	return write_data(pathbuf, data, length);
}
Exemplo n.º 13
0
void detect_reiser4(SECTION *section, int level)
{
  unsigned char *buf;
  char s[256];
  int layout_id;
  char layout_name[64];
  u4 blocksize;
  u8 blockcount;

  if (get_buffer(section, 16 * 4096, 1024, (void **)&buf) < 1024)
    return;

  /* check signature */
  if (memcmp(buf, "ReIsEr4", 7) != 0)
    return;

  /* get data from master superblock */
  layout_id = get_le_short(buf + 16);
  blocksize = get_le_short(buf + 18);
  if (layout_id == 0)
    strcpy(layout_name, "4.0 layout");
  else
    sprintf(layout_name, "Unknown layout with ID %d", layout_id);

  format_size(s, blocksize);
  print_line(level, "Reiser4 file system (%s, block size %s)",
             layout_name, s);

  /* get label and UUID */
  get_string(buf + 36, 16, s);
  if (s[0])
    print_line(level + 1, "Volume name \"%s\"", s);

  format_uuid(buf + 20, s);
  print_line(level + 1, "UUID %s", s);

  if (layout_id == 0) {
    /* read 4.0 superblock */
    if (get_buffer(section, 17 * 4096, 1024, (void **)&buf) < 1024)
      return;
    if (memcmp(buf + 52, "ReIsEr40FoRmAt", 14) != 0) {
      print_line(level + 1, "Superblock for 4.0 format missing");
      return;
    }

    blockcount = get_le_quad(buf);
    format_blocky_size(s, blockcount, blocksize, "blocks", NULL);
    print_line(level + 1, "Volume size %s", s);
  }
}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
    char buf[DEFAULT_LINK_LENGTH];
    float size = 100;
    int i = 0;

    for (i = 0; i < 50; i++)
    {
        format_size(buf, size);
        printf("%f format_size %s\n", size, buf);
        size += 1024 * 50;
    }

    return 0;
}
bool opentv_summaries_callback (int size, unsigned char* data)
{
	char fsize[256];
	buffer[buffer_index].size = size;
	buffer[buffer_index].data = _malloc (size);
	memcpy(buffer[buffer_index].data, data, size);
	buffer_index++;
	buffer_size += size;
	if (buffer_size_last + 100000 < buffer_size)
	{
		format_size (fsize, buffer_size);
		interactive_send_text (ACTION_SIZE, fsize);
		buffer_size_last = buffer_size;
	}
	return !stop;
}
Exemplo n.º 16
0
static gboolean
check_download_space (RCDTransaction *transaction, GError **err)
{
    gsize block_size;
    gsize avail_blocks;
    struct statvfs vfs_info;
    const char *cache_dir = rcd_prefs_get_cache_dir ();

    /* nothing to download... */
    if (!transaction->total_download_size)
        return TRUE;

    if (!g_path_is_absolute (cache_dir)) {
        g_set_error (err, RCD_TRANSACTION_ERROR_DOMAIN,
                     RCD_TRANSACTION_ERROR_DOWNLOAD,
                     "Cache directory is invalid: '%s'",
                     cache_dir);
        return FALSE;
    }

    if (!g_file_test (cache_dir, G_FILE_TEST_EXISTS))
        rc_mkdir (cache_dir, 0755);

    if (statvfs (cache_dir, &vfs_info)) {
        g_set_error (err, RCD_TRANSACTION_ERROR_DOMAIN,
                     RCD_TRANSACTION_ERROR_DOWNLOAD,
                     "Unable to get disk space info for '%s'",
                     cache_dir);
        return FALSE;
    }

    block_size = vfs_info.f_frsize;
    avail_blocks = vfs_info.f_bavail;

    if (transaction->total_download_size / block_size + 1 > avail_blocks) {
        g_set_error (err, RCD_TRANSACTION_ERROR_DOMAIN,
                     RCD_TRANSACTION_ERROR_DOWNLOAD,
                     "Insufficient disk space: %s needed in %s",
                     format_size (transaction->total_download_size),
                     cache_dir);

        return FALSE;
    }
    else
        return TRUE;
} /* check_download_space */
Exemplo n.º 17
0
void PropertiesDialog::update(const Glib::RefPtr<Gio::File>& file,
                              const Glib::RefPtr<Gio::FileInfo>& info,
                              const Size& dimensions,
                              unsigned int image_count) {
  name->set_label(info->get_display_name());
  width->set_label(Glib::ustring::compose(
      ngettext("%1 pixel", "%1 pixels", dimensions.width), dimensions.width));
  height->set_label(Glib::ustring::compose(
      ngettext("%1 pixel", "%1 pixels", dimensions.height), dimensions.height));
  type->set_label(Gio::content_type_get_description(info->get_content_type()));
  size->set_label(format_size(info->get_size(), G_FORMAT_SIZE_LONG_FORMAT));
  modified->set_label(Glib::DateTime::create_now_local(
      info->modification_time()).format("%c"));
  location_button->set_uri(file->get_uri());
  location->set_label(Glib::filename_display_name(
      file->get_parent()->get_path()));
  contents->set_label(Glib::ustring::compose(
      ngettext("%1 image", "%1 images", image_count), image_count));
}
Exemplo n.º 18
0
void detect_blank(SECTION *section, int level)
{
  unsigned char *buffer;
  int i, j;
  int block_size = BLOCK_SIZE;
  int max_blocks = MAX_BLOCKS;
  int blank_blocks = 0;
  unsigned char code;
  char s[256];

  if (get_buffer(section, 0, 1, (void **)&buffer) < 1)
    return;
  code = buffer[0];

  /* Limit to actual size of partition / disk */
  if (section->size && section->size < max_blocks * block_size) {
    max_blocks = section->size / block_size;
  }

  /* Determine number of blank blocks */
  for (i = 0; i < max_blocks; i++) {
    if (get_buffer(section, i * block_size, block_size, (void **)&buffer) < block_size)
      break;

    for (j = 0; j < block_size; j++) {
      if (buffer[j] != code)
        break;
    }
    if (j < block_size)
      break;

    blank_blocks = i + 1;
  }

  if (blank_blocks > 0 && blank_blocks >= max_blocks) {
    print_line(level, "Blank disk/medium");
  } else if (blank_blocks > MIN_BLOCKS) {
    format_size(s, blank_blocks * block_size);
    print_line(level, "First %s are blank", s);
  }
}
Exemplo n.º 19
0
int archwriter_write_buffer(carchwriter *ai, struct s_writebuf *wb)
{
    struct statvfs64 statvfsbuf;
    char textbuf[128];
    long lres;
    
    assert(ai);
    assert(wb);

    if (wb->size == 0)
    {   errprintf("wb->size=%ld\n", (long)wb->size);
        return -1;
    }

    if ((lres=write(ai->archfd, (char*)wb->data, (long)wb->size))!=(long)wb->size)
    {
        errprintf("write(size=%ld) returned %ld\n", (long)wb->size, (long)lres);
        if ((lres>0) && (lres < (long)wb->size)) // probably "no space left"
        {
            if (fstatvfs64(ai->archfd, &statvfsbuf)!=0)
            {   sysprintf("fstatvfs(fd=%d) failed\n", ai->archfd);
                return -1;
            }
            
            u64 freebytes = statvfsbuf.f_bfree * statvfsbuf.f_bsize;
            errprintf("Can't write to the archive file. Space on device is %s. \n"
                "If the archive is being written to a FAT filesystem, you may have reached \n"
                "the maximum filesize that it can handle (in general 2 GB)\n", 
                format_size(freebytes, textbuf, sizeof(textbuf), 'h'));
             werte_uebergeben (109,4);     
            return -1;
        }
        else // another error
        {
            sysprintf("write(size=%ld) failed\n", (long)wb->size);
            return -1;
        }
    }
    
    return 0;
}
Exemplo n.º 20
0
Arquivo: wm.c Projeto: krh/ksim
bool
get_surface(uint32_t binding_table_offset, int i, struct surface *s)
{
	uint64_t range;
	const uint32_t *binding_table;
	const uint32_t *state;

	binding_table = map_gtt_offset(binding_table_offset +
				       gt.surface_state_base_address, &range);
	if (range < 4)
		return false;

	state = map_gtt_offset(binding_table[i] +
			       gt.surface_state_base_address, &range);
	if (range < 16 * 4)
		return false;

	struct GEN9_RENDER_SURFACE_STATE v;
	GEN9_RENDER_SURFACE_STATE_unpack(state, &v);

	s->type = v.SurfaceType;
	s->width = v.Width + 1;
	s->height = v.Height + 1;
	s->stride = v.SurfacePitch + 1;
	s->format = v.SurfaceFormat;
	s->cpp = format_size(s->format);
	s->tile_mode = v.TileMode;
	s->qpitch = v.SurfaceQPitch << 2;
	s->minimum_array_element = v.MinimumArrayElement;
	s->pixels = map_gtt_offset(v.SurfaceBaseAddress, &range);

	const uint32_t block_size = format_block_size(s->format);
	const uint32_t height_in_blocks = DIV_ROUND_UP(s->height, block_size);

	if (range < height_in_blocks * s->stride) {
		ksim_warn("surface state out-of-range for bo\n");
		return false;
	}

	return true;
}
Exemplo n.º 21
0
void BtrfsDeviceResize::do_resize(HWND hwndDlg) {
    NTSTATUS Status;
    IO_STATUS_BLOCK iosb;
    btrfs_resize br;

    {
        win_handle h = CreateFileW(fn.c_str(), FILE_TRAVERSE | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
                                   OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr);

        if (h == INVALID_HANDLE_VALUE)
            throw last_error(GetLastError());

        br.device = dev_id;
        br.size = new_size;

        Status = NtFsControlFile(h, nullptr, nullptr, nullptr, &iosb, FSCTL_BTRFS_RESIZE, &br, sizeof(btrfs_resize), nullptr, 0);

        if (Status != STATUS_MORE_PROCESSING_REQUIRED && !NT_SUCCESS(Status))
            throw ntstatus_error(Status);
    }

    if (Status != STATUS_MORE_PROCESSING_REQUIRED) {
        wstring s, t, u;

        load_string(module, IDS_RESIZE_SUCCESSFUL, s);
        format_size(new_size, u, true);
        wstring_sprintf(t, s, dev_id, u.c_str());
        MessageBoxW(hwndDlg, t.c_str(), L"", MB_OK);

        EndDialog(hwndDlg, 0);
    } else {
        HWND par;

        par = GetParent(hwndDlg);
        EndDialog(hwndDlg, 0);

        BtrfsBalance bb(fn, false, true);
        bb.ShowBalance(par);
    }
}
Exemplo n.º 22
0
void detect_btrfs(SECTION *section, int level)
{
  unsigned char *buf;
  char s[258];

  if (get_buffer(section, 64 * 1024, 1024, (void **)&buf) < 1024)
    return;

  if (memcmp(buf + 64, "_BHRfS_M", 8) == 0) {
    print_line(level, "Btrfs file system");

    get_string(buf + 299, 256, s);
    if (s[0])
      print_line(level + 1, "Volume name \"%s\"", s);

    format_uuid(buf + 32, s);
    print_line(level + 1, "UUID %s", s);

    format_size(s, get_le_quad(buf + 0x70));
    print_line(level + 1, "Volume size %s", s);
  }
}
Exemplo n.º 23
0
void ExportObjectDialog::addObjectEntry(export_object_entry_t *entry)
{
    QTreeWidgetItem *entry_item;
    gchar *size_str;

    if (!entry) return;

    size_str = format_size(entry->payload_len, format_size_unit_bytes|format_size_prefix_si);

    entry_item = new QTreeWidgetItem(eo_ui_->objectTree);
    entry_item->setData(0, Qt::UserRole, qVariantFromValue(entry));

    entry_item->setText(0, QString().setNum(entry->pkt_num));
    entry_item->setText(1, entry->hostname);
    entry_item->setText(2, entry->content_type);
    entry_item->setText(3, size_str);
    entry_item->setText(4, entry->filename);
    g_free(size_str);
    // Not perfect but better than nothing.
    entry_item->setTextAlignment(3, Qt::AlignRight);

    if (save_all_bt_) save_all_bt_->setEnabled(true);
}
Exemplo n.º 24
0
UIDiskChooser::UIDiskChooser(const char* title):Fl_Double_Window(400, 200, title){
	uint32 i = 0;
	uint32 dcount = disk_count();
	disk_info_t info;
	handle_t h;
	char *fmt_name = "\\\\.\\PhysicalDrive%d";
	char *name;
	char *size;

	_list = new UIDiskList(0, 0, 400, 160);
	_list->begin();
	for (i = 0; i < dcount; i ++){
		h = disk_open(i);
		if (h != null){
			name = (char*)calloc(64, sizeof(char));
			size = (char*)calloc(32, sizeof(char));
			
			disk_info(h, &info);
			format_size(size, info.size);
			sprintf(name, fmt_name, i);
			
			_list->add_disk(i, name, size, info.mbr.gpt_protect ? info.gpt.part_count : info.mbr.part_count);
		}
		disk_close(h);
	}
	_list->end();
	add(_list);
	
	_ok = new Fl_Button(260, 170, 60, 24, "OK");
	_ok->callback(ok_cb, this);
	add(_ok);
	_cancel = new Fl_Button(330, 170, 60, 24, "Cancel");
	_cancel->callback(cancel_cb, this);
	add(_cancel);

}
Exemplo n.º 25
0
/**
   Add the specified filename if it matches the specified wildcard. 

   If the filename matches, first get the description of the specified
   filename. If this is a regular file, append the filesize to the
   description.

   \param list the list to add he completion to
   \param fullname the full filename of the file
   \param completion the completion part of the file name
   \param wc the wildcard to match against
   \param is_cmd whether we are performing command completion
*/
static void wildcard_completion_allocate( std::vector<completion_t> &list, 
					  const wcstring &fullname, 
					  const wcstring &completion,
					  const wchar_t *wc,
                      expand_flags_t expand_flags)
{
	struct stat buf, lbuf;
    wcstring sb;
	wcstring munged_completion;
    
	int flags = 0;
	int stat_res, lstat_res;
	int stat_errno=0;
	
	long long sz; 

	/*
	  If the file is a symlink, we need to stat both the file itself
	  _and_ the destination file. But we try to avoid this with
	  non-symlinks by first doing an lstat, and if the file is not a
	  link we copy the results over to the regular stat buffer.
	*/
	if( ( lstat_res = lwstat( fullname, &lbuf ) ) )
	{
        /* lstat failed! */
		sz=-1;
		stat_res = lstat_res;
	}
	else
	{
		if (S_ISLNK(lbuf.st_mode))
		{
			
			if( ( stat_res = wstat( fullname, &buf ) ) )
			{
				sz=-1;
			}
			else
			{
				sz = (long long)buf.st_size;
			}
			
			/*
			  In order to differentiate between e.g. rotten symlinks
			  and symlink loops, we also need to know the error status of wstat.
			*/
			stat_errno = errno;
		}
		else
		{
			stat_res = lstat_res;
			memcpy( &buf, &lbuf, sizeof( struct stat ) );
			sz = (long long)buf.st_size;
		}
	}
	
    
    bool wants_desc = ! (expand_flags & EXPAND_NO_DESCRIPTIONS);
	wcstring desc;
    if (wants_desc)
        desc = file_get_desc( fullname.c_str(), lstat_res, lbuf, stat_res, buf, stat_errno );
    
	if( sz >= 0 && S_ISDIR(buf.st_mode) )
	{
		flags = flags | COMPLETE_NO_SPACE;
        munged_completion = completion;
        munged_completion.push_back(L'/');
        if (wants_desc)
            sb.append(desc);
	}
	else
	{
        if (wants_desc)
        {
            if (! desc.empty())
            {
                sb.append(desc);
                sb.append(L", ");
            }
            sb.append(format_size(sz));
        }
	}
    
    const wcstring &completion_to_use = munged_completion.empty() ? completion : munged_completion;
	wildcard_complete(completion_to_use, wc, sb.c_str(), NULL, list, flags);
}
Exemplo n.º 26
0
void
refresh_progress_meter(void)
{
	char buf[MAX_WINSIZE + 1];
	time_t now;
	off_t transferred;
	double elapsed;
	int percent;
	off_t bytes_left;
	int cur_speed;
	int hours, minutes, seconds;
	int i, len;
	int file_len;
	off_t delta_pos;

	transferred = *counter - cur_pos;
	cur_pos = *counter;
	now = time(NULL);
	bytes_left = end_pos - cur_pos;

	delta_pos = cur_pos - last_pos;
	if (delta_pos > max_delta_pos) 
		max_delta_pos = delta_pos;

	if (bytes_left > 0)
		elapsed = now - last_update;
	else {
		elapsed = now - start;
		/* Calculate true total speed when done */
		transferred = end_pos;
		bytes_per_second = 0;
	}

	/* calculate speed */
	if (elapsed != 0)
		cur_speed = (transferred / elapsed);
	else
		cur_speed = transferred;

#define AGE_FACTOR 0.9
	if (bytes_per_second != 0) {
		bytes_per_second = (bytes_per_second * AGE_FACTOR) +
		    (cur_speed * (1.0 - AGE_FACTOR));
	} else
		bytes_per_second = cur_speed;

	/* filename */
	buf[0] = '\0';
	file_len = win_size - 45;
	if (file_len > 0) {
		len = snprintf(buf, file_len + 1, "\r%s", file);
		if (len < 0)
			len = 0;
		if (len >= file_len + 1)
			len = file_len;
		for (i = len; i < file_len; i++)
			buf[i] = ' ';
		buf[file_len] = '\0';
	}

	/* percent of transfer done */
	if (end_pos != 0)
		percent = ((float)cur_pos / end_pos) * 100;
	else
		percent = 100;

	snprintf(buf + strlen(buf), win_size - strlen(buf-8),
	    " %3d%% ", percent);

	/* amount transferred */
	format_size(buf + strlen(buf), win_size - strlen(buf),
	    cur_pos);
	strlcat(buf, " ", win_size);

	/* bandwidth usage */
	format_rate(buf + strlen(buf), win_size - strlen(buf),
	    (off_t)bytes_per_second);
	strlcat(buf, "/s ", win_size);

	/* instantaneous rate */
	format_rate(buf + strlen(buf), win_size - strlen(buf),
	    delta_pos);
	strlcat(buf, "/s ", win_size);

	/* ETA */
	if (!transferred)
		stalled += elapsed;
	else
		stalled = 0;

	if (stalled >= STALL_TIME)
		strlcat(buf, "- stalled -", win_size);
	else if (bytes_per_second == 0 && bytes_left)
		strlcat(buf, "  --:-- ETA", win_size);
	else {
		if (bytes_left > 0)
			seconds = bytes_left / bytes_per_second;
		else
			seconds = elapsed;

		hours = seconds / 3600;
		seconds -= hours * 3600;
		minutes = seconds / 60;
		seconds -= minutes * 60;

		if (hours != 0)
			snprintf(buf + strlen(buf), win_size - strlen(buf),
			    "%d:%02d:%02d", hours, minutes, seconds);
		else
			snprintf(buf + strlen(buf), win_size - strlen(buf),
			    "  %02d:%02d", minutes, seconds);

		if (bytes_left > 0)
			strlcat(buf, " ETA", win_size);
		else
			strlcat(buf, "    ", win_size);
	}

	write(STDOUT_FILENO, buf, win_size - 1);
	last_update = now;
	last_pos = cur_pos;
}
Exemplo n.º 27
0
static void
print_stats(const gchar *filename, capture_info *cf_info)
{
  const gchar           *file_type_string, *file_encap_string;
  gchar                 *size_string;

  /* Build printable strings for various stats */
  file_type_string = wtap_file_type_subtype_string(cf_info->file_type);
  file_encap_string = wtap_encap_string(cf_info->file_encap);

  if (filename)           printf     ("File name:           %s\n", filename);
  if (cap_file_type)      printf     ("File type:           %s%s\n",
      file_type_string,
      cf_info->iscompressed ? " (gzip compressed)" : "");

  if (cap_file_encap) {
    printf      ("File encapsulation:  %s\n", file_encap_string);
    if (cf_info->file_encap == WTAP_ENCAP_PER_PACKET) {
      int i;
      printf    ("Encapsulation in use by packets (# of pkts):\n");
      for (i=0; i<WTAP_NUM_ENCAP_TYPES; i++) {
        if (cf_info->encap_counts[i] > 0)
          printf("                     %s (%d)\n",
                 wtap_encap_string(i), cf_info->encap_counts[i]);
      }
    }
  }
  if (cap_file_more_info) {
    printf      ("File timestamp precision:  %s (%d)\n",
      wtap_tsprec_string(cf_info->file_tsprec), cf_info->file_tsprec);
  }

  if (cap_snaplen && cf_info->snap_set)
    printf     ("Packet size limit:   file hdr: %u bytes\n", cf_info->snaplen);
  else if (cap_snaplen && !cf_info->snap_set)
    printf     ("Packet size limit:   file hdr: (not set)\n");
  if (cf_info->snaplen_max_inferred > 0) {
    if (cf_info->snaplen_min_inferred == cf_info->snaplen_max_inferred)
      printf     ("Packet size limit:   inferred: %u bytes\n", cf_info->snaplen_min_inferred);
    else
      printf     ("Packet size limit:   inferred: %u bytes - %u bytes (range)\n",
          cf_info->snaplen_min_inferred, cf_info->snaplen_max_inferred);
  }
  if (cap_packet_count) {
    printf     ("Number of packets:   ");
    if (machine_readable) {
      printf ("%u\n", cf_info->packet_count);
    } else {
      size_string = format_size(cf_info->packet_count, format_size_unit_none);
      printf ("%s\n", size_string);
      g_free(size_string);
    }
  }
  if (cap_file_size) {
    printf     ("File size:           ");
    if (machine_readable) {
      printf     ("%" G_GINT64_MODIFIER "d bytes\n", cf_info->filesize);
    } else {
      size_string = format_size(cf_info->filesize, format_size_unit_bytes);
      printf ("%s\n", size_string);
      g_free(size_string);
    }
  }
  if (cap_data_size) {
    printf     ("Data size:           ");
    if (machine_readable) {
      printf     ("%" G_GINT64_MODIFIER "u bytes\n", cf_info->packet_bytes);
    } else {
      size_string = format_size(cf_info->packet_bytes, format_size_unit_bytes);
      printf ("%s\n", size_string);
      g_free(size_string);
    }
  }
  if (cf_info->times_known) {
    if (cap_duration) /* XXX - shorten to hh:mm:ss */
                          printf("Capture duration:    %s\n", relative_time_string(&cf_info->duration, cf_info->duration_tsprec, cf_info, TRUE));
    if (cap_start_time)
                          printf("First packet time:   %s\n", absolute_time_string(&cf_info->start_time, cf_info->start_time_tsprec, cf_info));
    if (cap_end_time)
                          printf("Last packet time:    %s\n", absolute_time_string(&cf_info->stop_time, cf_info->stop_time_tsprec, cf_info));
    if (cap_data_rate_byte) {
                          printf("Data byte rate:      ");
      if (machine_readable) {
        print_value("", 2, " bytes/sec",   cf_info->data_rate);
      } else {
        size_string = format_size((gint64)cf_info->data_rate, format_size_unit_bytes_s);
        printf ("%s\n", size_string);
        g_free(size_string);
      }
    }
    if (cap_data_rate_bit) {
                          printf("Data bit rate:       ");
      if (machine_readable) {
        print_value("", 2, " bits/sec",    cf_info->data_rate*8);
      } else {
        size_string = format_size((gint64)(cf_info->data_rate*8), format_size_unit_bits_s);
        printf ("%s\n", size_string);
        g_free(size_string);
      }
    }
  }
  if (cap_packet_size)    printf("Average packet size: %.2f bytes\n",        cf_info->packet_size);
  if (cf_info->times_known) {
    if (cap_packet_rate) {
                          printf("Average packet rate: ");
      if (machine_readable) {
        print_value("", 2, " packets/sec", cf_info->packet_rate);
      } else {
        size_string = format_size((gint64)cf_info->packet_rate, format_size_unit_packets_s);
        printf ("%s\n", size_string);
        g_free(size_string);
      }
    }
  }
#ifdef HAVE_LIBGCRYPT
  if (cap_file_hashes) {
    printf     ("SHA1:                %s\n", file_sha1);
    printf     ("RIPEMD160:           %s\n", file_rmd160);
    printf     ("MD5:                 %s\n", file_md5);
  }
#endif /* HAVE_LIBGCRYPT */
  if (cap_order)          printf     ("Strict time order:   %s\n", order_string(cf_info->order));
  if (cap_comment && cf_info->comment)
    printf     ("Capture comment:     %s\n", cf_info->comment);
  if (cap_file_more_info) {
    if (cf_info->hardware)
      printf   ("Capture hardware:    %s\n", cf_info->hardware);
    if (cf_info->os)
      printf   ("Capture oper-sys:    %s\n", cf_info->os);
    if (cf_info->usr_appl)
      printf   ("Capture application: %s\n", cf_info->usr_appl);
  }

  if (cap_file_idb && cf_info->num_interfaces != 0) {
    guint i;
    g_assert(cf_info->num_interfaces == cf_info->idb_info_strings->len);
    printf     ("Number of interfaces in file: %u\n", cf_info->num_interfaces);
    for (i = 0; i < cf_info->idb_info_strings->len; i++) {
      gchar *s = g_array_index(cf_info->idb_info_strings, gchar*, i);
      printf   ("Interface #%u info:\n", i);
      printf   ("%s", s);
      printf   ("                     Number of packets = %u\n", cf_info->interface_ids[i]);
    }
  }
Exemplo n.º 28
0
static int usage(int argc, char **argv)
{
	const char *progname = argc <= 0 ? "mediaextract" : argv[0];
	double default_length = 0;
	double default_size   = 0;
	const char *length_unit = format_size((SIZE_MAX>>1), &default_length);
	const char *size_unit   = format_size(SIZE_MAX,      &default_size);

	fprintf(stderr,
		"mediaextract - extracts media files that are embedded within other files\n"
		"\n"
		"Usage:\n"
		"  %s [option...] <filename> [<filename> ...]\n"
		"\n"
		"Options:\n"
		"  -h, --help             Print this help message.\n"
		"  -q, --quiet            Do not print status messages.\n"
		"  -s, --simulate         Don't write any output files.\n"
		"  -o, --output=DIR       Directory where extracted files should be written. (default: \".\")\n"
		"  -i, --offset=OFFSET    Start processing at byte OFFSET. (default: 0)\n"
		"  -n, --length=LENGTH    Only process LENGTH bytes.\n"
		"                         (default and maximum: %g %s)\n",
		progname, default_length, length_unit);

#if !defined(__LP64__) && !defined(_WIN64)

	fprintf(stderr,
		"\n"
		"                         NOTE: This program is compiled as a 32bit binary. This means\n"
		"                         the maximum amount of bytes that can be processed at once are\n"
		"                         limited to 2 GB. The rest of bigger files will be ignored. You\n"
		"                         need to run this program several times with different offsets\n"
		"                         to process such a file whole.\n"
		"\n"
		"                         This also means that extracted files can never be larger than\n"
		"                         2 GB.\n"
		"\n");

#endif

	fprintf(stderr,
		"  -m, --min-size=SIZE    Minumum size of extracted files (skip smaller). (default: 0)\n"
		"  -x, --max-size=SIZE    Maximum size of extracted files (skip larger).\n"
		"                         (default and maximum: %g %s)\n"
		"\n"
		"                         The last character of OFFSET, LENGTH and SIZE may be one of the\n"
		"                         following:\n"
		"                           B (or none)  for Bytes\n"
		"                           k            for Kilobytes (units of 1024 Bytes)\n"
		"                           M            for Megabytes (units of 1024 Kilobytes)\n"
		"                           G            for Gigabytes (units of 1024 Megabytes)\n"
		"                           T            for Terabytes (units of 1024 Gigabytes)\n"
		"                           P            for Petabytes (units of 1024 Terabytes)\n"
		"                           E            for Exabytes  (units of 1024 Petabytes)\n"
		"\n"
		"                         The special value \"max\" selects the maximum alowed value.\n"
		"\n",
		default_size, size_unit);

	fprintf(stderr,
		"  -f, --formats=FORMATS  Comma separated list of formats (file magics) to extract.\n"
		"\n"
		"                         Supported formats:\n"
		"                           all      all supported formats\n"
		"                           default  the default set of formats (AIFF, ASF, AU, BINK, BMP,\n"
		"                                    GIF, ID3v2, IT, JEPG, MPEG 1, MPEG PS, MIDI, MP4, Ogg,\n"
		"                                    PNG, RIFF, S3M, SMK, XM)\n"
		"                           audio    all audio files (AIFF, ASF, AU, ID3v2, IT, MIDI, MP4,\n"
		"                                    Ogg, RIFF, S3M, XM)\n"
		"                           text     all text files (ASCII, UTF-8, UTF-16LE, UTF-16BE,\n"
		"                                    UTF-32LE, UTF-32BE)\n"
		"                           image    all image files (BMP, PNG, JEPG, GIF)\n"
		"                           mpeg     all safe mpeg files (MPEG 1, MPEG PS, ID3v2)\n"
		"                           tracker  all tracker files (MOD, S3M, IT, XM)\n"
		"                           video    all video files (ASF, BINK, MP4, RIFF, SMK)\n"
		"\n"
		"                           aiff     big-endian (Apple) wave files\n"
		"                           ascii    7-bit ASCII files (only printable characters)\n"
		"                           asf      Advanced Systems Format files (also WMA and WMV)\n"
		"                           au       Sun Microsystems audio file format (.au or .snd)\n"
		"                           bink     BINK files\n"
		"                           bmp      Windows Bitmap files\n"
		"                           gif      Graphics Interchange Format files\n"
		"                           id3v2    MPEG layer 1/2/3 files with ID3v2 tags\n"
		"                           it       ImpulseTracker files\n"
		"                           jepg     JPEG Interchange Format files\n"
		"                           midi     MIDI files\n"
		"                           mod      Noisetracker/Soundtracker/Protracker Module files\n"
		"                           mpg123   MPEG layer 1/2/3 files (MP1, MP2, MP3)\n"
		"                           mpeg1    MPEG 1 System Streams\n"
		"                           mpegps   MPEG 2 Program Streams\n"
		"                           mpegts   MPEG 2 Transport Streams\n"
		"                           mp4      MP4 files (M4A, M4V, 3GPP etc.)\n"
		"                           ogg      Ogg files (Vorbis, Opus, Theora, etc.)\n"
		"                           png      Portable Network Graphics files\n"
		"                           riff     Resource Interchange File Format files (ANI, AVI, MMM,\n"
		"                                    PAL, RDI, RMI, SGT, STY, WAV and more)\n"
		"                           s3m      ScreamTracker III files\n"
		"                           smk      Smaker files\n"
		"                           utf-8    7-bit ASCII and UTF-8 files (only printable code points)\n"
		"                           utf-16be big-endian UTF-16 files (only printable code points)\n"
		"                           utf-16le little-endian UTF-16 files (only printable code points)\n"
		"                           utf-32be big-endian UTF-32 files (only printable code points)\n"
		"                           utf-32le little-endian UTF-32 files (only printable code points)\n"
		"                           xm       Extended Module files\n"
		"\n");

	fprintf(stderr,
		"                         WARNING: Because MP1/2/3 files do not have a nice file magic, using\n"
		"                         the 'mpg123' format may cause *a lot* of false positives. Nowadays\n"
		"                         MP3 files usually have an ID3v2 tag at the start, so using the\n"
		"                         'id3v2' format is the better option anyway.\n"
		"\n"
		"                         The detection accuracy of MOD files is not much better and of MPEG TS\n"
		"                         it is even worse and thus the 'mpg123', 'mpegts' and 'mod' formats\n"
		"                         are per default disabled.\n"
		"\n"
		"                         NOTE: When using only the 'mpg123' format but not 'id3v2' any ID3v2\n"
		"                         tag will be stripped. ID3v1 tags will still be kept.\n"
		"\n"
		"                         If '-' is written before a format name the format will be\n"
		"                         removed from the set of formats to extract. E.g. extract\n"
		"                         everything except tracker files:\n"
		"\n"
		"                           %s --formats=all,-tracker data.bin\n"
		"\n",
		progname);
	return 255;
}
Exemplo n.º 29
0
int do_extract(const uint8_t *filedata, size_t filesize, const struct extract_options *options, size_t *numfilesptr, size_t *sumsizeptr)
{
	const uint8_t *ptr = NULL, *end = NULL;
	enum fileformat format = NONE;

	size_t sumsize = 0;
	size_t length = 0;
	int success = 1;
	int formats = options->formats;
	char *outfilename = NULL;

	size_t numfiles = 0;
	const char *filename = basename(options->filepath);
	// max. ext length is 16 characters
	size_t namelen = strlen(options->outdir) + strlen(filename) + 37;

	struct mpg123_info mpg123;
	struct ogg_info ogg;
	struct file_info info = {0, 0};
	size_t count = 0; // e.g. for tracks count in midi
	const uint8_t *audio_start = NULL;
	size_t input_len = 0;

	outfilename = malloc(namelen);
	if (outfilename == NULL)
	{
		perror(options->filepath);
		goto error;
	}

	if (!options->quiet)
	{
		double slice_size = 0;
		const char *slice_unit = format_size(filesize, &slice_size);
		printf("Extracting 0x%08"PRIx64" ... 0x%08"PRIx64" (%g %s) from %s\n",
			options->offset,
			options->offset + filesize,
			slice_size, slice_unit,
			options->filepath);
	}

#define WRITE_FILE(data, length, ext) \
	if (write_file((data), length, options, filename, (size_t)((data) - filedata), (ext), outfilename, namelen)) \
	{ \
		++ numfiles; \
		sumsize += length; \
	}
	
	ptr = filedata;
	end = filedata + filesize;
	for (input_len = filesize; input_len >= 4; input_len = (size_t)(end - ptr))
	{
		uint32_t magic = MAGIC(ptr);
		
		if (formats & OGG && magic == OGG_MAGIC && ogg_ispage(ptr, input_len, &ogg))
		{
			uint32_t pageno = ogg.pageno;
			audio_start = ptr;

			for (;;)
			{
				ptr += ogg.length;
				
				if (!ogg_ispage(ptr, (size_t)(end - ptr), &ogg) || ogg.pageno <= pageno)
					break;

				pageno = ogg.pageno;
			}

			WRITE_FILE(audio_start, ptr - audio_start, "ogg");
			continue;
		}

		if (formats & RIFF && magic == RIFF_MAGIC && riff_isfile(ptr, input_len, &info))
		{
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}
		
		if (formats & AIFF && magic == FORM_MAGIC && aiff_isfile(ptr, input_len, &info))
		{
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}
		
		if (formats & MIDI && magic == MIDI_MAGIC && midi_isheader(ptr, input_len, &length, &count))
		{
			audio_start = ptr;
			do {
				ptr += length;
			} while (count-- > 0 && midi_istrack(ptr, (size_t)(end - ptr), &length));

			if (count != 0 && !(options->quiet))
			{
				fprintf(stderr, "warning: midi file misses %"PRIzu" tracks\n", count);
			}

			WRITE_FILE(audio_start, ptr - audio_start, "mid");
			continue;
		}
		
		format = NONE;
		if (formats & ID3v2 && IS_ID3v2_MAGIC(ptr) && id3v2_istag(ptr, input_len, 0, &length))
		{
			format = ID3v2;
		}

		if (formats & MPG123 && IS_MPG123_MAGIC(ptr))
		{
			format = MPG123;
			length = 0;
		}

		if (format & (ID3v2 | MPG123) && mpg123_isframe(ptr + length, input_len - length, &mpg123))
		{
			uint8_t version = mpg123.version;
			uint8_t layer   = mpg123.layer;

			audio_start = ptr;
			ptr += length;

			do {
				ptr += mpg123.frame_size;
			} while (mpg123_isframe(ptr, (size_t)(end - ptr), &mpg123)
			      && mpg123.version == version
			      && mpg123.layer   == layer);
					
			if (id3v1_istag(ptr, (size_t)(end - ptr), &length))
			{
				ptr += length;
			}

			if (formats & ID3v2 && id3v2_istag(ptr, (size_t)(end - ptr), 1, &length))
			{
				ptr += length;
			}
					
			WRITE_FILE(audio_start, ptr - audio_start,
				layer == 1 ? "mp1" :
				layer == 2 ? "mp2" :
				layer == 3 ? "mp3" :
				             "mpg");
			continue;
		}
		
		if (formats & IT && magic == IT_MAGIC && it_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "it");
			ptr += length;
			continue;
		}

		if (formats & XM && magic == XM_MAGIC && xm_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "xm");
			ptr += length;
			continue;
		}

		if (formats & ASF && magic == ASF_MAGIC && asf_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "asf");
			ptr += length;
			continue;
		}

		if (formats & AU && magic == AU_MAGIC && au_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "au");
			ptr += length;
			continue;
		}

		if (formats & PNG && magic == PNG_MAGIC && png_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "png");
			ptr += length;
			continue;
		}

		if (formats & GIF && magic == GIF_MAGIC && gif_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "gif");
			ptr += length;
			continue;
		}

		if (formats & (MPEG1 | MPEGPS | MPEGVS) && IS_MPEG_MAGIC(magic) && mpeg_isfile(ptr, input_len, formats, &length))
		{
			WRITE_FILE(ptr, length, "mpg");
			ptr += length;
			continue;
		}

		if (formats & MPEGTS && IS_MPEG_TS_MAGIC(ptr) && mpeg_isfile(ptr, input_len, formats, &length))
		{
			WRITE_FILE(ptr, length, "mpg");
			ptr += length;
			continue;
		}

		if (formats & JPEG && IS_JPG_MAGIC(magic) && jpg_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "jpg");
			ptr += length;
			continue;
		}

		if (formats & BINK && IS_BINK_MAGIC(magic) && bink_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "bik");
			ptr += length;
			continue;
		}

		if (formats & BMP && IS_BMP_MAGIC(ptr) && bmp_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "bmp");
			ptr += length;
			continue;
		}

		if (formats & SMK && IS_SMK_MAGIC(magic) && smk_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "smk");
			ptr += length;
			continue;
		}

		if (formats & MP4 && input_len > MP4_HEADER_SIZE &&
			MAGIC(ptr + MP4_MAGIC_OFFSET) == MP4_MAGIC &&
			mp4_isfile(ptr, input_len, &info))
		{
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		if (formats & S3M && input_len > S3M_MAGIC_OFFSET + 4 &&
			MAGIC(ptr + S3M_MAGIC_OFFSET) == S3M_MAGIC &&
			s3m_isfile(ptr, input_len, &length))
		{
			WRITE_FILE(ptr, length, "s3m");
			ptr += length;
			continue;
		}

		if (formats & MOD && input_len > MOD_MAGIC_OFFSET + 4)
		{
			const uint8_t *modmagic = ptr + MOD_MAGIC_OFFSET;
			if (IS_MOD_MAGIC(modmagic) && mod_isfile(ptr, input_len, &length))
			{
				WRITE_FILE(ptr, length, "mod");
				ptr += length;
				continue;
			}
		}

		if (formats & UTF_32LE && utf32le_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		if (formats & UTF_32BE && utf32be_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		if (formats & UTF_16LE && utf16le_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		if (formats & UTF_16BE && utf16be_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		if (formats & UTF_8 && utf8_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}
		else if (formats & ASCII && ascii_isfile(ptr, input_len, &info)) {
			WRITE_FILE(ptr, info.length, info.ext);
			ptr += info.length;
			continue;
		}

		++ ptr;
	}

	goto cleanup;

error:
	success = 0;

cleanup:
	if (outfilename)
		free(outfilename);

	if (numfilesptr)
		*numfilesptr = numfiles;
	
	if (sumsizeptr)
		*sumsizeptr = sumsize;

	return success;
}
Exemplo n.º 30
0
int main(int argc, char **argv)
{
	struct extract_options options = { NULL, ".", 0, SIZE_MAX, 0, (SIZE_MAX>>1), DEFAULT_FORMATS, 0, 0 };
	int i = 0, opt = 0;
	size_t failures = 0;
	size_t sumnumfiles = 0;
	size_t numfiles = 0;
	size_t size = 0;
	size_t sumsize = 0;

	while ((opt = getopt_long(argc, argv, "f:o:hqm:x:n:i:s", long_options, NULL)) != -1)
	{
		switch (opt)
		{
			case 'f':
				if (!parse_formats(optarg, &options.formats))
					return 255;
				else if (options.formats == 0)
				{
					fprintf(stderr, "error: No formats specified.\n"SEE_HELP);
					return 255;
				}
				break;

			case 'o':
				options.outdir = optarg;
				break;

			case 'h':
				return usage(argc, argv);

			case 'q':
				options.quiet = 1;
				break;

			case 'x':
			case 'm':
			case 'n':
				if (!parse_size(optarg, &size))
				{
					perror(optarg);
					fprintf(stderr, SEE_HELP);
					return 255;
				}

				if (opt == 'm')
					options.minsize = size;
				else if (opt == 'x')
					options.maxsize = size;
				else
					options.length  = size;
				break;

			case 'i':
				if (!parse_offset(optarg, &(options.offset)))
				{
					perror(optarg);
					fprintf(stderr, SEE_HELP);
					return 255;
				}
				break;

			case 's':
				options.simulate = 1;
				break;

			default:
				fprintf(stderr, SEE_HELP);
				return 255;
		}
	}

	if (optind >= argc)
	{
		fprintf(stderr, "error: Not enough arguments.\n"SEE_HELP);
		return 1;
	}

	if (options.length == 0)
	{
		if (!options.quiet)
			printf("Nothing to extract for 0-length range.\n");
		return 0;
	}

	for (i = optind; i < argc; ++ i)
	{
		options.filepath = argv[i];
		numfiles = 0;
		size = 0;
		if (extract(&options, &numfiles, &size))
		{
			sumnumfiles += numfiles;
			sumsize += size;
		}
		else {
			fprintf(stderr, "Error processing file: %s\n", options.filepath);
			failures += 1;
		}
	}

	double sz = 0;
	const char *sz_unit = format_size(sumsize, &sz);
	if (sumnumfiles == 1)
		printf("Extracted 1 file of %g %s size.\n", sz, sz_unit);
	else
		printf("Extracted %"PRIzu" files of %g %s size.\n", sumnumfiles, sz, sz_unit);

	if (failures > 0)
	{
		fprintf(stderr, "%"PRIzu" error(s) during extraction.\n", failures);
		return 1;
	}
	return 0;
}