origami-2.0.0/ 0000755 0000041 0000041 00000000000 12757133667 013211 5 ustar www-data www-data origami-2.0.0/bin/ 0000755 0000041 0000041 00000000000 12757133666 013760 5 ustar www-data www-data origami-2.0.0/bin/gui/ 0000755 0000041 0000041 00000000000 12757133666 014544 5 ustar www-data www-data origami-2.0.0/bin/gui/gtkhex.rb 0000644 0000041 0000041 00000124335 12757133666 016373 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
This work has been derived from the GHex project. Thanks to them.
Original implementation: Jaka Mocnik
=end
require 'gtk2'
module Gtk
class HexEditor < Fixed
module View
HEX = 1
ASCII = 2
end
module Group
BYTE = 1
WORD = 2
LONG = 4
end
class Highlight
attr_accessor :start, :end
attr_accessor :start_line, :end_line
attr_accessor :style
attr_accessor :min_select
attr_accessor :valid
end
class AutoHighlight
attr_accessor :search_view
attr_accessor :search_string
attr_accessor :search_len
attr_accessor :color
attr_accessor :view_min
attr_accessor :view_max
attr_accessor :highlights
end
DEFAULT_FONT = "Monospace 12"
DEFAULT_CPL = 32
DEFAULT_LINES = 16
DISPLAY_BORDER = 4
SCROLL_TIMEOUT = 100
type_register
@@primary = Clipboard.get(Gdk::Selection::PRIMARY)
@@clipboard = Clipboard.get(Gdk::Selection::CLIPBOARD)
def initialize(data = '')
super()
@data = data.force_encoding('binary')
@scroll_timeout = -1
@disp_buffer = ""
@starting_offset = 0
@xdisp_width = @adisp_width = 200
@xdisp_gc = @adisp_gc = nil
@active_view = View::HEX
@group_type = Group::BYTE
@lines = @vis_lines = @top_line = @cpl = 0
@cursor_pos = 0
@lower_nibble = false
@cursor_shown = false
@button = 0
@insert = false
@selecting = false
@selection = Highlight.new
@selection.start = @selection.end = 0
@selection.style = nil
@selection.min_select = 1
@selection.valid = false
@highlights = [ @selection ]
@auto_highlight = nil
@disp_font_metrics = load_font DEFAULT_FONT
@font_desc = Pango::FontDescription.new DEFAULT_FONT
@char_width = get_max_char_width(@disp_font_metrics)
@char_height = Pango.pixels(@disp_font_metrics.ascent) + Pango.pixels(@disp_font_metrics.descent) + 2
@show_offsets = false
@offsets_gc = nil
self.can_focus = true
self.events = Gdk::Event::KEY_PRESS_MASK
self.border_width = DISPLAY_BORDER
mouse_handler = lambda do |widget, event|
if event.event_type == Gdk::Event::BUTTON_RELEASE and event.button == 1
if @scroll_timeout
GLib::Source.remove @scroll_timeout
@scroll_timeout = nil
@scroll_dir = 0
end
@selecting = false
Gtk.grab_remove(widget)
@button = 0
elsif event.event_type == Gdk::Event::BUTTON_PRESS and event.button == 1
self.grab_focus unless self.has_focus?
Gtk.grab_add(widget)
@button = event.button
focus_view = (widget == @xdisp) ? View::HEX : View::ASCII
if @active_view == focus_view
if @active_view == View::HEX
hex_to_pointer(event.x, event.y)
else
ascii_to_pointer(event.x, event.y)
end
unless @selecting
@selecting = true
set_selection(@cursor_pos, @cursor_pos)
end
else
hide_cursor
@active_view = focus_view
show_cursor
end
elsif event.event_type == Gdk::Event::BUTTON_PRESS and event.button == 2
# TODO
else
@button = 0
end
end
@xdisp = DrawingArea.new
@xdisp.modify_font @font_desc
@xlayout = @xdisp.create_pango_layout('')
@xdisp.events =
Gdk::Event::EXPOSURE_MASK |
Gdk::Event::BUTTON_PRESS_MASK |
Gdk::Event::BUTTON_RELEASE_MASK |
Gdk::Event::BUTTON_MOTION_MASK |
Gdk::Event::SCROLL_MASK
@xdisp.signal_connect 'realize' do
@xdisp_gc = Gdk::GC.new(@xdisp.window)
@xdisp_gc.set_exposures(true)
end
@xdisp.signal_connect 'expose_event' do |xdisp, event|
imin = (event.area.y / @char_height).to_i
imax = ((event.area.y + event.area.height) / @char_height).to_i
imax += 1 if (event.area.y + event.area.height).to_i % @char_height != 0
imax = [ imax, @vis_lines ].min
render_hex_lines(imin, imax)
end
@xdisp.signal_connect 'scroll_event' do |xdisp, event|
@scrollbar.event(event)
end
@xdisp.signal_connect 'button_press_event' do |xdisp, event|
mouse_handler[xdisp, event]
end
@xdisp.signal_connect 'button_release_event' do |xdisp, event|
mouse_handler[xdisp, event]
end
@xdisp.signal_connect 'motion_notify_event' do |xdisp, event|
_w, x, y, _m = xdisp.window.pointer
if y < 0
@scroll_dir = -1
elsif y >= xdisp.allocation.height
@scroll_dir = 1
else
@scroll_dir = 0
end
if @scroll_dir != 0
if @scroll_timeout == nil
@scroll_timeout = GLib::Timeout.add(SCROLL_TIMEOUT) {
if @scroll_dir < 0
set_cursor([ 0, @cursor_pos - @cpl ].max)
elsif @scroll_dir > 0
set_cursor([ @data.size - 1, @cursor_pos + @cpl ].min)
end
true
}
next
end
else
if @scroll_timeout != nil
GLib::Source.remove @scroll_timeout
@scroll_timeout = nil
end
end
next if event.window != xdisp.window
hex_to_pointer(x,y) if @active_view == View::HEX and @button == 1
end
put @xdisp, 0, 0
@xdisp.show
@adisp = DrawingArea.new
@adisp.modify_font @font_desc
@alayout = @adisp.create_pango_layout('')
@adisp.events =
Gdk::Event::EXPOSURE_MASK |
Gdk::Event::BUTTON_PRESS_MASK |
Gdk::Event::BUTTON_RELEASE_MASK |
Gdk::Event::BUTTON_MOTION_MASK |
Gdk::Event::SCROLL_MASK
@adisp.signal_connect 'realize' do
@adisp_gc = Gdk::GC.new(@adisp.window)
@adisp_gc.set_exposures(true)
end
@adisp.signal_connect 'expose_event' do |adisp, event|
imin = (event.area.y / @char_height).to_i
imax = ((event.area.y + event.area.height) / @char_height).to_i
imax += 1 if (event.area.y + event.area.height).to_i % @char_height != 0
imax = [ imax, @vis_lines ].min
render_ascii_lines(imin, imax)
end
@adisp.signal_connect 'scroll_event' do |adisp, event|
@scrollbar.event(event)
end
@adisp.signal_connect 'button_press_event' do |adisp, event|
mouse_handler[adisp, event]
end
@adisp.signal_connect 'button_release_event' do |adisp, event|
mouse_handler[adisp, event]
end
@adisp.signal_connect 'motion_notify_event' do |adisp, event|
_w, x, y, _m = adisp.window.pointer
if y < 0
@scroll_dir = -1
elsif y >= adisp.allocation.height
@scroll_dir = 1
else
@scroll_dir = 0
end
if @scroll_dir != 0
if @scroll_timeout == nil
@scroll_timeout = GLib::Timeout.add(SCROLL_TIMEOUT) {
if @scroll_dir < 0
set_cursor([ 0, @cursor_pos - @cpl ].max)
elsif @scroll_dir > 0
set_cursor([ @data.size - 1, @cursor_pos + @cpl ].min)
end
true
}
next
end
else
if @scroll_timeout != nil
GLib::Source.remove @scroll_timeout
@scroll_timeout = nil
end
end
next if event.window != adisp.window
ascii_to_pointer(x,y) if @active_view == View::ASCII and @button == 1
end
put @adisp, 0, 0
@adisp.show
@adj = Gtk::Adjustment.new(0, 0, 0, 0, 0, 0)
@scrollbar = Gtk::VScrollbar.new(@adj)
@adj.signal_connect 'value_changed' do |adj|
unless @xdisp_gc.nil? or @adisp_gc.nil? or not @xdisp.drawable? or not @adisp.drawable?
source_min = (adj.value.to_i - @top_line) * @char_height
source_max = source_min + @xdisp.allocation.height
dest_min = 0
dest_max = @xdisp.allocation.height
rect = Gdk::Rectangle.new(0, 0, 0, 0)
@top_line = adj.value.to_i
if source_min < 0
rect.y = 0
rect.height = -source_min
rect_height = [ rect.height, @xdisp.allocation.height ].min
source_min = 0
dest_min = rect.height
else
rect.y = 2 * @xdisp.allocation.height - source_max
rect.y = 0 if rect.y < 0
rect.height = @xdisp.allocation.height - rect.y
source_max = @xdisp.allocation.height
dest_max = rect.y
end
if source_min != source_max
@xdisp.window.draw_drawable(
@xdisp_gc,
@xdisp.window,
0, source_min,
0, dest_min,
@xdisp.allocation.width,
source_max - source_min
)
@adisp.window.draw_drawable(
@adisp_gc,
@adisp.window,
0, source_min,
0, dest_min,
@adisp.allocation.width,
source_max - source_min
)
if @offsets
if @offsets_gc.nil?
@offsets_gc = Gdk::GC.new(@offsets.window)
@offsets_gc.set_exposures(true)
end
@offsets.window.draw_drawable(
@offsets_gc,
@offsets.window,
0, source_min,
0, dest_min,
@offsets.allocation.width,
source_max - source_min
)
end
# TODO update_all_auto_highlights(true, true)
invalidate_all_highlights
rect.width = @xdisp.allocation.width
@xdisp.window.invalidate(rect, false)
rect.width = @adisp.allocation.width
@adisp.window.invalidate(rect, false)
if @offsets
rect.width = @offsets.allocation.width
@offsets.window.invalidate(rect, false)
end
end
end
end
put @scrollbar, 0, 0
@scrollbar.show
end
def set_selection(s, e)
e = [ e, @data.size ].min
@@primary.clear if @selection.start != @selection.end
os, oe = [ @selection.start, @selection.end ].sort
@selection.start = [ 0, s ].max
@selection.start = [ @selection.start, @data.size ].min
@selection.end = [ e, @data.size ].min
invalidate_highlight(@selection)
ns, ne = [ @selection.start, @selection.end ].sort
if ns != os and ne != oe
bytes_changed([ns, os].min, [ne, oe].max)
elsif ne != oe
bytes_changed(*[ne, oe].sort)
elsif ns != os
bytes_changed(*[ns, os].sort)
end
if @selection.start != @selection.end
if @active_view == View::HEX
brk_len = 2 * @cpl + @cpl / @group_type
format_xblock(s,e)
(@disp_buffer.size / brk_len + 1).times do |i| @disp_buffer.insert(i * (brk_len + 1), $/) end
else
brk_len = @cpl
format_ablock(s,e)
end
@@primary.set_text(@disp_buffer)
end
end
def get_selection
[ @selection.start, @selection.end ].sort
end
def clear_selection
set_selection(0, 0)
end
def cursor
@cursor_pos
end
def set_cursor(index)
return if index < 0 or index > @data.size
old_pos = @cursor_pos
index -= 1 if @insert and index == @data.size
index = [ 0, index ].max
hide_cursor
@cursor_pos = index
return if @cpl == 0
y = index / @cpl
if y >= @top_line + @vis_lines
@adj.value = [ y - @vis_lines + 1, @lines - @vis_lines ].min
@adj.value = [ 0, @adj.value ].max
@adj.signal_emit 'value_changed'
elsif y < @top_line
@adj.value = y
@adj.signal_emit 'value_changed'
end
@lower_nibble = false if index == @data.size
if @selecting
set_selection(@selection.start, @cursor_pos)
bytes_changed(*[@cursor_pos, old_pos].sort)
else# @selection.start != @selection.end
s, e = [@selection.start, @selection.end].sort
@selection.end = @selection.start = @cursor_pos
bytes_changed(s, e)
end
self.signal_emit 'cursor_moved'
bytes_changed(old_pos, old_pos)
show_cursor
end
def set_cursor_xy(x, y)
pos = y.to_i * @cpl + x.to_i
return if y < 0 or y >= @lines or x < 0 or x >= @cpl or pos > @data.size
set_cursor(pos)
end
def set_cursor_on_lower_nibble(bool)
if @selecting
bytes_changed(@cursor_pos, @cursor_pos)
@lower_nibble = bool
elsif @selection.start != @selection.end
s, e = [ @selection.start, @selection.end ].sort
@selection.start = @selection.end = 0
bytes_changed(s, e)
@lower_nibble = bool
else
hide_cursor
@lower_nibble = bool
show_cursor
end
end
def set_group_type(type)
hide_cursor
@group_type = type
recalc_displays(self.allocation.width, self.allocation.height)
self.queue_resize
show_cursor
end
def show_offsets(bool)
return unless @show_offsets ^ bool
@show_offsets = bool
if bool
show_offsets_widget
else
hide_offsets_widget
end
end
def set_font(fontname)
@font_desc = Pango::FontDescription.new(fontname)
@disp_font_metrics = load_font(fontname)
@xdisp.modify_font(@font_desc) if @xdisp
@adisp.modify_font(@font_desc) if @adisp
@offsets.modify_font(@font_desc) if @offsets
@char_width = get_max_char_width(@disp_font_metrics)
@char_height = Pango.pixels(@disp_font_metrics.ascent) + Pango.pixels(@disp_font_metrics.descent) + 2
recalc_displays(self.allocation.width, self.allocation.height)
redraw_widget
end
def set_data(data)
prev_data_size = @data.size
@data = data.dup
recalc_displays(self.allocation.width, self.allocation.height)
set_cursor 0
bytes_changed(0, [ prev_data_size, @data.size ].max)
redraw_widget
end
def validate_highlight(hl)
unless hl.valid
hl.start_line = [ hl.start, hl.end ].min / @cpl - @top_line
hl.end_line = [ hl.start, hl.end ].max / @cpl - @top_line
hl.valid = true
end
end
def invalidate_highlight(hl)
hl.valid = false
end
def invalidate_all_highlights
@highlights.each do |hl| invalidate_highlight(hl) end
end
private
signal_new(
'data_changed',
GLib::Signal::RUN_FIRST,
nil,
nil,
String
)
signal_new(
'cursor_moved',
GLib::Signal::RUN_FIRST,
nil,
nil
)
def signal_do_cursor_moved
end
def signal_do_data_changed(data)
# TODO
end
def signal_do_realize
super
self.window.set_back_pixmap(nil, true)
end
def signal_do_size_allocate(alloc)
hide_cursor
recalc_displays(alloc.width, alloc.height)
self.set_allocation(alloc.x, alloc.y, alloc.width, alloc.height)
self.window.move_resize(
alloc.x, alloc.y,
alloc.width, alloc.height
) if self.realized?
bw = self.border_width
xt = widget_get_xt
yt = widget_get_yt
my_alloc = Gtk::Allocation.new(0, 0, 0, 0)
my_alloc.x = bw + xt
my_alloc.y = bw + yt
my_alloc.height = [ alloc.height - 2*bw - 2*yt, 1 ].max
if @show_offsets
my_alloc.width = 8 * @char_width
@offsets.size_allocate(my_alloc)
@offsets.queue_draw
my_alloc.x += 2*xt + my_alloc.width
end
my_alloc.width = @xdisp_width
@xdisp.size_allocate(my_alloc)
my_alloc.x = alloc.width - bw - @scrollbar.requisition[0]
my_alloc.y = bw
my_alloc.width = @scrollbar.requisition[0]
my_alloc.height = [ alloc.height - 2*bw, 1 ].max
@scrollbar.size_allocate(my_alloc)
my_alloc.x -= @adisp_width + xt
my_alloc.y = bw + yt
my_alloc.width = @adisp_width
my_alloc.height = [ alloc.height - 2*bw - 2*yt, 1 ].max
@adisp.size_allocate(my_alloc)
show_cursor
end
def signal_do_size_request(req)
sb_width, _sb_height = @scrollbar.size_request
bw = self.border_width
xt, yt = widget_get_xt, widget_get_yt
width = 4*xt + 2*bw + sb_width +
@char_width*(DEFAULT_CPL + (DEFAULT_CPL-1)/@group_type)
width += 2*xt + 8*@char_width if @show_offsets
height = DEFAULT_LINES * @char_height + 2*yt + 2*bw
req[0] = width
req[1] = height
end
def signal_do_expose_event(event)
draw_shadow(event.area)
super(event)
true
end
def signal_do_key_press_event(event)
hide_cursor
@selecting = (event.state & Gdk::Window::SHIFT_MASK) != 0
ret = true
case event.keyval
when Gdk::Keyval::GDK_KP_Tab, Gdk::Keyval::GDK_Tab
@active_view = (@active_view == View::HEX) ? View::ASCII : View::HEX
when Gdk::Keyval::GDK_Up
set_cursor(@cursor_pos - @cpl)
when Gdk::Keyval::GDK_Down
set_cursor(@cursor_pos + @cpl)
when Gdk::Keyval::GDK_Page_Up
set_cursor([0, @cursor_pos - @vis_lines * @cpl].max)
when Gdk::Keyval::GDK_Page_Down
set_cursor([@cursor_pos + @vis_lines * @cpl, @data.size].min)
when Gdk::Keyval::GDK_Left
if @active_view == View::HEX
if @selecting
set_cursor(@cursor_pos - 1)
else
@lower_nibble ^= 1
set_cursor(@cursor_pos - 1) if @lower_nibble
end
else
set_cursor(@cursor_pos - 1)
end
when Gdk::Keyval::GDK_Right
if @active_view == View::HEX
if @selecting
set_cursor(@cursor_pos + 1)
else
@lower_nibble ^= 1
set_cursor(@cursor_pos + 1) unless @lower_nibble
end
else
set_cursor(@cursor_pos + 1)
end
when Gdk::Keyval::GDK_c, Gdk::Keyval::GDK_C
if event.state & Gdk::Window::CONTROL_MASK != 0
s,e = @selection.start, @selection.end + 1
if @active_view == View::HEX
brk_len = 2 * @cpl + @cpl / @group_type
format_xblock(s,e)
(@disp_buffer.size / brk_len + 1).times do |i| @disp_buffer.insert(i * (brk_len + 1), $/) end
else
brk_len = @cpl
format_ablock(s,e)
end
@@clipboard.set_text(@disp_buffer)
end
else
ret = false
end
show_cursor
ret
end
def hex_to_pointer(mx, my)
cy = @top_line + my.to_i / @char_height
cx = x = 0
while cx < 2 * @cpl
x += @char_width
if x > mx
set_cursor_xy(cx / 2, cy)
set_cursor_on_lower_nibble(cx % 2 != 0)
cx = 2 * @cpl
end
cx += 1
x += @char_width if ( cx % (2 * @group_type) == 0 )
end
end
def ascii_to_pointer(mx, my)
cx = mx / @char_width
cy = @top_line + my / @char_height
set_cursor_xy(cx, cy)
end
def load_font(fontname)
desc = Pango::FontDescription.new(fontname)
context = Gdk::Pango.context
context.set_language(Gtk.default_language)
font = context.load_font(desc)
font.metrics(context.language)
end
def draw_shadow(area)
bw = self.border_width
x = bw
xt = widget_get_xt
if @show_offsets
self.style.paint_shadow(
self.window,
Gtk::STATE_NORMAL, Gtk::SHADOW_IN,
nil, self, nil,
bw, bw,
8*@char_width + 2*xt, self.allocation.height - 2*bw
)
x += 8*@char_width + 2*xt
end
self.style.paint_shadow(
self.window,
Gtk::STATE_NORMAL, Gtk::SHADOW_IN,
nil, self, nil,
x, bw,
@xdisp_width + 2*xt, self.allocation.height - 2*bw
)
self.style.paint_shadow(
self.window,
Gtk::STATE_NORMAL, Gtk::SHADOW_IN,
nil, self, nil,
self.allocation.width - bw - @adisp_width - @scrollbar.requisition[0] - 2*xt, bw,
@adisp_width + 2*xt, self.allocation.height - 2*bw
)
end
def redraw_widget
return unless self.realized?
self.window.invalidate(nil, false)
end
def widget_get_xt
self.style.xthickness
end
def widget_get_yt
self.style.ythickness
end
def recalc_displays(width, height)
old_cpl = @cpl
w, _h = @scrollbar.size_request
@xdisp_width = 1
@adisp_width = 1
total_width = width - 2 * self.border_width - 4 * widget_get_xt - w
total_width -= 2 * widget_get_xt + 8 * @char_width if @show_offsets
total_cpl = total_width / @char_width
if total_cpl == 0 or total_width < 0
@cpl = @lines = @vis_lines = 0
return
end
@cpl = 0
begin
break if @cpl % @group_type == 0 and total_cpl < @group_type * 3
@cpl += 1
total_cpl -= 3
total_cpl -= 1 if @cpl % @group_type == 0
end while total_cpl > 0
return if @cpl == 0
if @data.empty?
@lines = 1
else
@lines = @data.size / @cpl
@lines += 1 if @data.size % @cpl != 0
end
@vis_lines = (height - 2*self.border_width - 2*widget_get_yt).to_i / @char_height.to_i
@adisp_width = @cpl * @char_width + 1
xcpl = @cpl * 2 + (@cpl - 1) / @group_type
@xdisp_width = xcpl * @char_width + 1
@disp_buffer = ''
@adj.value = [@top_line * old_cpl / @cpl, @lines - @vis_lines].min
@adj.value = [ 0, @adj.value ].max
if @cursor_pos / @cpl < @adj.value or @cursor_pos / @cpl > @adj.value + @vis_lines - 1
@adj.value = [ @cursor_pos / @cpl, @lines - @vis_lines ].min
@adj.value = [ 0, @adj.value ].max
end
@adj.lower = 0
@adj.upper = @lines
@adj.step_increment = 1
@adj.page_increment = @vis_lines - 1
@adj.page_size = @vis_lines
@adj.signal_emit 'changed'
@adj.signal_emit 'value_changed'
end
def get_max_char_width(metrics)
layout = self.create_pango_layout('')
layout.set_font_description(@font_desc)
char_widths = [ 0 ]
(1..100).each do |i|
logical_rect = Pango::Rectangle.new(0, 0, 0, 0)
if is_displayable(i.chr)
layout.set_text(i.chr)
logical_rect = layout.pixel_extents[1]
end
char_widths << logical_rect.width
end
char_widths[48..122].max
end
def show_cursor
unless @cursor_shown
if @xdisp_gc and @adisp_gc and @xdisp.realized? and @adisp.realized?
render_xc
render_ac
end
@cursor_shown = true
end
end
def hide_cursor
if @cursor_shown
if @xdisp_gc and @adisp_gc and @xdisp.realized? and @adisp.realized?
render_byte(@cursor_pos)
end
@cursor_shown = false
end
end
def show_offsets_widget
@offsets = DrawingArea.new
@offsets.modify_font @font_desc
@olayout = @offsets.create_pango_layout('')
@offsets.events = Gdk::Event::EXPOSURE_MASK
@offsets.signal_connect 'expose_event' do |offsets, event|
imin = (event.area.y / @char_height).to_i
imax = ((event.area.y + event.area.height) / @char_height).to_i
imax += 1 if (event.area.y + event.area.height).to_i % @char_height != 0
imax = [ imax, @vis_lines ].min
render_offsets(imin, imax)
end
put @offsets, 0, 0
@offsets.show
end
def hide_offsets_widget
if @offsets
self.remove(@offsets)
@offsets = @offsets_gc = nil
end
end
def is_displayable(c)
c = c.ord
c >= 0x20 and c < 0x7f
end
def bytes_changed(s, e)
start_line = s / @cpl - @top_line
end_line = e / @cpl - @top_line
return if end_line < 0 or start_line > @vis_lines
start_line = [ 0, start_line ].max
render_hex_lines(start_line, end_line)
render_ascii_lines(start_line, end_line)
render_offsets(start_line, end_line) if @show_offsets
end
def render_hex_highlights(cursor_line)
xcpl = @cpl * 2 + @cpl / @group_type
@highlights.each do |hl|
next if (hl.start - hl.end).abs < hl.min_select
validate_highlight(hl)
s, e = [ hl.start, hl.end ].sort
sl, el = hl.start_line, hl.end_line
hl.style.attach(@xdisp.window) if hl.style
state = (@active_view == View::HEX) ? Gtk::STATE_SELECTED : Gtk::STATE_INSENSITIVE
if cursor_line == sl
cursor_off = 2 * (s % @cpl) + (s % @cpl) / @group_type
if cursor_line == el
len = 2 * (e % @cpl + 1) + (e % @cpl) / @group_type
else
len = xcpl
end
len -= cursor_off
(hl.style || self.style).paint_flat_box(
@xdisp.window,
state, Gtk::SHADOW_NONE,
nil, @xdisp, '',
cursor_off * @char_width, cursor_line * @char_height,
len * @char_width, @char_height
) if len > 0
elsif cursor_line == el
cursor_off = 2 * (e % @cpl + 1) + (e % @cpl) / @group_type
(hl.style || self.style).paint_flat_box(
@xdisp.window,
state, Gtk::SHADOW_NONE,
nil, @xdisp, '',
0, cursor_line * @char_height,
cursor_off * @char_width, @char_height
) if cursor_off > 0
elsif cursor_line > sl and cursor_line < el
(hl.style || self.style).paint_flat_box(
@xdisp.window,
state, Gtk::SHADOW_NONE,
nil, @xdisp, '',
0, cursor_line * @char_height,
xcpl * @char_width, @char_height
)
end
hl.style.attach(@adisp.window) if hl.style
end
end
def render_hex_lines(imin, imax)
return unless self.realized? and @cpl != 0
cursor_line = @cursor_pos / @cpl - @top_line
@xdisp_gc.set_foreground(self.style.base(Gtk::STATE_NORMAL))
@xdisp.window.draw_rectangle(
@xdisp_gc,
true,
0,
imin * @char_height,
@xdisp.allocation.width,
(imax - imin + 1) * @char_height
)
imax = [ imax, @vis_lines, @lines ].min
@xdisp_gc.set_foreground(self.style.text(Gtk::STATE_NORMAL))
frm_len = format_xblock((@top_line+imin) * @cpl, [(@top_line+imax+1) * @cpl, @data.size].min)
tmp = nil
xcpl = @cpl*2 + @cpl/@group_type
(imin..imax).each do |i|
return unless (tmp = frm_len - ((i - imin) * xcpl)) > 0
render_hex_highlights(i)
text = @disp_buffer[(i-imin) * xcpl, [xcpl, tmp].min]
@xlayout.set_text(text)
@xdisp.window.draw_layout(@xdisp_gc, 0, i * @char_height, @xlayout)
end
render_xc if cursor_line >= imin and cursor_line <= imax and @cursor_shown
end
def render_ascii_highlights(cursor_line)
@highlights.each do |hl|
next if (hl.start - hl.end).abs < hl.min_select
validate_highlight(hl)
s, e = [ hl.start, hl.end ].sort
sl, el = hl.start_line, hl.end_line
hl.style.attach(@adisp.window) if hl.style
state = (@active_view == View::ASCII) ? Gtk::STATE_SELECTED : Gtk::STATE_INSENSITIVE
if cursor_line == sl
cursor_off = s % @cpl
len =
if cursor_line == el
e - s + 1
else
@cpl - cursor_off
end
(hl.style || self.style).paint_flat_box(
@adisp.window,
state, Gtk::SHADOW_NONE,
nil, @adisp, '',
cursor_off * @char_width, cursor_line * @char_height,
len * @char_width, @char_height
) if len > 0
elsif cursor_line == el
cursor_off = e % @cpl + 1
(hl.style || self.style).paint_flat_box(
@adisp.window,
state, Gtk::SHADOW_NONE,
nil, @adisp, '',
0, cursor_line * @char_height,
cursor_off * @char_width, @char_height
) if cursor_off > 0
elsif cursor_line > sl and cursor_line < el
(hl.style || self.style).paint_flat_box(
@adisp.window,
state, Gtk::SHADOW_NONE,
nil, @adisp, '',
0, cursor_line * @char_height,
@cpl * @char_width, @char_height
)
end
hl.style.attach(@adisp.window) if hl.style
end
end
def render_ascii_lines(imin, imax)
return unless self.realized? and @cpl != 0
cursor_line = @cursor_pos / @cpl - @top_line
@adisp_gc.set_foreground(self.style.base(Gtk::STATE_NORMAL))
@adisp.window.draw_rectangle(
@adisp_gc,
true,
0,
imin * @char_height,
@adisp.allocation.width,
(imax - imin + 1) * @char_height
)
imax = [ imax, @vis_lines, @lines ].min
@adisp_gc.set_foreground(self.style.text(Gtk::STATE_NORMAL))
frm_len = format_ablock((@top_line+imin) * @cpl, [(@top_line+imax+1) * @cpl, @data.size].min)
tmp = nil
(imin..imax).each do |i|
return unless (tmp = frm_len - ((i - imin) * @cpl)) > 0
render_ascii_highlights(i)
text = @disp_buffer[(i-imin) * @cpl, [@cpl, tmp].min]
@alayout.set_text(text)
@adisp.window.draw_layout(@adisp_gc, 0, i * @char_height, @alayout)
end
render_ac if cursor_line >= imin and cursor_line <= imax and @cursor_shown
end
def render_offsets(imin, imax)
return unless self.realized?
unless @offsets_gc
@offsets_gc = Gdk::GC.new(@offsets.window)
@offsets_gc.set_exposures(true)
end
@offsets_gc.set_foreground(self.style.base(Gtk::STATE_INSENSITIVE))
@offsets.window.draw_rectangle(
@offsets_gc,
true,
0, imin * @char_height,
@offsets.allocation.width, (imax - imin + 1) * @char_height
)
imax = [ imax, @vis_lines, @lines - @top_line - 1 ].min
@offsets_gc.set_foreground(self.style.text(Gtk::STATE_NORMAL))
(imin..imax).each do |i|
text = "%08x" % ((@top_line + i) * @cpl + @starting_offset)
@olayout.set_text(text)
@offsets.window.draw_layout(@offsets_gc, 0, i * @char_height, @olayout)
end
end
def render_byte(pos)
return unless @xdisp_gc and @adisp_gc and @xdisp.realized? and @adisp.realized?
return unless (coords = get_xcoords(pos))
cx, cy = coords
c = format_xbyte(pos)
@xdisp_gc.set_foreground(self.style.base(Gtk::STATE_NORMAL))
@xdisp.window.draw_rectangle(
@xdisp_gc,
true,
cx, cy,
2 * @char_width, @char_height
)
if pos < @data.size
@xdisp_gc.set_foreground(self.style.text(Gtk::STATE_NORMAL))
@xlayout.set_text(c)
@xdisp.window.draw_layout(@xdisp_gc, cx, cy, @xlayout)
end
return unless (coords = get_acoords(pos))
cx, cy = coords
@adisp_gc.set_foreground(self.style.base(Gtk::STATE_NORMAL))
@adisp.window.draw_rectangle(
@adisp_gc,
true,
cx, cy,
@char_width, @char_height
)
if pos < @data.size
@adisp_gc.set_foreground(self.style.text(Gtk::STATE_NORMAL))
c = get_byte(pos)
c = '.' unless is_displayable(c)
@alayout.set_text(c)
@adisp.window.draw_layout(@adisp_gc, cx, cy, @alayout)
end
end
def render_xc
return unless @xdisp.realized?
if coords = get_xcoords(@cursor_pos)
cx, cy = coords
c = format_xbyte(@cursor_pos)
if @lower_nibble
cx += @char_width
c = c[1,1]
else
c = c[0,1]
end
@xdisp_gc.set_foreground(self.style.base(Gtk::STATE_ACTIVE))
@xdisp.window.draw_rectangle(
@xdisp_gc,
(@active_view == View::HEX),
cx, cy,
@char_width,
@char_height - 1
)
@xdisp_gc.set_foreground(self.style.text(Gtk::STATE_ACTIVE))
@xlayout.set_text(c)
@xdisp.window.draw_layout(@xdisp_gc, cx, cy, @xlayout)
end
end
def render_ac
return unless @adisp.realized?
if coords = get_acoords(@cursor_pos)
cx, cy = coords
c = get_byte(@cursor_pos)
c = '.' unless is_displayable(c)
@adisp_gc.set_foreground(self.style.base(Gtk::STATE_ACTIVE))
@adisp.window.draw_rectangle(
@adisp_gc,
(@active_view == View::ASCII),
cx, cy,
@char_width,
@char_height - 1
)
@adisp_gc.set_foreground(self.style.text(Gtk::STATE_ACTIVE))
@alayout.set_text(c)
@adisp.window.draw_layout(@adisp_gc, cx, cy, @alayout)
end
end
def get_xcoords(pos)
return nil if @cpl == 0
cy = pos / @cpl - @top_line
return nil if cy < 0
cx = 2 * (pos % @cpl)
spaces = (pos % @cpl) / @group_type
cx *= @char_width
cy *= @char_height
spaces *= @char_width
[cx + spaces, cy]
end
def get_acoords(pos)
return nil if @cpl == 0
cy = pos / @cpl - @top_line
return nil if cy < 0
cy *= @char_height
cx = @char_width * (pos % @cpl)
[cx, cy]
end
def format_xblock(s, e)
@disp_buffer = ''
(s+1..e).each do |i|
@disp_buffer << get_byte(i - 1).unpack('H2')[0]
@disp_buffer << ' ' if i % @group_type == 0
end
@disp_buffer.size
end
def format_ablock(s, e)
@disp_buffer = ''
(s..e-1).each do |i|
c = get_byte(i)
c = '.' unless is_displayable(c)
@disp_buffer << c
end
@disp_buffer.size
end
def get_byte(offset)
if offset >= 0 and offset < @data.size
@data[offset, 1]
else
0.chr
end
end
def format_xbyte(pos)
get_byte(pos).unpack('H2')[0]
end
end
end
__END__
hexedit = Gtk::HexEditor.new(File.read '/bin/cat')
hexedit.show_offsets(true)
hexedit.set_cursor 2
hexedit.set_cursor_on_lower_nibble true
hexedit.set_font 'Terminus 12'
hexedit.set_group_type Gtk::HexEditor::Group::LONG
window = Gtk::Window.new
window.add(hexedit)
window.show_all
Gtk.main
origami-2.0.0/bin/gui/imgview.rb 0000644 0000041 0000041 00000003716 12757133666 016547 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class ImgViewer < Window
attr_reader :image
def initialize
super()
set_title "Image view"
set_decorated false
set_resizable false
add_events(Gdk::Event::KEY_RELEASE_MASK)
signal_connect('key_release_event') { |w, event|
destroy if event.keyval == Gdk::Keyval::GDK_Escape
}
end
def show_raw_img(data, w, h, bpc, bpr)
set_default_size w,h
pixbuf = GdkPixbuf::Pixbuf.new data: data,
colorspace: GdkPixbuf::Colorspace::RGB,
has_alpha: false,
bits_per_sample: bpc,
width: w, height: h,
row_stride: bpr
@image = Gtk::Image.new(pixbuf)
add @image
show_all
end
def show_compressed_img(data)
loader = Gdk::PixbufLoader.new
loader.last_write data
pixbuf = loader.pixbuf
set_default_size pixbuf.width, pixbuf.height
@image = Gtk::Image.new(pixbuf)
add @image
show_all
end
end
end
origami-2.0.0/bin/gui/about.rb 0000644 0000041 0000041 00000002313 12757133666 016202 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class Walker < Window
def about
AboutDialog.show(self,
name: "PDF Walker",
program_name: "PDF Walker",
version: Origami::VERSION,
copyright: "Copyright (C) 2016\nGuillaume Delugré",
comments: "A graphical PDF parser front-end",
license: File.read(File.join(__dir__, "COPYING"))
)
end
end
end
origami-2.0.0/bin/gui/textview.rb 0000644 0000041 0000041 00000005656 12757133666 016764 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class Walker < Window
private
def create_objectview
@objectview = ObjectView.new(self)
end
class ObjectView < Notebook
attr_reader :parent
attr_reader :pdfpanel, :valuepanel
def initialize(parent)
@parent = parent
super()
@pdfbuffer = TextBuffer.new
@pdfview = TextView.new(@pdfbuffer).set_editable(false).set_cursor_visible(false).set_left_margin(5)
@pdfpanel = ScrolledWindow.new.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
@pdfpanel.add_with_viewport @pdfview
append_page(@pdfpanel, Label.new("PDF Code"))
@pdfbuffer.create_tag("Default",
weight: Pango::WEIGHT_BOLD,
family: "monospace",
scale: Pango::AttrScale::LARGE
)
end
def load(object)
begin
self.clear
case object
when Origami::PDF::Header, Origami::FDF::Header, Origami::PPKLite::Header
text = object.to_s
@pdfbuffer.set_text(text)
@pdfbuffer.apply_tag("Default", @pdfbuffer.start_iter, @pdfbuffer.end_iter)
when Origami::Object
if object.is_a?(Origami::Stream)
text = [ "#{object.no} #{object.generation} obj", object.dictionary ].join($/)
else
text = object.to_s
end
text.encode!("UTF-8", replace: '.')
.gsub!("\x00", '.')
@pdfbuffer.set_text(text)
@pdfbuffer.apply_tag("Default", @pdfbuffer.start_iter, @pdfbuffer.end_iter)
end
rescue
@parent.error("An error occured while loading this object.\n#{$!} (#{$!.class})")
end
end
def clear
@pdfbuffer.set_text("")
end
end
end
end
origami-2.0.0/bin/gui/properties.rb 0000644 0000041 0000041 00000011412 12757133666 017264 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
require 'digest/md5'
module PDFWalker
class Walker < Window
def display_file_properties
Properties.new(self, @opened) if @opened
end
class Properties < Dialog
@@acrobat_versions =
{
1.0 => "1.x",
1.1 => "2.x",
1.2 => "3.x",
1.3 => "4.x",
1.4 => "5.x",
1.5 => "6.x",
1.6 => "7.x",
1.7 => "8.x / 9.x / 10.x"
}
def initialize(parent, pdf)
super("Document properties", parent, Dialog::MODAL, [Stock::CLOSE, Dialog::RESPONSE_NONE])
docframe = Frame.new(" File properties ")
stat = File.stat(parent.filename)
creation_date = stat.ctime.to_s.encode("utf-8", :invalid => :replace, :undef => :replace)
last_modified = stat.mtime.to_s.encode("utf-8", :invalid => :replace, :undef => :replace)
md5sum = Digest::MD5.hexdigest(File.binread(parent.filename))
labels =
[
[ "Filename:", parent.filename ],
[ "File size:", "#{File.size(parent.filename)} bytes" ],
[ "MD5:", md5sum ],
[ "Read-only:", "#{not stat.writable?}" ],
[ "Creation date:", creation_date ],
[ "Last modified:", last_modified ]
]
doctable = Table.new(labels.size + 1, 3)
row = 0
labels.each do |name, value|
doctable.attach(Label.new(name).set_alignment(1,0), 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
doctable.attach(Label.new(value).set_alignment(0,0), 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
docframe.border_width = 5
docframe.shadow_type = Gtk::SHADOW_IN
docframe.add(doctable)
pdfframe = Frame.new(" PDF properties ")
pdf_version = pdf.header.to_f
if pdf_version >= 1.0 and pdf_version <= 1.7
acrobat_version = @@acrobat_versions[pdf_version]
else
acrobat_version = "unknown version"
end
labels =
[
[ "Version:", "#{pdf_version} (Acrobat #{acrobat_version})" ],
[ "Number of revisions:", "#{pdf.revisions.size}" ],
[ "Number of indirect objects:", "#{pdf.indirect_objects.size}" ],
[ "Number of pages:", "#{pdf.pages.count}" ],
[ "Linearized:", pdf.linearized? ? 'yes' : 'no' ],
[ "Encrypted:", pdf.encrypted? ? 'yes' : 'no' ],
[ "Signed:", pdf.signed? ? 'yes' : 'no' ],
[ "Has usage rights:", pdf.usage_rights? ? 'yes' : 'no' ],
[ "Form:", pdf.form? ? 'yes' : 'no' ],
[ "XFA form:", pdf.xfa_form? ? 'yes' : 'no' ],
[ "Document information:", pdf.document_info? ? 'yes' : 'no' ],
[ "Metadata:", pdf.metadata? ? 'yes' : 'no' ]
]
pdftable = Table.new(labels.size + 1, 3)
row = 0
labels.each do |name, value|
pdftable.attach(Label.new(name).set_alignment(1,0), 0, 1, row, row + 1, Gtk::FILL, Gtk::SHRINK, 4, 4)
pdftable.attach(Label.new(value).set_alignment(0,0), 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
pdfframe.border_width = 5
pdfframe.shadow_type = Gtk::SHADOW_IN
pdfframe.add(pdftable)
vbox.add(docframe)
vbox.add(pdfframe)
signal_connect('response') { destroy }
show_all
end
end
end
end
origami-2.0.0/bin/gui/file.rb 0000644 0000041 0000041 00000036252 12757133666 016020 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
require 'origami'
module PDFWalker
class Walker < Window
attr_reader :opened
attr_reader :explore_history
def close
@opened = nil
@filename = ''
@explorer_history.clear
@treeview.clear
@objectview.clear
@hexview.clear
# disable all menus.
[
@file_menu_close, @file_menu_saveas, @file_menu_serialize, @file_menu_refresh,
@document_menu_search,
@document_menu_gotocatalog, @document_menu_gotodocinfo, @document_menu_gotometadata,
@document_menu_gotopage, @document_menu_gotofield, @document_menu_gotorev, @document_menu_gotoobj,
@document_menu_properties, @document_menu_sign, @document_menu_ur
].each do |menu|
menu.sensitive = false
end
@statusbar.pop(@main_context)
GC.start
end
def open(filename = nil)
dialog = Gtk::FileChooserDialog.new("Open PDF File",
self,
FileChooser::ACTION_OPEN,
nil,
[Stock::CANCEL, Dialog::RESPONSE_CANCEL],
[Stock::OPEN, Dialog::RESPONSE_ACCEPT])
last_file = @config.recent_files.first
unless last_file.nil?
last_folder = File.dirname(last_file)
dialog.set_current_folder(last_folder) if File.directory?(last_folder)
end
dialog.filter = FileFilter.new.add_pattern("*.acrodata").add_pattern("*.pdf").add_pattern("*.fdf")
if filename.nil? and dialog.run != Gtk::Dialog::RESPONSE_ACCEPT
dialog.destroy
return
end
create_progressbar
filename ||= dialog.filename
dialog.destroy
begin
if @help_menu_profile.active?
require 'ruby-prof'
RubyProf.start
end
target = parse_file(filename)
if @help_menu_profile.active?
result = RubyProf.stop
multiprinter = RubyProf::MultiPrinter.new(result)
Dir.mkdir(@config.profile_output_dir) unless Dir.exists?(@config.profile_output_dir)
multiprinter.print(path: @config.profile_output_dir, profile: File.basename(filename))
end
if target
close if @opened
@opened = target
@filename = filename
@config.last_opened_file(filename)
@config.save
update_recent_menu
@last_search_result = []
@last_search =
{
:expr => "",
:regexp => false,
:type => :body
}
self.reload
# Enable basic file menus.
[
@file_menu_close, @file_menu_refresh,
].each do |menu|
menu.sensitive = true
end
@explorer_history.clear
@statusbar.push(@main_context, "Viewing #{filename}")
if @opened.is_a?(Origami::PDF)
# Enable save and document menu.
[
@file_menu_saveas, @file_menu_serialize,
@document_menu_search,
@document_menu_gotocatalog, @document_menu_gotopage, @document_menu_gotorev, @document_menu_gotoobj,
@document_menu_properties, @document_menu_sign, @document_menu_ur
].each do |menu|
menu.sensitive = true
end
@document_menu_gotodocinfo.sensitive = true if @opened.document_info?
@document_menu_gotometadata.sensitive = true if @opened.metadata?
@document_menu_gotofield.sensitive = true if @opened.form?
page_menu = Menu.new
@document_menu_gotopage.remove_submenu
@opened.each_page.with_index(1) do |page, index|
page_menu.append(item = MenuItem.new(index.to_s).show)
item.signal_connect("activate") do @treeview.goto(page) end
end
@document_menu_gotopage.set_submenu(page_menu)
field_menu = Menu.new
@document_menu_gotofield.remove_submenu
@opened.each_field do |field|
field_name = field.T || ""
field_menu.append(item = MenuItem.new(field_name).show)
item.signal_connect("activate") do @treeview.goto(field) end
end
@document_menu_gotofield.set_submenu(field_menu)
rev_menu = Menu.new
@document_menu_gotorev.remove_submenu
rev_index = 1
@opened.revisions.each do |rev|
rev_menu.append(item = MenuItem.new(rev_index.to_s).show)
item.signal_connect("activate") do @treeview.goto(rev) end
rev_index = rev_index + 1
end
@document_menu_gotorev.set_submenu(rev_menu)
goto_catalog
end
end
rescue
error("Error while parsing file.\n#{$!} (#{$!.class})\n" + $!.backtrace.join("\n"))
end
close_progressbar
self.activate_focus
end
def deserialize
dialog = Gtk::FileChooserDialog.new("Open dump file",
self,
FileChooser::ACTION_OPEN,
nil,
[Stock::CANCEL, Dialog::RESPONSE_CANCEL],
[Stock::OPEN, Dialog::RESPONSE_ACCEPT]
)
dialog.current_folder = File.join(Dir.pwd, "dumps")
dialog.filter = FileFilter.new.add_pattern("*.gz")
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
close if @opened
filename = dialog.filename
begin
@opened = Origami::PDF.deserialize(filename)
self.reload
[
@file_menu_close, @file_menu_saveas, @file_menu_serialize, @file_menu_refresh,
@document_menu_search,
@document_menu_gotocatalog, @document_menu_gotopage, @document_menu_gotorev, @document_menu_gotoobj,
@document_menu_properties, @document_menu_sign, @document_menu_ur
].each do |menu|
menu.sensitive = true
end
@document_menu_gotodocinfo.sensitive = true if @opened.document_info?
@document_menu_gotometadata.sensitive = true if @opened.metadata?
@document_menu_gotofield.sensitive = true if @opened.form?
@explorer_history.clear
@statusbar.push(@main_context, "Viewing dump of #{filename}")
rescue
error("This file cannot be loaded.\n#{$!} (#{$!.class})")
end
end
dialog.destroy
end
def serialize
dialog = Gtk::FileChooserDialog.new("Save dump file",
self,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.do_overwrite_confirmation = true
dialog.current_folder = File.join(Dir.pwd, "dumps")
dialog.current_name = "#{File.basename(@filename)}.dmp.gz"
dialog.filter = FileFilter.new.add_pattern("*.gz")
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
begin
@opened.serialize(dialog.filename)
rescue
error("Error: #{$!.message}")
end
end
dialog.destroy
end
def save_data(caption, data, filename = "")
dialog = Gtk::FileChooserDialog.new(caption,
self,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.do_overwrite_confirmation = true
dialog.current_name = File.basename(filename)
dialog.filter = FileFilter.new.add_pattern("*.*")
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
begin
File.binwrite(dialog.filename, data)
rescue
error("Error: #{$!.message}")
end
end
dialog.destroy
end
def save
dialog = Gtk::FileChooserDialog.new("Save PDF file",
self,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.filter = FileFilter.new.add_pattern("*.acrodata").add_pattern("*.pdf").add_pattern("*.fdf")
folder = File.dirname(@filename)
dialog.set_current_folder(folder)
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
begin
@opened.save(dialog.filename)
rescue
error("#{$!.class}: #{$!.message}\n#{$!.backtrace.join($/)}")
end
end
dialog.destroy
end
def save_dot
dialog = Gtk::FileChooserDialog.new("Save dot file",
self,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.filter = FileFilter.new.add_pattern("*.dot")
folder = File.dirname(@filename)
dialog.set_current_folder(folder)
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
begin
@opened.export_to_graph(dialog.filename)
rescue
error("Error: #{$!.message}")
end
end
dialog.destroy
end
def save_graphml
dialog = Gtk::FileChooserDialog.new("Save GraphML file",
self,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.filter = FileFilter.new.add_pattern("*.graphml")
folder = File.dirname(@filename)
dialog.set_current_folder(folder)
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
begin
@opened.export_to_graphml(dialog.filename)
rescue
error("Error: #{$!.message}")
end
end
dialog.destroy
end
private
def parse_file(path)
update_bar = lambda { |obj|
@progressbar.pulse if @progressbar
Gtk.main_iteration while Gtk.events_pending?
}
prompt_passwd = lambda {
passwd = ""
dialog = Gtk::Dialog.new(
"This document is encrypted",
nil,
Gtk::Dialog::MODAL,
[ Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK ],
[ Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL ]
)
dialog.set_default_response(Gtk::Dialog::RESPONSE_OK)
label = Gtk::Label.new("Please enter password:")
entry = Gtk::Entry.new
entry.signal_connect('activate') {
dialog.response(Gtk::Dialog::RESPONSE_OK)
}
dialog.vbox.add(label)
dialog.vbox.add(entry)
dialog.show_all
dialog.run do |response|
if response == Gtk::Dialog::RESPONSE_OK
passwd = entry.text
end
end
dialog.destroy
return passwd
}
#
# Try to detect the file type of the document.
# Fallback to PDF if none is found.
#
file_type = detect_file_type(path)
if file_type.nil?
file_type = Origami::PDF
force_mode = true
else
force_mode = false
end
file_type.read(path,
verbosity: Origami::Parser::VERBOSE_TRACE,
ignore_errors: false,
callback: update_bar,
prompt_password: prompt_passwd,
force: force_mode
)
end
def detect_file_type(path)
supported_types = [ Origami::PDF, Origami::FDF, Origami::PPKLite ]
File.open(path, 'rb') do |file|
data = file.read(128)
supported_types.each do |type|
return type if data.match(type::Header::MAGIC)
end
end
nil
end
def create_progressbar
@progresswin = Dialog.new("Parsing file...", self, Dialog::MODAL)
@progresswin.vbox.add(@progressbar = ProgressBar.new.set_pulse_step(0.05))
@progresswin.show_all
end
def close_progressbar
@progresswin.close
end
end
end
origami-2.0.0/bin/gui/config.rb 0000644 0000041 0000041 00000006614 12757133666 016345 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
require 'origami'
require 'yaml'
module PDFWalker
class Walker < Window
class Config
DEFAULT_CONFIG_FILE = "#{File.expand_path("~")}/.pdfwalker.conf.yml"
DEFAULT_CONFIG =
{
"Debug" =>
{
"Profiling" => false,
"ProfilingOutputDir" => "prof",
"Verbosity" => Origami::Parser::VERBOSE_TRACE,
"IgnoreFileHeader" => true
},
"UI" =>
{
"LastOpenedDocuments" => []
}
}
NLOG_RECENT_FILES = 5
def initialize(configfile = DEFAULT_CONFIG_FILE)
begin
@conf = YAML.load(File.open(configfile)) or DEFAULT_CONFIG
rescue
ensure
@filename = configfile
set_missing_values
end
end
def last_opened_file(filepath)
@conf["UI"]['LastOpenedDocuments'].push(filepath).uniq!
@conf["UI"]['LastOpenedDocuments'].delete_at(0) while @conf["UI"]['LastOpenedDocuments'].size > NLOG_RECENT_FILES
save
end
def recent_files(n = NLOG_RECENT_FILES)
@conf["UI"]['LastOpenedDocuments'].last(n).reverse
end
def set_profiling(bool)
@conf["Debug"]['Profiling'] = bool
save
end
def profile?
@conf["Debug"]['Profiling']
end
def profile_output_dir
@conf["Debug"]['ProfilingOutputDir']
end
def set_ignore_header(bool)
@conf["Debug"]['IgnoreFileHeader'] = bool
save
end
def ignore_header?
@conf["Debug"]['IgnoreFileHeader']
end
def set_verbosity(level)
@conf["Debug"]['Verbosity'] = level
save
end
def verbosity
@conf["Debug"]['Verbosity']
end
def save
File.open(@filename, "w").write(@conf.to_yaml)
end
private
def set_missing_values
@conf ||= {}
DEFAULT_CONFIG.each_key do |cat|
@conf[cat] = {} unless @conf.include?(cat)
DEFAULT_CONFIG[cat].each_pair do |key, value|
@conf[cat][key] = value unless @conf[cat].include?(key)
end
end
end
end
end
end
origami-2.0.0/bin/gui/hexview.rb 0000644 0000041 0000041 00000004365 12757133666 016560 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
require 'gui/gtkhex'
module PDFWalker
class Walker < Window
private
def create_hexview
@hexview = DumpView.new(self)
end
class DumpView < ScrolledWindow
def initialize(parent)
@parent = parent
super()
set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
@current_obj = nil
@view = HexEditor.new
@view.show_offsets(true)
add_with_viewport @view
end
def clear
@view.set_data ''
end
def load(object)
return if @current_obj.equal?(object)
begin
self.clear
case object
when Origami::Stream
begin
@view.set_data(object.data)
rescue Origami::Filter::Error
@view.set_data($!.input_data) if $!.input_data
@parent.error("#{$!.class}: #{$!.message}") unless object.filters == [ :DCTDecode ]
end
when Origami::String
@view.set_data(object.value)
end
@current_obj = object
rescue
@parent.error("An error occured while loading this object.\n#{$!} (#{$!.class})")
end
end
end
end
end
origami-2.0.0/bin/gui/walker.rb 0000644 0000041 0000041 00000020424 12757133666 016360 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
begin
require 'gtk2'
rescue LoadError
abort('Error: you need to install ruby-gtk2 to run this application')
end
include Gtk
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../../lib')
require 'origami'
end
require 'gui/menu'
require 'gui/about'
require 'gui/file'
require 'gui/hexview'
require 'gui/treeview'
require 'gui/textview'
require 'gui/imgview'
require 'gui/config'
require 'gui/properties'
require 'gui/xrefs'
require 'gui/signing'
module PDFWalker #:nodoc:all
class Walker < Window
attr_reader :treeview, :hexview, :objectview
attr_reader :explorer_history
attr_reader :config
attr_reader :filename
def self.start(file = nil)
Gtk.init
Walker.new(file)
Gtk.main
end
def initialize(target_file = nil)
super("PDF Walker")
@config = Walker::Config.new
@opened = nil
@last_search_result = []
@last_search =
{
:expr => "",
:regexp => false,
:type => :body
}
@explorer_history = Array.new
signal_connect('destroy') {
@config.save
Gtk.main_quit
}
add_events(Gdk::Event::KEY_RELEASE_MASK)
signal_connect('key_release_event') { |w, event|
if event.keyval == Gdk::Keyval::GDK_F1 then about
elsif event.keyval == Gdk::Keyval::GDK_Escape and @opened and not @explorer_history.empty?
@treeview.goto(@explorer_history.pop)
end
}
create_menus
create_treeview
create_hexview
create_objectview
create_panels
create_statusbar
@vbox = VBox.new
@vbox.pack_start(@menu, false, false)
@vbox.pack_start(@hpaned)
@vbox.pack_end(@statusbar, false, false)
add @vbox
set_default_size(self.screen.width * 0.5, self.screen.height * 0.5)
#maximize
show_all
open(target_file)
end
def error(msg)
dialog = Gtk::MessageDialog.new(self,
Gtk::Dialog::DESTROY_WITH_PARENT,
Gtk::MessageDialog::ERROR,
Gtk::MessageDialog::BUTTONS_CLOSE,
msg
)
dialog.run
dialog.destroy
end
def reload
@treeview.load(@opened) if @opened
end
def search
dialog = Gtk::Dialog.new("Search...",
self,
Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
[Gtk::Stock::FIND, Gtk::Dialog::RESPONSE_OK],
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL]
)
entry = Gtk::Entry.new
entry.signal_connect('activate') { dialog.response(Gtk::Dialog::RESPONSE_OK) }
entry.text = @last_search[:expr]
button_bydata = Gtk::RadioButton.new("In object body")
button_byname = Gtk::RadioButton.new(button_bydata, "In object name")
button_regexp = Gtk::CheckButton.new("Regular expression")
button_bydata.set_active(true) if @last_search[:type] == :body
button_byname.set_active(true) if @last_search[:type] == :name
button_regexp.set_active(@last_search[:regexp])
hbox = HBox.new
hbox.pack_start Gtk::Label.new("Search for expression ")
hbox.pack_start entry
dialog.vbox.pack_start(hbox)
dialog.vbox.pack_start(button_bydata)
dialog.vbox.pack_start(button_byname)
dialog.vbox.pack_end(button_regexp)
dialog.signal_connect('response') do |dlg, response|
if response != Gtk::Dialog::RESPONSE_OK
dialog.destroy
next
end
search =
{
:expr => entry.text,
:regexp => button_regexp.active?,
:type => button_byname.active? ? :name : :body
}
if search == @last_search
@last_search_result.push @last_search_result.shift
results = @last_search_result
else
expr = search[:regexp] ? Regexp.new(search[:expr]) : search[:expr]
results =
if search[:type] == :body
@opened.grep(expr)
else
@opened.ls(expr, follow_references: false)
end
@last_search = search
end
if results.empty?
error("No result found.")
else
if results != @last_search_result
# Reset the previous search highlighting.
@last_search_result.each do |obj| @treeview.highlight(obj, nil) end
# Highlight the new results.
results.each do |obj| @treeview.highlight(obj, "lightpink") end
@last_search_result = results
end
@treeview.goto(results.first, follow_references: false)
end
end
dialog.show_all
end
def goto_catalog
@treeview.goto(@opened.Catalog.reference)
end
def goto_docinfo
@treeview.goto(@opened.document_info.reference) if @opened.document_info?
end
def goto_metadata
@treeview.goto(@opened.Catalog.Metadata.reference) if @opened.metadata?
end
def goto_object
dialog = Gtk::Dialog.new("Jump to object...",
self,
Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
[Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL]
)
entry = Gtk::Entry.new
entry.signal_connect('activate') { dialog.response(Gtk::Dialog::RESPONSE_OK) }
dialog.vbox.pack_start Gtk::Label.new("Object number: ")
dialog.vbox.pack_start entry
dialog.show_all
no = 0
dialog.run do |response|
no = entry.text.to_i if response == Gtk::Dialog::RESPONSE_OK
dialog.destroy
end
return unless no > 0
obj = @opened[no]
if obj.nil?
error("Object #{no} not found.")
else
@treeview.goto(obj)
end
end
private
def create_panels
@hpaned = HPaned.new
@treepanel = ScrolledWindow.new.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
@treepanel.add @treeview
@vpaned = VPaned.new
@vpaned.pack1(@objectview, true, false)
@vpaned.pack2(@hexview, true, false)
@hpaned.pack1(@treepanel, true, false)
@hpaned.pack2(@vpaned, true, false)
end
def create_statusbar
@statusbar = Statusbar.new
@main_context = @statusbar.get_context_id 'Main'
@statusbar.push(@main_context, 'No file selected')
end
end
end
PDFWalker::Walker.start if __FILE__ == $0
origami-2.0.0/bin/gui/xrefs.rb 0000644 0000041 0000041 00000004635 12757133666 016230 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class Walker < Window
def show_xrefs(target)
XrefsDialog.new(self, target)
end
end
class XrefsDialog < Dialog
OBJCOL = 0
REFCOL = 1
NAMECOL = 2
def initialize(parent, target)
super("Xrefs to #{target.reference}", parent, Dialog::MODAL, [Stock::CLOSE, Dialog::RESPONSE_NONE])
@parent = parent
@list = ListStore.new(Object, String, String)
@view = TreeView.new(@list)
column = Gtk::TreeViewColumn.new("Origin", Gtk::CellRendererText.new, text: REFCOL)
@view.append_column(column)
column = Gtk::TreeViewColumn.new("Objects", Gtk::CellRendererText.new, text: NAMECOL)
@view.append_column(column)
target.xrefs.each { |obj|
str = obj.type.to_s
iter = @list.append
@list.set_value(iter, OBJCOL, obj)
obj = obj.parent until obj.indirect?
@list.set_value(iter, REFCOL, obj.reference.to_s)
@list.set_value(iter, NAMECOL, str)
}
@view.signal_connect("row_activated") { |tree, path, _column|
if @view.selection.selected
from = @list.get_value(@view.selection.selected, OBJCOL)
@parent.treeview.goto(from)
end
}
scroll = ScrolledWindow.new.set_policy(POLICY_NEVER, POLICY_AUTOMATIC)
scroll.add(@view)
vbox.add(scroll)
set_default_size(200, 200)
signal_connect('response') { destroy }
show_all
end
end
end
origami-2.0.0/bin/gui/menu.rb 0000644 0000041 0000041 00000040605 12757133666 016042 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
module Popable
@@menus = Hash.new([])
@@menus[:"PDF File"] =
[
{
Name: Stock::SAVE_AS,
Sensitive: true,
Callback: lambda { |widget, viewer, path|
viewer.parent.save
}
},
{
Name: "Serialize",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
viewer.parent.serialize
}
},
{
Name: :"---"
},
{
Name: Stock::PROPERTIES,
Sensitive: true,
Callback: lambda { |widget, viewer, path|
viewer.parent.display_file_properties
}
},
{
Name: :"---"
},
{
Name: Stock::CLOSE,
Sensitive: true,
Callback: lambda { |widget, viewer, path|
viewer.parent.close
}
}
]
@@menus[:Reference] =
[
{
Name: Stock::JUMP_TO,
Sensitive: true,
Callback: lambda { |widget, viewer, path|
viewer.row_activated(path, viewer.get_column(viewer.class::TEXTCOL))
}
}
]
@@menus[:Revision] =
[
{
Name: "Save to this revision",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
revstr = viewer.model.get_value(viewer.model.get_iter(path), viewer.class::TEXTCOL)
revstr.slice!(0, "Revision ".size)
revnum = revstr.to_i
dialog = Gtk::FileChooserDialog.new("Save PDF File",
viewer.parent,
Gtk::FileChooser::ACTION_SAVE,
nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
[Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT]
)
dialog.filter = FileFilter.new.add_pattern("*.pdf")
if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
viewer.parent.opened.save_upto(revnum, dialog.filename)
end
dialog.destroy
}
}
]
@@menus[:Stream] =
[
{
Name: "Dump encoded stream",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
stream = viewer.model.get_value(viewer.model.get_iter(path), viewer.class::OBJCOL)
viewer.parent.save_data("Save stream to file", stream.encoded_data)
}
},
{
Name: "Dump decoded stream",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
stream = viewer.model.get_value(viewer.model.get_iter(path), viewer.class::OBJCOL)
viewer.parent.save_data("Save stream to file", stream.data)
}
}
]
@@menus[:String] =
[
{
Name: "Dump string",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
string = viewer.model.get_value(viewer.model.get_iter(path), viewer.class::OBJCOL)
viewer.parent.save_data("Save string to file", string.value)
}
}
]
@@menus[:Image] = @@menus[:Stream] +
[
{
Name: :"---"
},
{
Name: "View image",
Sensitive: true,
Callback: lambda { |widget, viewer, path|
stm = viewer.model.get_value(viewer.model.get_iter(path), viewer.class::OBJCOL)
w,h = stm.Width, stm.Height
if stm.ColorSpace.nil?
colors = 1
else
colors =
case stm.ColorSpace.value
when :DeviceGray then 1
when :DeviceRGB then 3
when :DeviceCMYK then 4
else
1
end
end
bpc = stm.BitsPerComponent || 8
bpr = (w * colors * bpc + 7) >> 3
data = stm.data
begin
imgview = ImgViewer.new
if stm.Filter == :DCTDecode or (stm.Filter.is_a?(Array) and stm.Filter[0] == :DCTDecode)
imgview.show_compressed_img data
else
imgview.show_raw_img data, w, h, bpc, bpr
end
rescue
viewer.parent.error("#{$!.class}: #{$!.message}")
end
}
}
]
def popup_menu(obj, event, path)
menu = Menu.new
type =
if obj.is_a?(Origami::Object)
if obj.is_a?(Origami::Graphics::ImageXObject)
:Image
else
obj.native_type.to_s.split("::").last.to_sym
end
else
case obj
when Origami::PDF
:"PDF File"
when Origami::PDF::Revision, Origami::FDF::Revision, Origami::PPKLite::Revision
:Revision
when ::Array
:Body
when Origami::PDF::Header, Origami::FDF::Header, Origami::PPKLite::Header
:Header
when Origami::Trailer
:Trailer
when Origami::XRef::Section
:XRefSection
when Origami::XRef::Subsection
:XRefSubsection
when Origami::XRef, Origami::XRefToCompressedObj
:XRef
else
:Unknown
end
end
title = obj.is_a?(Origami::Object) ? "Object : " : ""
title << type.to_s
menu.append(MenuItem.new(title).set_sensitive(false).modify_text(Gtk::STATE_INSENSITIVE, Gdk::Color.new(255,0,255)))
if obj.is_a?(Origami::Object)
if obj.indirect?
menu.append(MenuItem.new("Number : #{obj.no}; Generation : #{obj.generation}").set_sensitive(false))
menu.append(MenuItem.new("File offset : #{obj.file_offset}").set_sensitive(false))
getxrefs = MenuItem.new("Search references to this object").set_sensitive(true)
getxrefs.signal_connect("activate") do
ref = self.model.get_value(self.model.get_iter(path), self.class::OBJCOL)
self.parent.show_xrefs(ref)
end
menu.append(getxrefs)
elsif not obj.parent.nil?
gotoparent = MenuItem.new("Goto Parent Object").set_sensitive(true)
gotoparent.signal_connect("activate") do
dest = self.model.get_value(self.model.get_iter(path), self.class::OBJCOL).parent
self.goto(dest)
end
menu.append(gotoparent)
end
end
items = @@menus[type]
menu.append(SeparatorMenuItem.new) if not items.empty?
items.each { |item|
if item[:Name] == :"---"
entry = SeparatorMenuItem.new
else
if item[:Name].is_a?(String)
entry = MenuItem.new(item[:Name])
else
entry = ImageMenuItem.new(item[:Name])
end
entry.set_sensitive(item[:Sensitive])
entry.signal_connect("activate", self, path, &item[:Callback])
end
menu.append(entry)
}
menu.show_all
menu.popup(nil, nil, event.button, event.time)
end
end
class Walker < Window
private
def create_menus
AccelMap.add_entry("/File/Open", Gdk::Keyval::GDK_O, Gdk::Window::CONTROL_MASK)
AccelMap.add_entry("/File/Refresh", Gdk::Keyval::GDK_R, Gdk::Window::CONTROL_MASK)
AccelMap.add_entry("/File/Close", Gdk::Keyval::GDK_W, Gdk::Window::CONTROL_MASK)
AccelMap.add_entry("/File/Save", Gdk::Keyval::GDK_S, Gdk::Window::CONTROL_MASK)
AccelMap.add_entry("/File/Quit", Gdk::Keyval::GDK_Q, Gdk::Window::CONTROL_MASK)
AccelMap.add_entry("/Document/Search", Gdk::Keyval::GDK_F, Gdk::Window::CONTROL_MASK)
@menu = MenuBar.new
####################################################
file_ag = Gtk::AccelGroup.new
@file_menu = Menu.new.set_accel_group(file_ag).set_accel_path("/File")
add_accel_group(file_ag)
@file_menu_open = ImageMenuItem.new(Stock::OPEN).set_accel_path("/File/Open")
@file_menu_recent = MenuItem.new("Last opened")
@file_menu_deserialize = MenuItem.new("Deserialize")
@file_menu_refresh = ImageMenuItem.new(Stock::REFRESH).set_sensitive(false).set_accel_path("/File/Refresh")
@file_menu_close = ImageMenuItem.new(Stock::CLOSE).set_sensitive(false).set_accel_path("/File/Close")
@file_menu_saveas = ImageMenuItem.new(Stock::SAVE_AS).set_sensitive(false)
@file_menu_serialize = MenuItem.new("Serialize").set_sensitive(false)
@file_menu_exit = ImageMenuItem.new(Stock::QUIT).set_accel_path("/File/Quit")
@export_menu = Menu.new
@export_pdf_menu = MenuItem.new("As PDF").set_accel_path("/File/Save")
@export_graph_menu = MenuItem.new("As GraphViz dot file")
@export_graphml_menu = MenuItem.new("As GraphML file")
@export_pdf_menu.signal_connect('activate') do save end
@export_graph_menu.signal_connect('activate') do save_dot end
@export_graphml_menu.signal_connect('activate') do save_graphml end
@export_menu.append(@export_pdf_menu)
@export_menu.append(@export_graph_menu)
@export_menu.append(@export_graphml_menu)
@file_menu_saveas.set_submenu(@export_menu)
@file_menu_open.signal_connect('activate') do open end
@file_menu_deserialize.signal_connect('activate') do deserialize end
@file_menu_refresh.signal_connect('activate') do open(@filename) end
@file_menu_close.signal_connect('activate') do close end
@file_menu_serialize.signal_connect('activate') do serialize end
@file_menu_exit.signal_connect('activate') do self.destroy end
update_recent_menu
@file_menu.append(@file_menu_open)
@file_menu.append(@file_menu_recent)
@file_menu.append(@file_menu_deserialize)
@file_menu.append(@file_menu_refresh)
@file_menu.append(@file_menu_close)
@file_menu.append(@file_menu_saveas)
@file_menu.append(@file_menu_serialize)
@file_menu.append(@file_menu_exit)
@menu.append(MenuItem.new('_File').set_submenu(@file_menu))
####################################################
doc_ag = Gtk::AccelGroup.new
@document_menu = Menu.new.set_accel_group(doc_ag)
add_accel_group(doc_ag)
@document_menu_search = ImageMenuItem.new(Stock::FIND).set_sensitive(false).set_accel_path("/Document/Search")
@document_menu_gotocatalog = MenuItem.new("Jump to Catalog").set_sensitive(false)
@document_menu_gotodocinfo = MenuItem.new("Jump to Document Info").set_sensitive(false)
@document_menu_gotometadata = MenuItem.new("Jump to Metadata").set_sensitive(false)
@document_menu_gotorev = MenuItem.new("Jump to Revision...").set_sensitive(false)
@document_menu_gotopage = MenuItem.new("Jump to Page...").set_sensitive(false)
@document_menu_gotofield = MenuItem.new("Jump to Field...").set_sensitive(false)
@document_menu_gotoobj = MenuItem.new("Jump to Object...").set_sensitive(false)
@document_menu_properties = ImageMenuItem.new(Stock::PROPERTIES).set_sensitive(false)
@document_menu_sign = MenuItem.new("Sign the document").set_sensitive(false)
@document_menu_ur = MenuItem.new("Enable Usage Rights").set_sensitive(false)
@document_menu_search.signal_connect('activate') do search end
@document_menu_gotocatalog.signal_connect('activate') do goto_catalog end
@document_menu_gotodocinfo.signal_connect('activate') do goto_docinfo end
@document_menu_gotometadata.signal_connect('activate') do goto_metadata end
@document_menu_gotoobj.signal_connect('activate') do goto_object end
@document_menu_properties.signal_connect('activate') do display_file_properties end
@document_menu_sign.signal_connect('activate') do display_signing_wizard end
@document_menu_ur.signal_connect('activate') do display_usage_rights_wizard end
@document_menu.append(@document_menu_search)
@document_menu.append(MenuItem.new)
@document_menu.append(@document_menu_gotocatalog)
@document_menu.append(@document_menu_gotodocinfo)
@document_menu.append(@document_menu_gotometadata)
@document_menu.append(@document_menu_gotorev)
@document_menu.append(@document_menu_gotopage)
@document_menu.append(@document_menu_gotofield)
@document_menu.append(@document_menu_gotoobj)
@document_menu.append(MenuItem.new)
@document_menu.append(@document_menu_sign)
@document_menu.append(@document_menu_ur)
@document_menu.append(@document_menu_properties)
@menu.append(MenuItem.new('_Document').set_submenu(@document_menu))
####################################################
@help_menu = Menu.new
@help_menu_profile = CheckMenuItem.new("Profiling (Debug purposes only)").set_active(@config.profile?)
@help_menu_profile.signal_connect('toggled') do @config.set_profiling(@help_menu_profile.active?) end
@help_menu_about = ImageMenuItem.new(Stock::ABOUT)
@help_menu_about.signal_connect('activate') do about end
@help_menu.append(@help_menu_profile)
@help_menu.append(@help_menu_about)
@menu.append(MenuItem.new('_Help').set_submenu(@help_menu))
####################################################
end
def update_recent_menu
@recent_menu = Menu.new
@config.recent_files.each { |file|
menu = MenuItem.new(file)
menu.signal_connect('activate') do open(file) end
@recent_menu.append(menu)
}
@file_menu_recent.set_submenu(@recent_menu)
@file_menu_recent.show_all
end
end
end
origami-2.0.0/bin/gui/signing.rb 0000644 0000041 0000041 00000057104 12757133666 016536 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class Walker < Window
def display_signing_wizard
SignWizard.new(self, @opened) if @opened
end
def display_usage_rights_wizard
UsageRightsWizard.new(self, @opened) if @opened
end
module SignatureDialogs
private
def open_private_key_dialog(page)
dialog = FileChooserDialog.new("Choose a private RSA key",
@parent,
FileChooser::ACTION_OPEN,
nil,
[Stock::CANCEL, Dialog::RESPONSE_CANCEL],
[Stock::OPEN, Dialog::RESPONSE_ACCEPT])
filter = FileFilter.new
filter.add_pattern("*.key")
filter.add_pattern("*.pem")
filter.add_pattern("*.der")
dialog.set_filter(filter)
if dialog.run == Dialog::RESPONSE_ACCEPT
begin
@pkey = OpenSSL::PKey::RSA.new(File.binread(dialog.filename))
@pkeyfilename.set_text(dialog.filename)
set_page_complete(page, true) if @cert
rescue
@parent.error("Error loading file '#{File.basename(dialog.filename)}'")
@pkey = nil
@pkeyfilename.text = ""
set_page_complete(page, false)
ensure
@ca = [] # Shall be added to the GUI
end
end
dialog.destroy
end
def open_certificate_dialog(page)
dialog = FileChooserDialog.new("Choose a x509 certificate",
@parent,
FileChooser::ACTION_OPEN,
nil,
[Stock::CANCEL, Dialog::RESPONSE_CANCEL],
[Stock::OPEN, Dialog::RESPONSE_ACCEPT])
filter = FileFilter.new
filter.add_pattern("*.crt")
filter.add_pattern("*.cer")
filter.add_pattern("*.pem")
filter.add_pattern("*.der")
dialog.set_filter(filter)
if dialog.run == Dialog::RESPONSE_ACCEPT
begin
@cert = OpenSSL::X509::Certificate.new(File.binread(dialog.filename))
@certfilename.set_text(dialog.filename)
if @pkey then set_page_complete(page, true) end
rescue
@parent.error("Error loading file '#{File.basename(dialog.filename)}'")
@cert = nil
@certfilename.text = ""
set_page_complete(page, false)
ensure
@ca = [] # Shall be added to the GUI
end
end
dialog.destroy
end
def open_pkcs12_file_dialog(page)
get_passwd = -> () do
dialog = Dialog.new("Enter passphrase",
@parent,
Dialog::MODAL,
[Stock::OK, Dialog::RESPONSE_OK]
)
pwd_entry = Entry.new.set_visibility(false).show
dialog.vbox.pack_start(pwd_entry, true, true, 0)
pwd = (dialog.run == Dialog::RESPONSE_OK) ? pwd_entry.text : ""
dialog.destroy
return pwd
end
dialog = FileChooserDialog.new("Open PKCS12 container",
@parent,
FileChooser::ACTION_OPEN,
nil,
[Stock::CANCEL, Dialog::RESPONSE_CANCEL],
[Stock::OPEN, Dialog::RESPONSE_ACCEPT])
filter = FileFilter.new
filter.add_pattern("*.pfx")
filter.add_pattern("*.p12")
dialog.filter = filter
if dialog.run == Dialog::RESPONSE_ACCEPT
begin
p12 = OpenSSL::PKCS12::PKCS12.new(File.binread(dialog.filename), get_passwd)
raise TypeError, "PKCS12 does not contain a RSA key" unless p12.key.is_a?(OpenSSL::PKey::RSA)
raise TypeError, "PKCS12 does not contain a x509 certificate" unless p12.certificate.is_a?(OpenSSL::X509::Certificate)
@pkey = p12.key
@cert = p12.certificate
@ca = p12.ca_certs
@p12filename.set_text(dialog.filename)
set_page_complete(page, true)
rescue
@parent.error("Error loading file '#{File.basename(dialog.filename)}'")
@pkey, @cert, @ca = nil, nil, []
@p12filename.text = ""
set_page_complete(page, false)
end
end
dialog.destroy
end
end
class UsageRightsWizard < Assistant
include SignatureDialogs
def initialize(parent, pdf)
super()
@parent = parent
@pkey, @cert = nil, nil
create_intro_page
create_keypair_import_page
create_rights_selection_page
create_termination_page
signal_connect('delete_event') { self.destroy }
signal_connect('cancel') { self.destroy }
signal_connect('close') { self.destroy }
signal_connect('apply') {
rights = []
rights << Origami::UsageRights::Rights::DOCUMENT_FULLSAVE if @document_fullsave.active?
rights << Origami::UsageRights::Rights::ANNOTS_CREATE if @annots_create.active?
rights << Origami::UsageRights::Rights::ANNOTS_DELETE if @annots_delete.active?
rights << Origami::UsageRights::Rights::ANNOTS_MODIFY if @annots_modify.active?
rights << Origami::UsageRights::Rights::ANNOTS_COPY if @annots_copy.active?
rights << Origami::UsageRights::Rights::ANNOTS_IMPORT if @annots_import.active?
rights << Origami::UsageRights::Rights::ANNOTS_EXPORT if @annots_export.active?
rights << Origami::UsageRights::Rights::ANNOTS_ONLINE if @annots_online.active?
rights << Origami::UsageRights::Rights::ANNOTS_SUMMARYVIEW if @annots_sumview.active?
rights << Origami::UsageRights::Rights::FORM_FILLIN if @form_fillin.active?
rights << Origami::UsageRights::Rights::FORM_IMPORT if @form_import.active?
rights << Origami::UsageRights::Rights::FORM_EXPORT if @form_export.active?
rights << Origami::UsageRights::Rights::FORM_SUBMITSTANDALONE if @form_submit.active?
rights << Origami::UsageRights::Rights::FORM_SPAWNTEMPLATE if @form_spawntemplate.active?
rights << Origami::UsageRights::Rights::FORM_BARCODEPLAINTEXT if @form_barcode.active?
rights << Origami::UsageRights::Rights::FORM_ONLINE if @form_online.active?
rights << Origami::UsageRights::Rights::SIGNATURE_MODIFY if @signature_modify.active?
rights << Origami::UsageRights::Rights::EF_CREATE if @ef_create.active?
rights << Origami::UsageRights::Rights::EF_DELETE if @ef_delete.active?
rights << Origami::UsageRights::Rights::EF_MODIFY if @ef_modify.active?
rights << Origami::UsageRights::Rights::EF_IMPORT if @ef_import.active?
begin
pdf.enable_usage_rights(@cert, @pkey, *rights)
set_page_title(@lastpage, "Usage Rights have been enabled")
@msg_status.text = "Usage Rights have been enabled for the current document.\n You should consider saving it now."
@parent.reload
rescue
@parent.error("#{$!}: #{$!.backtrace.join($/)}")
set_page_title(@lastpage, "Usage Rights have not been enabled")
@msg_status.text = "An error occured during the signature process."
end
}
set_modal(true)
show_all
end
private
def create_intro_page
intro = <<-INTRO
You are about to enable Usage Rights for the current PDF document.
To enable these features, you need to have an Adobe public/private key pair in your possession.
Make sure you have adobe.crt and adobe.key located in the current directory.
INTRO
vbox = VBox.new(false, 5)
vbox.set_border_width(5)
lbl = Label.new(intro).set_justify(Gtk::JUSTIFY_LEFT).set_wrap(true)
vbox.pack_start(lbl, true, true, 0)
append_page(vbox)
set_page_title(vbox, "Usage Rights Wizard")
set_page_type(vbox, Assistant::PAGE_INTRO)
set_page_complete(vbox, true)
end
def create_keypair_import_page
labels =
[
[ "Private RSA key:", @pkeyfilename = Entry.new, pkeychoosebtn = Button.new(Gtk::Stock::OPEN) ],
[ "Public certificate:", @certfilename = Entry.new, certchoosebtn = Button.new(Gtk::Stock::OPEN) ]
]
row = 0
table = Table.new(2, 3)
labels.each do |lbl, entry, btn|
entry.editable = entry.sensitive = false
table.attach(Label.new(lbl).set_alignment(1,0), 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
table.attach(entry, 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
table.attach(btn, 2, 3, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
pkeychoosebtn.signal_connect('clicked') { open_private_key_dialog(table) }
certchoosebtn.signal_connect('clicked') { open_certificate_dialog(table) }
append_page(table)
set_page_title(table, "Import a public/private key pair")
set_page_type(table, Assistant::PAGE_CONTENT)
end
def create_rights_selection_page
vbox = VBox.new(false, 5)
docframe = Frame.new(" Document ")
docframe.border_width = 5
docframe.shadow_type = Gtk::SHADOW_IN
doctable = Table.new(1, 2)
doctable.attach(@document_fullsave = CheckButton.new("Full Save").set_active(true), 0, 1, 0, 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
docframe.add(doctable)
annotsframe = Frame.new(" Annotations ")
annotsframe.border_width = 5
annotsframe.shadow_type = Gtk::SHADOW_IN
annotstable = Table.new(4,2)
annots =
[
[ @annots_create = CheckButton.new("Create").set_active(true), @annots_import = CheckButton.new("Import").set_active(true) ],
[ @annots_delete = CheckButton.new("Delete").set_active(true), @annots_export = CheckButton.new("Export").set_active(true) ],
[ @annots_modify = CheckButton.new("Modify").set_active(true), @annots_online = CheckButton.new("Online").set_active(true) ],
[ @annots_copy = CheckButton.new("Copy").set_active(true), @annots_sumview = CheckButton.new("Summary View").set_active(true) ]
]
row = 0
annots.each do |col1, col2|
annotstable.attach(col1, 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
annotstable.attach(col2, 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
annotsframe.add(annotstable)
formframe = Frame.new(" Forms ")
formframe.border_width = 5
formframe.shadow_type = Gtk::SHADOW_IN
formtable = Table.new(4,2)
forms =
[
[ @form_fillin = CheckButton.new("Fill in").set_active(true), @form_spawntemplate = CheckButton.new("Spawn template").set_active(true) ],
[ @form_import = CheckButton.new("Import").set_active(true), @form_barcode = CheckButton.new("Barcode plaintext").set_active(true) ],
[ @form_export = CheckButton.new("Export").set_active(true), @form_online = CheckButton.new("Online").set_active(true) ],
[ @form_submit = CheckButton.new("Submit stand-alone").set_active(true), nil ]
]
row = 0
forms.each do |col1, col2|
formtable.attach(col1, 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
formtable.attach(col2, 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4) unless col2.nil?
row = row.succ
end
formframe.add(formtable)
signatureframe = Frame.new(" Signature ")
signatureframe.border_width = 5
signatureframe.shadow_type = Gtk::SHADOW_IN
signaturetable = Table.new(1, 2)
signaturetable.attach(@signature_modify = CheckButton.new("Modify").set_active(true), 0, 1, 0, 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
signatureframe.add(signaturetable)
efframe = Frame.new(" Embedded files ")
efframe.border_width = 5
efframe.shadow_type = Gtk::SHADOW_IN
eftable = Table.new(2,2)
efitems =
[
[ @ef_create = CheckButton.new("Create").set_active(true), @ef_modify = CheckButton.new("Modify").set_active(true) ],
[ @ef_delete = CheckButton.new("Delete").set_active(true), @ef_import = CheckButton.new("Import").set_active(true) ]
]
row = 0
efitems.each do |col1, col2|
eftable.attach(col1, 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
eftable.attach(col2, 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
efframe.add(eftable)
vbox.add(docframe)
vbox.add(annotsframe)
vbox.add(formframe)
vbox.add(signatureframe)
vbox.add(efframe)
append_page(vbox)
set_page_title(vbox, "Select Usage Rights to enable")
set_page_type(vbox, Assistant::PAGE_CONFIRM)
set_page_complete(vbox, true)
end
def create_termination_page
@lastpage = VBox.new(false, 5)
@msg_status = Label.new
@lastpage.pack_start(@msg_status, true, true, 0)
append_page(@lastpage)
set_page_title(@lastpage, "Usage Rights have not been enabled")
set_page_type(@lastpage, Assistant::PAGE_SUMMARY)
end
end
class SignWizard < Assistant
include SignatureDialogs
INTRO_PAGE = 0
KEY_SELECT_PAGE = 1
PKCS12_IMPORT_PAGE = 2
KEYPAIR_IMPORT_PAGE = 3
SIGNATURE_INFO_PAGE = 4
SIGNATURE_RESULT_PAGE = 5
def initialize(parent, pdf)
super()
@parent = parent
@pkey, @cert, @ca = nil, nil, []
create_intro_page
create_key_selection_page
create_pkcs12_import_page
create_keypair_import_page
create_signature_info_page
create_termination_page
set_forward_page_func { |current_page|
case current_page
when KEY_SELECT_PAGE
if @p12button.active? then PKCS12_IMPORT_PAGE else KEYPAIR_IMPORT_PAGE end
when PKCS12_IMPORT_PAGE, KEYPAIR_IMPORT_PAGE
SIGNATURE_INFO_PAGE
else current_page.succ
end
}
signal_connect('delete_event') { self.destroy }
signal_connect('cancel') { self.destroy }
signal_connect('close') { self.destroy }
signal_connect('apply') {
location = @location.text.empty? ? nil : @location.text
contact = @email.text.empty? ? nil : @email.text
reason = @reason.text.empty? ? nil : @reason.text
begin
pdf.sign(@cert, @pkey,
ca: @ca,
location: location,
contact: contact,
reason: reason)
set_page_title(@lastpage, "Document has been signed")
@msg_status.text = "The document has been signed.\n You should consider saving it now."
@parent.reload
rescue
@parent.error("#{$!}: #{$!.backtrace.join($/)}")
set_page_title(@lastpage, "Document has not been signed")
@msg_status.text = "An error occured during the signature process."
end
}
set_modal(true)
show_all
end
private
def create_intro_page
intro = <<-INTRO
You are about to sign the current PDF document.
Once the document will be signed, no further modification will be allowed.
The signature process is based on assymetric cryptography, so you will basically need a public/private RSA key pair (between 1024 and 4096 bits).
INTRO
vbox = VBox.new(false, 5)
vbox.set_border_width(5)
lbl = Label.new(intro).set_justify(Gtk::JUSTIFY_LEFT).set_wrap(true)
vbox.pack_start(lbl, true, true, 0)
append_page(vbox)
set_page_title(vbox, "Signature Wizard")
set_page_type(vbox, Assistant::PAGE_INTRO)
set_page_complete(vbox, true)
end
def create_key_selection_page
vbox = VBox.new(false, 5)
@rawbutton = RadioButton.new("Import keys from separate PEM/DER encoded files")
@p12button = RadioButton.new(@rawbutton, "Import keys from a PKCS12 container")
vbox.pack_start(@rawbutton, true, true, 0)
vbox.pack_start(@p12button, true, true, 0)
append_page(vbox)
set_page_title(vbox, "Choose a key importation method")
set_page_type(vbox, Assistant::PAGE_CONTENT)
set_page_complete(vbox, true)
end
def create_pkcs12_import_page
vbox = VBox.new(false, 5)
hbox = HBox.new(false, 5)
vbox.pack_start(hbox, true, false, 10)
@p12filename = Entry.new.set_editable(false).set_sensitive(false)
choosebtn = Button.new(Gtk::Stock::OPEN)
choosebtn.signal_connect('clicked') { open_pkcs12_file_dialog(vbox) }
hbox.pack_start(@p12filename, true, true, 5)
hbox.pack_start(choosebtn, false, false, 5)
append_page(vbox)
set_page_title(vbox, "Import a PKCS12 container")
set_page_type(vbox, Assistant::PAGE_CONTENT)
end
def create_keypair_import_page
labels =
[
[ "Private RSA key:", @pkeyfilename = Entry.new, pkeychoosebtn = Button.new(Gtk::Stock::OPEN) ],
[ "Public certificate:", @certfilename = Entry.new, certchoosebtn = Button.new(Gtk::Stock::OPEN) ]
]
row = 0
table = Table.new(2, 3)
labels.each do |lbl, entry, btn|
entry.editable = entry.sensitive = false
table.attach(Label.new(lbl).set_alignment(1,0), 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
table.attach(entry, 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
table.attach(btn, 2, 3, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
pkeychoosebtn.signal_connect('clicked') { open_private_key_dialog(table) }
certchoosebtn.signal_connect('clicked') { open_certificate_dialog(table) }
append_page(table)
set_page_title(table, "Import a public/private key pair")
set_page_type(table, Assistant::PAGE_CONTENT)
end
def create_signature_info_page
vbox = VBox.new(false, 5)
lbl = Label.new("Here are a few optional information you can add with your signature.")
vbox.pack_start(lbl, true, true, 0)
labels =
[
[ "Location:", @location = Entry.new ],
[ "Contact:", @email = Entry.new ],
[ "Reason:", @reason = Entry.new ]
]
row = 0
table = Table.new(4, 3)
labels.each do |label|
table.attach(Label.new(label[0]).set_alignment(1,0), 0, 1, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
table.attach(label[1], 1, 2, row, row + 1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK, 4, 4)
row = row.succ
end
vbox.pack_start(table, true, true, 0)
append_page(vbox)
set_page_title(vbox, "Fill in signature details")
set_page_type(vbox, Assistant::PAGE_CONFIRM)
set_page_complete(vbox, true)
end
def create_termination_page
@lastpage = VBox.new(false, 5)
@msg_status = Label.new
@lastpage.pack_start(@msg_status, true, true, 0)
append_page(@lastpage)
set_page_title(@lastpage, "Document has not been signed")
set_page_type(@lastpage, Assistant::PAGE_SUMMARY)
end
end
end
end
origami-2.0.0/bin/gui/treeview.rb 0000644 0000041 0000041 00000034537 12757133666 016737 0 ustar www-data www-data =begin
This file is part of PDF Walker, a graphical PDF file browser
Copyright (C) 2016 Guillaume Delugré.
PDF Walker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PDF Walker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PDF Walker. If not, see .
=end
module PDFWalker
class Walker < Window
private
def create_treeview
@treeview = PDFTree.new(self).set_headers_visible(false)
colcontent = Gtk::TreeViewColumn.new("Names",
Gtk::CellRendererText.new.set_foreground_set(true).set_background_set(true),
text: PDFTree::TEXTCOL,
weight: PDFTree::WEIGHTCOL,
style: PDFTree::STYLECOL,
foreground: PDFTree::FGCOL,
background: PDFTree::BGCOL
)
@treeview.append_column(colcontent)
end
end
class PDFTree < TreeView
include Popable
OBJCOL = 0
TEXTCOL = 1
WEIGHTCOL = 2
STYLECOL = 3
FGCOL = 4
BGCOL = 5
LOADCOL = 6
@@appearance = Hash.new(Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_NORMAL)
attr_reader :parent
def initialize(parent)
@parent = parent
reset_appearance
@treestore = TreeStore.new(Object::Object, String, Pango::FontDescription::Weight, Pango::FontDescription::Style, String, String, Fixnum)
super(@treestore)
signal_connect('cursor-changed') {
iter = selection.selected
if iter
obj = @treestore.get_value(iter, OBJCOL)
parent.hexview.load(obj)
parent.objectview.load(obj)
end
}
signal_connect('row-activated') { |tree, path, column|
if selection.selected
obj = @treestore.get_value(selection.selected, OBJCOL)
if row_expanded?(path)
collapse_row(path)
else
expand_row(path, false)
end
goto(obj) if obj.is_a?(Origami::Reference)
end
}
signal_connect('row-expanded') { |tree, iter, path|
obj = @treestore.get_value(iter, OBJCOL)
if obj.is_a?(Origami::Stream) and iter.n_children == 1
# Processing with an XRef or Object Stream
if obj.is_a?(Origami::ObjectStream)
obj.each { |embeddedobj|
load_object(iter, embeddedobj)
}
elsif obj.is_a?(Origami::XRefStream)
obj.each { |xref|
load_xrefstm(iter, xref)
}
end
end
for i in 0...iter.n_children
subiter = iter.nth_child(i)
subobj = @treestore.get_value(subiter, OBJCOL)
load_sub_objects(subiter, subobj)
end
}
add_events(Gdk::Event::BUTTON_PRESS_MASK)
signal_connect('button_press_event') { |widget, event|
if event.button == 3 && parent.opened
path = get_path(event.x,event.y).first
set_cursor(path, nil, false)
obj = @treestore.get_value(@treestore.get_iter(path), OBJCOL)
popup_menu(obj, event, path)
end
}
end
def clear
@treestore.clear
end
def goto(obj, follow_references: true)
if obj.is_a?(TreePath)
set_cursor(obj, nil, false)
else
if obj.is_a?(Origami::Name) and obj.parent.is_a?(Origami::Dictionary) and obj.parent.has_key?(obj)
obj = obj.parent[obj]
elsif obj.is_a?(Origami::Reference) and follow_references
obj =
begin
obj.solve
rescue Origami::InvalidReferenceError
@parent.error("Object not found : #{obj}")
return
end
end
_, path = object_to_tree_pos(obj)
if path.nil?
@parent.error("Object not found : #{obj.type}")
return
end
expand_to_path(path) unless row_expanded?(path)
@parent.explorer_history << cursor.first if cursor.first
set_cursor(path, nil, false)
end
end
def highlight(obj, color)
if obj.is_a?(Origami::Name) and obj.parent.is_a?(Origami::Dictionary) and obj.parent.has_key?(obj)
obj = obj.parent[obj]
end
iter, path = object_to_tree_pos(obj)
if iter.nil? or path.nil?
@parent.error("Object not found : #{obj.type}")
return
end
@treestore.set_value(iter, BGCOL, color)
expand_to_path(path) unless row_expanded?(path)
end
def load(pdf)
return unless pdf
self.clear
begin
#
# Create root entry
#
root = @treestore.append(nil)
@treestore.set_value(root, OBJCOL, pdf)
set_node(root, :Filename, @parent.filename)
#
# Create header entry
#
header = @treestore.append(root)
@treestore.set_value(header, OBJCOL, pdf.header)
set_node(header, :Header,
"Header (version #{pdf.header.major_version}.#{pdf.header.minor_version})")
no = 1
pdf.revisions.each { |revision|
load_revision(root, no, revision)
no = no + 1
}
set_model(@treestore)
ensure
expand(@treestore.iter_first, 3)
set_cursor(@treestore.iter_first.path, nil, false)
end
end
private
def object_to_tree_pos(obj)
# Locate the indirect object.
root_obj = obj
object_path = [ root_obj ]
while root_obj.parent
root_obj = root_obj.parent
object_path.push(root_obj)
end
@treestore.each do |model, path, iter|
current_obj = @treestore.get_value(iter, OBJCOL)
# Load the intermediate nodes if necessary.
if object_path.any?{|object| object.equal?(current_obj)}
load_sub_objects(iter, current_obj)
end
# Unfold the object stream if it's in the object path.
if obj.is_a?(Origami::Object) and current_obj.is_a?(Origami::ObjectStream) and
root_obj.equal?(current_obj) and iter.n_children == 1
current_obj.each { |embeddedobj|
load_object(iter, embeddedobj)
}
end
return [ iter, path ] if obj.equal?(current_obj)
end
nil
end
def expand(row, depth)
if row and depth != 0
loop do
expand_row(row.path, false)
expand(row.first_child, depth - 1)
break if not row.next!
end
end
end
def load_revision(root, no, revision)
revroot = @treestore.append(root)
@treestore.set_value(revroot, OBJCOL, revision)
set_node(revroot, :Revision, "Revision #{no}")
load_body(revroot, revision.body.values)
load_xrefs(revroot, revision.xreftable)
load_trailer(revroot, revision.trailer)
end
def load_body(rev, body)
bodyroot = @treestore.append(rev)
@treestore.set_value(bodyroot, OBJCOL, body)
set_node(bodyroot, :Body, "Body")
body.sort_by{|obj| obj.file_offset.to_i }.each { |object|
begin
load_object(bodyroot, object)
rescue
msg = "#{$!.class}: #{$!.message}\n#{$!.backtrace.join($/)}"
STDERR.puts(msg)
#@parent.error(msg)
next
end
}
end
def load_object(container, object, depth = 1, name = nil)
iter = @treestore.append(container)
@treestore.set_value(iter, OBJCOL, object)
type = object.native_type.to_s.split('::').last.to_sym
if name.nil?
name =
case object
when Origami::String
'"' + object.to_utf8.gsub("\x00", ".") + '"'
when Origami::Number, Origami::Name
object.value.to_s
else
object.type.to_s
end
end
set_node(iter, type, name)
return unless depth > 0
load_sub_objects(iter, object, depth)
end
def load_sub_objects(container, object, depth = 1)
return unless depth > 0 and @treestore.get_value(container, LOADCOL) != 1
case object
when Origami::Array
object.each do |subobject|
load_object(container, subobject, depth - 1)
end
when Origami::Dictionary
object.each_key do |subkey|
load_object(container, object[subkey.value], depth - 1, subkey.value.to_s)
end
when Origami::Stream
load_object(container, object.dictionary, depth - 1, "Stream Dictionary")
end
@treestore.set_value(container, LOADCOL, 1)
end
def load_xrefstm(stm, embxref)
xref = @treestore.append(stm)
@treestore.set_value(xref, OBJCOL, embxref)
if embxref.is_a?(Origami::XRef)
set_node(xref, :XRef, embxref.to_s.chomp)
else
set_node(xref, :XRef, "xref to ObjectStream #{embxref.objstmno}, object index #{embxref.index}")
end
end
def load_xrefs(rev, table)
return unless table
section = @treestore.append(rev)
@treestore.set_value(section, OBJCOL, table)
set_node(section, :XRefSection, "XRef section")
table.each_subsection { |subtable|
subsection = @treestore.append(section)
@treestore.set_value(subsection, OBJCOL, subtable)
set_node(subsection, :XRefSubSection, "#{subtable.range.begin} #{subtable.range.end - subtable.range.begin + 1}")
subtable.each { |entry|
xref = @treestore.append(subsection)
@treestore.set_value(xref, OBJCOL, entry)
set_node(xref, :XRef, entry.to_s.chomp)
}
}
end
def load_trailer(rev, trailer)
trailer_root = @treestore.append(rev)
@treestore.set_value(trailer_root, OBJCOL, trailer)
set_node(trailer_root, :Trailer, "Trailer")
load_object(trailer_root, trailer.dictionary) unless trailer.dictionary.nil?
end
def reset_appearance
@@appearance[:Filename] = {Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Header] = {Color: "darkgreen", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Revision] = {Color: "blue", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Body] = {Color: "purple", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:XRefSection] = {Color: "purple", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:XRefSubSection] = {Color: "brown", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:XRef] = {Color: "gray20", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Trailer] = {Color: "purple", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:StartXref] = {Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:String] = {Color: "red", Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_ITALIC}
@@appearance[:Name] = {Color: "gray", Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_ITALIC}
@@appearance[:Number] = {Color: "orange", Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_NORMAL}
@@appearance[:Dictionary] = {Color: "brown", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Stream] = {Color: "darkcyan", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:StreamData] = {Color: "darkcyan", Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_OBLIQUE}
@@appearance[:Array] = {Color: "darkgreen", Weight: Pango::WEIGHT_BOLD, Style: Pango::STYLE_NORMAL}
@@appearance[:Reference] = {Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_OBLIQUE}
@@appearance[:Boolean] = {Color: "deeppink", Weight: Pango::WEIGHT_NORMAL, Style: Pango::STYLE_NORMAL}
end
def get_object_appearance(type)
@@appearance[type]
end
def set_node(node, type, text)
@treestore.set_value(node, TEXTCOL, text)
app = get_object_appearance(type)
@treestore.set_value(node, WEIGHTCOL, app[:Weight])
@treestore.set_value(node, STYLECOL, app[:Style])
@treestore.set_value(node, FGCOL, app[:Color])
end
end
end
origami-2.0.0/bin/gui/COPYING 0000644 0000041 0000041 00000104513 12757133666 015603 0 ustar www-data www-data GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
origami-2.0.0/bin/pdfmetadata 0000755 0000041 0000041 00000006022 12757133666 016160 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Prints out the metadata contained in a PDF document.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'colorize'
require 'optparse'
class OptParser
BANNER = <] [-i] [-x]
Prints out the metadata contained in a PDF document.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-i", "Extracts document info metadata") do |i|
options[:doc_info] = true
end
opts.on("-x", "Extracts XMP document metadata stream") do |i|
options[:doc_stream] = true
end
opts.on("-n", "Turn off colorized output.") do
options[:disable_colors] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
disable_colors: false
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
unless @options[:doc_info] or @options[:doc_stream]
@options[:doc_info] = @options[:doc_stream] = true
end
String.disable_colorization @options[:disable_colors]
target = (ARGV.empty?) ? STDIN : ARGV.shift
params =
{
verbosity: Parser::VERBOSE_QUIET,
lazy: true
}
pdf = PDF.read(target, params)
if @options[:doc_info] and pdf.document_info?
puts "[*] Document information dictionary:".magenta
docinfo = pdf.document_info
docinfo.each_pair do |name, item|
obj = item.solve
print name.value.to_s.ljust(20, ' ').green
puts ": #{obj.respond_to?(:to_utf8) ? obj.to_utf8 : obj.value}"
end
puts
end
if @options[:doc_stream] and pdf.metadata?
puts "[*] Metadata stream:".magenta
metadata = pdf.metadata
metadata.each_pair do |name, item|
print name.ljust(20, ' ').green
puts ": #{item}"
end
end
rescue
abort "#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdfcop 0000755 0000041 0000041 00000033314 12757133666 015165 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
This is a PDF document filtering engine using Origami.
Security policies are based on a white list of PDF features.
Default policies details can be found in the default configuration file.
You can also add your own policy and activate it using the -p switch.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
require 'optparse'
require 'yaml'
require 'rexml/document'
require 'digest/md5'
require 'colorize'
DEFAULT_CONFIG_FILE = "#{File.dirname(__FILE__)}/config/pdfcop.conf.yml"
DEFAULT_POLICY = "standard"
SECURITY_POLICIES = {}
def load_config_file(path)
SECURITY_POLICIES.update(Hash.new(false).update YAML.load(File.read(path)))
end
class OptParser
BANNER = <
The PDF filtering engine. Scans PDF documents for malicious structures.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parse(args)
options = {colors: true}
opts = OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-o", "--output LOG_FILE", "Output log file (default STDOUT)") do |o|
options[:output_log] = o
end
opts.on("-c", "--config CONFIG_FILE", "Load security policies from given configuration file") do |cf|
options[:config_file] = cf
end
opts.on("-p", "--policy POLICY_NAME", "Specify applied policy. Predefined policies: 'none', 'standard', 'strong', 'paranoid'") do |p|
options[:policy] = p
end
opts.on("-n", "--no-color", "Turn off colorized output") do
options[:disable_colors] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opts.parse!(args)
options
end
end
@options = OptParser.parse(ARGV)
if @options.has_key?(:output_log)
LOGGER = File.open(@options[:output_log], "a+")
else
LOGGER = STDOUT
end
if not @options.has_key?(:policy)
@options[:policy] = DEFAULT_POLICY
end
String.disable_colorization @options[:disable_colors]
load_config_file(@options[:config_file] || DEFAULT_CONFIG_FILE)
unless SECURITY_POLICIES.has_key?("POLICY_#{@options[:policy].upcase}")
abort "Undeclared policy `#{@options[:policy]}'"
end
if ARGV.empty?
abort "Error: No filename was specified. #{$0} --help for details."
else
TARGET = ARGV.shift
end
def log(str, color = :default)
LOGGER.puts("[#{Time.now}]".cyan + " #{str.colorize(color)}")
end
def reject(cause)
log("Document rejected by policy `#{@options[:policy]}', caused by #{cause.inspect}.", :red)
abort
end
def check_rights(*required_rights)
current_rights = SECURITY_POLICIES["POLICY_#{@options[:policy].upcase}"]
reject(required_rights) if required_rights.any?{|right| current_rights[right.to_s] == false}
end
def analyze_xfa_forms(xfa)
case xfa
when Origami::Array then
xml = ""
i = 0
xfa.each do |packet|
if i % 2 == 1
xml << packet.solve.data
end
i = i + 1
end
when Origami::Stream then
xml = xfa.data
else
reject("Malformed XFA dictionary")
end
xfadoc = REXML::Document.new(xml)
REXML::XPath.match(xfadoc, "//script").each do |script|
case script.attributes["contentType"]
when "application/x-formcalc" then
check_rights(:allowFormCalc)
else
check_rights(:allowJS)
end
end
end
def analyze_annotation(annot, level = 0)
check_rights(:allowAnnotations)
if annot.is_a?(Origami::Dictionary) and annot.has_key?(:Subtype)
case annot[:Subtype].solve.value
when :FileAttachment
check_rights(:allowAttachments, :allowFileAttachmentAnnotation)
when :Sound
check_rights(:allowSoundAnnotation)
when :Movie
check_rights(:allowMovieAnnotation)
when :Screen
check_rights(:allowScreenAnnotation)
when :Widget
check_rights(:allowAcroforms)
when :"3D"
check_rights(:allow3DAnnotation)
# 3D annotation might pull in JavaScript for real-time driven behavior.
if annot.has_key?(:"3DD")
dd = annot[:"3DD"].solve
u3dstream = nil
case dd
when Origami::Stream
u3dstream = dd
when Origami::Dictionary
u3dstream = dd[:"3DD"]
end
if u3dstream and u3dstream.has_field?(:OnInstantiate)
check_rights(:allowJS)
if annot.has_key?(:"3DA") # is 3d view instantiated automatically?
u3dactiv = annot[:"3DA"].solve
check_rights(:allowJSAtOpening) if u3dactiv.is_a?(Origami::Dictionary) and (u3dactiv[:A] == :PO or u3dactiv[:A] == :PV)
end
end
end
when :RichMedia
check_rights(:allowRichMediaAnnotation)
end
end
end
def analyze_page(page, level = 0)
section_prefix = " " * 2 * level + ">" * (level + 1)
log(section_prefix + " Inspecting page...")
text_prefix = " " * 2 * (level + 1) + "." * (level + 1)
if page.is_a?(Origami::Dictionary)
#
# Checking page additional actions.
#
if page.has_key?(:AA)
if page.AA.is_a?(Origami::Dictionary)
log(text_prefix + " Page has an action dictionary.")
aa = Origami::Page::AdditionalActions.new(page.AA); aa.parent = page.AA.parent
analyze_action(aa.O, true, level + 1) if aa.has_key?(:O)
analyze_action(aa.C, false, level + 1) if aa.has_key?(:C)
end
end
#
# Looking for page annotations.
#
page.each_annotation do |annot|
analyze_annotation(annot, level + 1)
end
end
end
def analyze_action(action, triggered_at_opening, level = 0)
section_prefix = " " * 2 * level + ">" * (level + 1)
log(section_prefix + " Inspecting action...")
text_prefix = " " * 2 * (level + 1) + "." * (level + 1)
if action.is_a?(Origami::Dictionary)
log(text_prefix + " Found #{action[:S]} action.")
type = action[:S].is_a?(Origami::Reference) ? action[:S].solve : action[:S]
case type.value
when :JavaScript
check_rights(:allowJS)
check_rights(:allowJSAtOpening) if triggered_at_opening
when :Launch
check_rights(:allowLaunchAction)
when :Named
check_rights(:allowNamedAction)
when :GoTo
check_rights(:allowGoToAction)
dest = action[:D].is_a?(Origami::Reference) ? action[:D].solve : action[:D]
if dest.is_a?(Origami::Array) and dest.length > 0 and dest.first.is_a?(Origami::Reference)
dest_page = dest.first.solve
if dest_page.is_a?(Origami::Page)
log(text_prefix + " Destination page found.")
analyze_page(dest_page, level + 1)
end
end
when :GoToE
check_rights(:allowAttachments,:allowGoToEAction)
when :GoToR
check_rights(:allowGoToRAction)
when :Thread
check_rights(:allowGoToRAction) if action.has_key?(:F)
when :URI
check_rights(:allowURIAction)
when :SubmitForm
check_rights(:allowAcroForms,:allowSubmitFormAction)
when :ImportData
check_rights(:allowAcroForms,:allowImportDataAction)
when :Rendition
check_rights(:allowScreenAnnotation,:allowRenditionAction)
when :Sound
check_rights(:allowSoundAnnotation,:allowSoundAction)
when :Movie
check_rights(:allowMovieAnnotation,:allowMovieAction)
when :RichMediaExecute
check_rights(:allowRichMediaAnnotation,:allowRichMediaAction)
when :GoTo3DView
check_rights(:allow3DAnnotation,:allowGoTo3DAction)
end
if action.has_key?(:Next)
log(text_prefix + "This action is chained to another action!")
check_rights(:allowChainedActions)
analyze_action(action.Next)
end
elsif action.is_a?(Origami::Array)
dest = action
if dest.length > 0 and dest.first.is_a?(Origami::Reference)
dest_page = dest.first.solve
if dest_page.is_a?(Origami::Page)
log(text_prefix + " Destination page found.")
check_rights(:allowGoToAction)
analyze_page(dest_page, level + 1)
end
end
end
end
begin
log("PDFcop is running on target `#{TARGET}', policy = `#{@options[:policy]}'", :green)
log(" File size: #{File.size(TARGET)} bytes", :magenta)
log(" MD5: #{Digest::MD5.hexdigest(File.read(TARGET))}", :magenta)
@pdf = Origami::PDF.read(TARGET,
verbosity: Origami::Parser::VERBOSE_QUIET,
ignore_errors: SECURITY_POLICIES["POLICY_#{@options[:policy].upcase}"]['allowParserErrors']
)
log("> Inspecting document structure...", :yellow)
if @pdf.encrypted?
log(" . Encryption = YES")
check_rights(:allowEncryption)
end
log("> Inspecting document catalog...", :yellow)
catalog = @pdf.Catalog
reject("Invalid document catalog") unless catalog.is_a?(Origami::Catalog)
if catalog.has_key?(:OpenAction)
log(" . OpenAction entry = YES")
check_rights(:allowOpenAction)
action = catalog.OpenAction
analyze_action(action, true, 1)
end
if catalog.has_key?(:AA)
if catalog.AA.is_a?(Origami::Dictionary)
aa = Origami::CatalogAdditionalActions.new(catalog.AA); aa.parent = catalog;
log(" . Additional actions dictionary = YES")
analyze_action(aa.WC, false, 1) if aa.has_key?(:WC)
analyze_action(aa.WS, false, 1) if aa.has_key?(:WS)
analyze_action(aa.DS, false, 1) if aa.has_key?(:DS)
analyze_action(aa.WP, false, 1) if aa.has_key?(:WP)
analyze_action(aa.DP, false, 1) if aa.has_key?(:DP)
end
end
if catalog.has_key?(:AcroForm)
acroform = catalog.AcroForm
if acroform.is_a?(Origami::Dictionary)
log(" . AcroForm = YES")
check_rights(:allowAcroForms)
if acroform.has_key?(:XFA)
log(" . XFA = YES")
check_rights(:allowXFAForms)
analyze_xfa_forms(acroform[:XFA].solve)
end
end
end
log("> Inspecting JavaScript names directory...", :yellow)
if @pdf.each_named_script.any?
check_rights(:allowJS)
check_rights(:allowJSAtOpening)
end
log("> Inspecting attachment names directory...", :yellow)
if @pdf.each_attachment.any?
check_rights(:allowAttachments)
end
log("> Inspecting document pages...", :yellow)
@pdf.each_page do |page|
analyze_page(page, 1)
end
log("> Inspecting document streams...", :yellow)
@pdf.indirect_objects.find_all{|obj| obj.is_a?(Origami::Stream)}.each do |stream|
if stream.dictionary.has_key?(:Filter)
filters = stream.Filter
filters = [ filters ] if filters.is_a?(Origami::Name)
if filters.is_a?(Origami::Array)
filters.each do |filter|
case filter.value
when :ASCIIHexDecode
check_rights(:allowASCIIHexFilter)
when :ASCII85Decode
check_rights(:allowASCII85Filter)
when :LZWDecode
check_rights(:allowLZWFilter)
when :FlateDecode
check_rights(:allowFlateDecode)
when :RunLengthDecode
check_rights(:allowRunLengthFilter)
when :CCITTFaxDecode
check_rights(:allowCCITTFaxFilter)
when :JBIG2Decode
check_rights(:allowJBIG2Filter)
when :DCTDecode
check_rights(:allowDCTFilter)
when :JPXDecode
check_rights(:allowJPXFilter)
when :Crypt
check_rights(:allowCryptFilter)
end
end
end
end
end
#
# TODO: Detect JS at opening in XFA (check event tag)
# Check image encoding in XFA ?
# Only allow valid signed documents ?
# Recursively scan attached files.
# On-the-fly injection of prerun JS code to hook vulnerable methods (dynamic exploit detection) ???
# ...
#
log("Document accepted by policy `#{@options[:policy]}'.", :green)
rescue
log("An error occured during analysis : #{$!.class} (#{$!.message})")
reject("Analysis failure")
ensure
LOGGER.close
end
origami-2.0.0/bin/pdfencrypt 0000755 0000041 0000041 00000005731 12757133666 016072 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Encrypts a PDF document.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
class OptParser
BANNER = <] [-p ] [-c ] [-s ] [--hardened] [-o ]
Encrypts a PDF document. Supports RC4 40 to 128 bits, AES128, AES256.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-o", "--output FILE", "Output PDF file (stdout by default)") do |o|
options[:output] = o
end
opts.on("-p", "--password PASSWORD", "Password of the document") do |p|
options[:password] = p
end
opts.on("-c", "--cipher CIPHER", "Cipher used to encrypt the document (Default: AES)") do |c|
options[:cipher] = c
end
opts.on("-s", "--key-size KEYSIZE", "Key size in bits (Default: 128)") do |s|
options[:key_size] = s.to_i
end
opts.on("--hardened", "Use stronger key validation scheme (only AES-256)") do
options[:hardened] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
output: STDOUT,
password: '',
cipher: 'aes',
key_size: 128,
hardened: false
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
target = (ARGV.empty?) ? STDIN : ARGV.shift
params =
{
verbosity: Parser::VERBOSE_QUIET,
}
pdf = PDF.read(target, params)
pdf.encrypt(
user_passwd: @options[:password],
owner_passwd: @options[:password],
cipher: @options[:cipher],
key_size: @options[:key_size],
hardened: @options[:hardened]
)
pdf.save(@options[:output], noindent: true)
rescue
abort "#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdfexplode 0000755 0000041 0000041 00000016770 12757133666 016053 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Explodes a PDF into separate documents.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
require 'rexml/document'
class OptParser
BANNER = < [-r ] [-t pages|rsrc] [-d ]
Explodes a document into separate documents.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-d", "--output-dir DIR", "Output directory.") do |d|
options[:output_dir] = d
end
opts.on("-r", "--range PAGES", "Page range (e.g: 2-, 1-3, 5). Default to '-'.") do |r|
range =
if r.index('-').nil?
page = r.to_i
Range.new(page-1, page-1)
else
from, to = r.split('-').map{|bound| bound.to_i}
from ||= 1
to ||= 0
Range.new(from-1, to-1)
end
options[:page_range] = range
end
opts.on("-t", "--type TYPE", "Split by type. Can be 'pages' or 'rsrc'. Default to 'pages'.") do |t|
options[:split_by] = t
end
opts.on_tail("-h", "--help", "Show this message.") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
page_range: (0..-1),
split_by: 'pages'
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
if ARGV.empty?
abort "Error: No filename was specified. #{$0} --help for details."
else
target = ARGV.shift
end
if @options[:output_dir].nil?
@options[:output_dir] = "#{File.join(File.dirname(target), File.basename(target,'.pdf'))}.explode"
end
Origami::OPTIONS[:ignore_bad_references] = true
OUTPUT_DIR = @options[:output_dir]
Dir::mkdir(OUTPUT_DIR) unless File.directory?(OUTPUT_DIR)
def split_by_rsrc(n, page, type)
all_rsrc = page.resources
type_rsrc = page.resources(type)
other_rsrc = all_rsrc.keys - type_rsrc.keys
unless type_rsrc.empty?
# Keep only specified resource type.
output_file = File.join(OUTPUT_DIR, "page_#{n}_keeponly_#{type}.pdf")
PDF.write(output_file) do |pdf|
reduced = page.copy
# New resource dictionary with only matching resources.
reduced.Resources = Resources.new(type => type_rsrc)
# Remove mention of other resources.
reduced.each_content_stream do |stream|
stream.data = stream.data.lines.
delete_if {|line| other_rsrc.any?{|rsrc| line =~ /#{rsrc}/}}.join
end
STDERR.puts "Creating #{output_file}..."
pdf.append_page(reduced)
end
# Remove all specified resource type.
output_file = File.join(OUTPUT_DIR, "page_#{n}_excluded_#{type}.pdf")
PDF.write(output_file) do |pdf|
reduced = page.copy
# New resource dictionary with no resource of specified type.
reduced.Resources = reduced.Resources.copy
reduced.Resources.delete(type)
# Remove mention this resource type.
reduced.each_content_stream do |stream|
stream.data = stream.data.lines.
delete_if {|line| type_rsrc.keys.any?{|rsrc| line =~ /#{rsrc}/}}.join
end
STDERR.puts "Creating #{output_file}..."
pdf.append_page(reduced)
end
# Now treating each resource object separately.
type_rsrc.each_pair do |name, rsrc|
anyother_rsrc = all_rsrc.keys - [ name ]
# Keey only specified resource object.
output_file = File.join(OUTPUT_DIR, "page_#{n}_keeponly_#{type}_#{name}.pdf")
PDF.write(output_file) do |pdf|
reduced = page.copy
# New resource dictionary with only specified resource object.
reduced.Resources = Resources.new(type => {name => rsrc})
# Remove mention of all other resources.
reduced.each_content_stream do |stream|
stream.data = stream.data.lines.
delete_if {|line| anyother_rsrc.any?{|rsrc| line =~ /#{rsrc}/}}.join
end
STDERR.puts "Creating #{output_file}..."
pdf.append_page(reduced)
end
# Remove only specified resource object.
output_file = File.join(OUTPUT_DIR, "page_#{n}_excluded_#{type}_#{name}.pdf")
PDF.write(output_file) do |pdf|
reduced = page.copy
# New resource dictionary with only specified resource object.
reduced.Resources = reduced.Resources.copy
reduced.Resources[type] = reduced.Resources.send(type).copy
reduced.Resources[type].delete(name)
# Remove mention of this resource only.
reduced.each_content_stream do |stream|
stream.data = stream.data.lines.
delete_if {|line| line =~ /#{name}/}.join
end
STDERR.puts "Creating #{output_file}..."
pdf.append_page(reduced)
end
end
end
end
params =
{
verbosity: Parser::VERBOSE_QUIET,
}
pdf = PDF.read(target, params)
i = @options[:page_range].first + 1
pdf.pages[@options[:page_range]].each do |page|
case @options[:split_by]
when 'pages'
output_file = File.join(OUTPUT_DIR, "page_#{i}.pdf")
PDF.write(output_file) do |pdf|
STDERR.puts "Creating #{output_file}..."
pdf.append_page(page)
end
when 'rsrc'
[ Resources::EXTGSTATE,
Resources::COLORSPACE,
Resources::PATTERN,
Resources::SHADING,
Resources::XOBJECT,
Resources::FONT,
Resources::PROPERTIES
].each { |type| split_by_rsrc(i, page, type) }
else
raise ArgumentError, "Unknown split option: #{@options[:split_by]}"
end
i += 1
end
rescue
abort "#{$!.class}: #{$!.message} #{$!.backtrace.join($/)}"
end
origami-2.0.0/bin/pdfdecompress 0000755 0000041 0000041 00000004517 12757133666 016553 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Uncompresses all binary streams of a PDF document.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
class OptParser
BANNER = <] [-p ] [-o ]
Uncompresses all binary streams of a PDF document.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-o", "--output FILE", "Output PDF file (stdout by default)") do |o|
options[:output] = o
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
output: STDOUT,
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
target = (ARGV.empty?) ? STDIN : ARGV.shift
params =
{
verbosity: Parser::VERBOSE_QUIET,
}
pdf = PDF.read(target, params)
pdf.root_objects.find_all { |obj|
obj.is_a?(Stream)
}.each { |stream|
unless stream.filters.any?{|filter| %i[JPXDecode DCTDecode JBIG2Decode].include?(filter.value) }
stream.encoded_data = stream.data
stream.dictionary.delete(:Filter)
end
}
pdf.save(@options[:output], noindent: true)
rescue
STDERR.puts $!.backtrace.join($/)
abort "#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdfsh 0000755 0000041 0000041 00000000356 12757133666 015016 0 ustar www-data www-data #!/usr/bin/env ruby
begin
require 'irb'
rescue LoadError
abort "Error: you need to install irb to run this application."
end
$:.unshift File.join(__dir__, 'shell')
ENV["IRBRC"] = File.join(__dir__, "shell", ".irbrc")
IRB.start
origami-2.0.0/bin/config/ 0000755 0000041 0000041 00000000000 12757133666 015225 5 ustar www-data www-data origami-2.0.0/bin/config/pdfcop.conf.yml 0000644 0000041 0000041 00000012303 12757133666 020146 0 ustar www-data www-data ---
POLICY_NONE:
#
# General features.
#
allowParserErrors: true
allowAttachments: true
allowEncryption: true
allowFormCalc: true
allowJSAtOpening: true
allowJS: true
allowAcroForms: true
allowXFAForms: true
#
# Page annotations.
#
allowAnnotations: true
allow3DAnnotation: true
allowFileAttachmentAnnotation: true
allowMovieAnnotation: true
allowRichMediaAnnotation: true
allowScreenAnnotation: true
allowSoundAnnotation: true
#
# PDF Actions.
#
allowChainedActions: true
allowOpenAction: true
allowGoTo3DAction: true
allowGoToAction: true
allowGoToEAction: true
allowGoToRAction: true
allowImportDataAction: true
allowJSAction: true
allowLaunchAction: true
allowMovieAction: true
allowNamedAction: true
allowRenditionAction: true
allowRichMediaAction: true
allowSoundAction: true
allowSubmitFormAction: true
allowURIAction: true
#
# Stream filters.
#
allowASCII85Filter: true
allowASCIIHexFilter: true
allowCCITTFaxFilter: true
allowCryptFilter: true
allowDCTFilter: true
allowFlateFilter: true
allowJBIG2Filter: true
allowJPXFilter: true
allowLZWFilter: true
allowRunLengthFilter: true
POLICY_STANDARD:
#
# General features.
#
allowParserErrors: false
allowAttachments: false
allowAcroForms: true
allowEncryption: true
allowFormCalc: true
allowJS: true
allowJSAtOpening: false
allowXFAForms: true
#
# Page annotations.
#
allowAnnotations: true
allow3DAnnotation: false
allowFileAttachmentAnnotation: false
allowMovieAnnotation: false
allowRichMediaAnnotation: false
allowScreenAnnotation: false
allowSoundAnnotation: false
#
# PDF Actions.
#
allowChainedActions: true
allowOpenAction: true
allowGoTo3DAction: false
allowGoToAction: true
allowGoToEAction: false
allowGoToRAction: false
allowImportDataAction: false
allowJSAction: true
allowLaunchAction: false
allowMovieAction: false
allowNamedAction: false
allowRenditionAction: false
allowRichMediaAction: false
allowSoundAction: false
allowSubmitFormAction: true
allowURIAction: true
#
# Stream filters.
#
allowASCII85Filter: false
allowASCIIHexFilter: false
allowCCITTFaxFilter: true
allowCryptFilter: true
allowDCTFilter: true
allowFlateFilter: true
allowJBIG2Filter: false
allowJPXFilter: false
allowLZWFilter: false
allowRunLengthFilter: false
POLICY_STRONG:
#
# General features.
#
allowParserErrors: false
allowAttachments: false
allowAcroForms: false
allowEncryption: true
allowFormCalc: true
allowJS: false
allowJSAtOpening: false
allowXFAForms: false
#
# Page annotations.
#
allowAnnotations: true
allow3DAnnotation: false
allowFileAttachmentAnnotation: false
allowMovieAnnotation: false
allowRichMediaAnnotation: false
allowScreenAnnotation: false
allowSoundAnnotation: false
#
# PDF Actions.
#
allowChainedActions: false
allowOpenAction: true
allowGoTo3DAction: false
allowGoToAction: true
allowGoToEAction: false
allowGoToRAction: false
allowImportDataAction: false
allowJSAction: false
allowLaunchAction: false
allowMovieAction: false
allowNamedAction: false
allowRenditionAction: false
allowRichMediaAction: false
allowSoundAction: false
allowSubmitFormAction: false
allowURIAction: true
#
# Stream filters.
#
allowASCII85Filter: false
allowASCIIHexFilter: false
allowCCITTFaxFilter: false
allowCryptFilter: true
allowDCTFilter: true
allowFlateFilter: true
allowJBIG2Filter: false
allowJPXFilter: false
allowLZWFilter: false
allowRunLengthFilter: false
POLICY_PARANOID:
#
# General features.
#
allowParserErrors: false
allowAttachments: false
allowAcroForms: false
allowEncryption: false
allowFormCalc: false
allowJS: false
allowJSAtOpening: false
allowXFAForms: false
#
# Page annotations.
#
allowAnnotations: true
allow3DAnnotation: false
allowFileAttachmentAnnotation: false
allowMovieAnnotation: false
allowRichMediaAnnotation: false
allowScreenAnnotation: false
allowSoundAnnotation: false
#
# PDF Actions.
#
allowChainedActions: false
allowOpenAction: false
allowGoTo3DAction: false
allowGoToAction: true
allowGoToEAction: false
allowGoToRAction: false
allowImportDataAction: false
allowJSAction: false
allowLaunchAction: false
allowMovieAction: false
allowNamedAction: false
allowRenditionAction: false
allowRichMediaAction: false
allowSoundAction: false
allowSubmitFormAction: false
allowURIAction: false
#
# Stream filters.
#
allowASCII85Filter: false
allowASCIIHexFilter: false
allowCCITTFaxFilter: false
allowCryptFilter: false
allowDCTFilter: true
allowFlateFilter: true
allowJBIG2Filter: false
allowJPXFilter: false
allowLZWFilter: false
allowRunLengthFilter: false
origami-2.0.0/bin/shell/ 0000755 0000041 0000041 00000000000 12757133666 015067 5 ustar www-data www-data origami-2.0.0/bin/shell/hexdump.rb 0000644 0000041 0000041 00000003413 12757133666 017067 0 ustar www-data www-data =begin
This file is part of Origami, PDF manipulation framework for Ruby
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Origami. If not, see .
=end
require 'colorize'
class String #:nodoc:
def hexdump(bytesperline: 16, upcase: true, offsets: true, delta: 0)
dump = ""
counter = 0
while counter < length
offset = sprintf("%010X", counter + delta)
linelen = (counter < length - bytesperline) ? bytesperline : (length - counter)
bytes = ""
linelen.times do |i|
byte = self[counter + i].ord.to_s(16)
byte.insert(0, "0") if byte.size < 2
bytes << byte
bytes << " " unless i == bytesperline - 1
end
ascii = self[counter, linelen].ascii_print
if upcase
offset.upcase!
bytes.upcase!
end
dump << "#{offset.yellow if offsets} #{bytes.to_s.ljust(bytesperline * 3 - 1).bold} #{ascii}\n"
counter += bytesperline
end
dump
end
def ascii_print
self.gsub(/[^[[:print:]]]/, ".")
end
end
origami-2.0.0/bin/shell/.irbrc 0000644 0000041 0000041 00000003264 12757133666 016176 0 ustar www-data www-data begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../../lib')
require 'origami'
end
include Origami
require 'console.rb'
require 'readline'
OPENSSL_SUPPORT = (defined?(OpenSSL).nil?) ? 'no' : 'yes'
JAVASCRIPT_SUPPORT = (defined?(PDF::JavaScript::Engine).nil?) ? 'no' : 'yes'
DEFAULT_BANNER = "Welcome to the PDF shell (Origami release #{Origami::VERSION}) [OpenSSL: #{OPENSSL_SUPPORT}, JavaScript: #{JAVASCRIPT_SUPPORT}]\n"
def set_completion
completionProc = proc { |input|
bind = IRB.conf[:MAIN_CONTEXT].workspace.binding
case input
when /^(.*)::$/
begin
space = eval("Origami::#{$1}", bind)
rescue Exception
return []
end
return space.constants.reject{|const| space.const_get(const) <= Exception}
when /^(.*).$/
begin
space = eval($1, bind)
rescue
return []
end
return space.public_methods
end
}
if Readline.respond_to?("basic_word_break_characters=")
Readline.basic_word_break_characters= " \t\n\"\\'`><=;|&{("
end
Readline.completion_append_character = nil
Readline.completion_proc = completionProc
end
def set_prompt
IRB.conf[:PROMPT][:PDFSH] = {
PROMPT_C: "?>> ",
RETURN: "%s\n",
PROMPT_I: ">>> ",
PROMPT_N: ">>> ",
PROMPT_S: nil
}
IRB.conf[:PROMPT_MODE] = :PDFSH
IRB.conf[:AUTO_INDENT] = true
end
# Print the shell banner.
puts DEFAULT_BANNER.green
# Import the type conversion helper routines.
TOPLEVEL_BINDING.eval("using Origami::TypeConversion")
#set_completion
set_prompt
origami-2.0.0/bin/shell/console.rb 0000644 0000041 0000041 00000006741 12757133666 017066 0 ustar www-data www-data =begin
This file is part of Origami, PDF manipulation framework for Ruby
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
require 'tempfile'
require 'hexdump'
require 'colorize'
String.disable_colorization(false)
module Origami
module Object
def inspect
to_s
end
end
class Stream
def edit(editor = ENV['EDITOR'])
Tempfile.open("origami") do |tmpfile|
tmpfile.write(self.data)
tmpfile.flush
Process.wait Kernel.spawn "#{editor} #{tmpfile.path}"
self.data = File.read(tmpfile.path)
tmpfile.unlink
end
true
end
def inspect
self.data.hexdump
end
end
class Page < Dictionary
def edit
each_content_stream do |stream|
stream.edit
end
end
end
class PDF
if defined?(PDF::JavaScript::Engine)
class JavaScript::Engine
def shell
while (print 'js> '.magenta; line = gets)
begin
puts exec(line)
rescue V8::JSError => e
puts "Error: #{e.message}"
end
end
end
end
end
class Revision
def to_s
puts "---------- Body ----------".white.bold
@body.each_value { |obj|
print "#{obj.reference.to_s.rjust(8,' ')}".ljust(10).magenta
puts "#{obj.type}".yellow
}
puts "---------- Trailer ---------".white.bold
if not @trailer.dictionary
puts " [x] No trailer found.".blue
else
@trailer.dictionary.each_pair { |entry, value|
print " [*] ".magenta
print "#{entry.to_s}: ".yellow
puts "#{value.to_s}".red
}
print " [+] ".magenta
print "startxref: ".yellow
puts "#{@trailer.startxref}".red
end
end
def inspect
to_s
end
end
def to_s
puts
puts "---------- Header ----------".white.bold
print " [+] ".magenta
print "Version: ".yellow
puts "#{@header.major_version}.#{@header.minor_version}".red
@revisions.each { |revision|
revision.to_s
}
puts
end
def inspect
to_s
end
end
end
origami-2.0.0/bin/pdfextract 0000755 0000041 0000041 00000020147 12757133666 016056 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Extracts valuable data from a PDF document. Can extract:
- decoded streams
- JavaScript
- file attachments
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
require 'rexml/document'
class OptParser
BANNER = < [-afjms] [-d ]
Extracts various data out of a document (streams, scripts, images, fonts, metadata, attachments).
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-d", "--output-dir DIR", "Output directory") do |d|
options[:output_dir] = d
end
opts.on("-s", "--streams", "Extracts all decoded streams") do
options[:streams] = true
end
opts.on("-a", "--attachments", "Extracts file attachments") do
options[:attachments] = true
end
opts.on("-f", "--fonts", "Extracts embedded font files") do
options[:fonts] = true
end
opts.on("-j", "--js", "Extracts JavaScript scripts") do
options[:javascript] = true
end
opts.on("-m", "--metadata", "Extracts metadata streams") do
options[:metadata] = true
end
opts.on("-i", "--images", "Extracts embedded images") do
options[:images] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options = {}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
if ARGV.empty?
abort "Error: No filename was specified. #{$0} --help for details."
else
target = ARGV.shift
end
unless %i[streams javascript attachments fonts metadata images].any? {|opt| @options[opt]}
@options[:streams] =
@options[:javascript] =
@options[:fonts] =
@options[:attachments] =
@options[:images] = true
end
if @options[:output_dir].nil?
@options[:output_dir] = "#{File.basename(target, '.pdf')}.dump"
end
# Force data extraction, even for invalid FlateDecode streams.
Origami::OPTIONS[:ignore_zlib_errors] = true
Origami::OPTIONS[:ignore_png_errors] = true
OUTPUT_DIR = @options[:output_dir]
Dir::mkdir(OUTPUT_DIR) unless File.directory?(OUTPUT_DIR)
params =
{
verbosity: Parser::VERBOSE_QUIET,
}
pdf = PDF.read(target, params)
if @options[:streams]
nstreams = 0
stream_dir = File.join(OUTPUT_DIR, "streams")
Dir::mkdir(stream_dir) unless File.directory?(stream_dir)
pdf.root_objects.find_all{|obj| obj.is_a?(Stream)}.each do |stream|
stream_file = File.join(stream_dir, "stream_#{stream.reference.refno}.dmp")
File.binwrite(stream_file, stream.data)
nstreams += 1
end
puts "Extracted #{nstreams} PDF streams to '#{stream_dir}'."
end
if @options[:javascript]
nscripts = 0
js_dir = File.join(OUTPUT_DIR, "scripts")
Dir::mkdir(js_dir) unless File.directory?(js_dir)
pdf.ls(/^JS$/).each do |script|
script_file = File.join(js_dir, "script_#{script.hash}.js")
script_data =
case script
when Stream then script.data
else script.value
end
File.binwrite(script_file, script_data)
nscripts += 1
end
# Also checking for presence of JavaScript in XML forms.
if pdf.form? and pdf.Catalog.AcroForm.has_key?(:XFA)
xfa = pdf.Catalog.AcroForm[:XFA].solve
case xfa
when Array then
xml = ""
i = 0
xfa.each do |packet|
if i % 2 == 1
xml << packet.solve.data
end
i = i + 1
end
when Stream then
xml = xfa.data
else
reject("Malformed XFA dictionary")
end
xfadoc = REXML::Document.new(xml)
REXML::XPath.match(xfadoc, "//script").each do |script|
script_file = File.join(js_dir, "script_#{script.hash}.js")
File.binwrite(script_file, script.text)
nscripts += 1
end
end
puts "Extracted #{nscripts} scripts to '#{js_dir}'."
end
if @options[:attachments]
nattach = 0
attachments_dir = File.join(OUTPUT_DIR, "attachments")
Dir::mkdir(attachments_dir) unless File.directory?(attachments_dir)
pdf.each_attachment do |name, attachment|
attached_file = File.join(attachments_dir, "attached_#{File.basename(name)}")
spec = attachment.solve
if spec and spec.EF and f = spec.EF.F and f.is_a?(Stream)
File.binwrite(attached_file, f.data)
nattach += 1
end
end
puts "Extracted #{nattach} attachments to '#{attachments_dir}'."
end
if @options[:fonts]
nfonts = 0
fonts_dir = File.join(OUTPUT_DIR, "fonts")
Dir::mkdir(fonts_dir) unless File.directory?(fonts_dir)
pdf.root_objects.find_all{|obj| obj.is_a?(Stream)}.each do |stream|
font = stream.xrefs.find{|obj| obj.is_a?(FontDescriptor)}
if font
font_file = File.join(fonts_dir, File.basename(font.FontName.value.to_s))
File.binwrite(font_file, stream.data)
nfonts += 1
end
end
puts "Extracted #{nfonts} fonts to '#{fonts_dir}'."
end
if @options[:metadata]
nmeta = 0
metadata_dir = File.join(OUTPUT_DIR, "metadata")
Dir::mkdir(metadata_dir) unless File.directory?(metadata_dir)
pdf.root_objects.find_all{|obj| obj.is_a?(MetadataStream)}.each do |stream|
metadata_file = File.join(metadata_dir, "metadata_#{stream.reference.refno}.xml")
File.binwrite(metadata_file, stream.data)
nmeta += 1
end
puts "Extracted #{nmeta} metadata streams to '#{metadata_dir}'."
end
if @options[:images]
nimages = 0
image_dir = File.join(OUTPUT_DIR, "images")
Dir::mkdir(image_dir) unless File.directory?(image_dir)
pdf.root_objects.find_all{|obj| obj.is_a?(Graphics::ImageXObject)}.each do |stream|
begin
ext, image_data = stream.to_image_file
image_file = File.join(image_dir, "image_#{stream.reference.refno}.#{ext}")
if ext != 'png' and stream.ColorSpace == Graphics::Color::Space::DEVICE_CMYK
STDERR.puts "Warning: file '#{image_file}' is intended to be viewed in CMYK color space."
end
File.binwrite(image_file, image_data)
nimages += 1
rescue
STDERR.puts "Unable to decode image (stream #{stream.reference.refno}). #{$!.message}"
end
end
puts "Extracted #{nimages} images to '#{image_dir}'."
end
rescue
abort "#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdfdecrypt 0000755 0000041 0000041 00000004275 12757133666 016062 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Decrypts a PDF document.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
class OptParser
BANNER = <] [-p ] [-o ]
Decrypts a PDF document. Supports RC4 40 to 128 bits, AES128, AES256.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-o", "--output FILE", "Output PDF file (stdout by default)") do |o|
options[:output] = o
end
opts.on("-p", "--password PASSWORD", "Password of the document") do |p|
options[:password] = p
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
output: STDOUT,
password: ''
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
target = (ARGV.empty?) ? STDIN : ARGV.shift
params =
{
verbosity: Parser::VERBOSE_QUIET,
password: @options[:password]
}
PDF.read(target, params).save(@options[:output], decrypt: true, noindent: true)
rescue
abort "#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdf2pdfa 0000755 0000041 0000041 00000004204 12757133666 015374 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Enforces a document to be rendered as PDF/A.
This will disable multimedia features and JavaScript execution in Adobe Reader.
= License
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
require 'optparse'
class OptParser
BANNER = <] [-o ]
Enforces a document to be rendered as PDF/A.
This will disable multimedia features and JavaScript execution in Adobe Reader.
Bug reports or feature requests at: http://github.com/gdelugre/origami
Options:
USAGE
def self.parser(options)
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-o", "--output FILE", "Output PDF file (stdout by default)") do |o|
options[:output] = o
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
end
def self.parse(args)
options =
{
output: STDOUT,
}
self.parser(options).parse!(args)
options
end
end
begin
@options = OptParser.parse(ARGV)
target = (ARGV.empty?) ? STDIN : ARGV.shift
params =
{
verbosity: Parser::VERBOSE_QUIET,
}
PDF.read(target, params).save(@options[:output], intent: 'PDF/A', noindent: true)
rescue
abort"#{$!.class}: #{$!.message}"
end
origami-2.0.0/bin/pdf2ruby 0000755 0000041 0000041 00000021614 12757133666 015447 0 ustar www-data www-data #!/usr/bin/env ruby
=begin
= Info
Convert a PDF document to an Origami script.
Experimental.
= License:
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see .
=end
require 'optparse'
require 'fileutils'
require 'colorize'
begin
require 'origami'
rescue LoadError
$: << File.join(__dir__, '../lib')
require 'origami'
end
include Origami
@var_hash = {}
@code_hash = {}
@obj_route = []
@current_idx = nil
class OptParser
def self.parse(args)
options = {}
options[:verbose] =
options[:xstreams] = false
opts = OptionParser.new do |opts|
opts.banner = <
Convert a PDF document to an Origami script (experimental).
Options:
BANNER
opts.on("-v", "--verbose", "Verbose mode") do
options[:verbose] = true
end
opts.on("-x", "--extract-streams", "Extract PDF streams to separate files") do
options[:xstreams] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opts.parse!(args)
options
end
end
@options = OptParser.parse(ARGV)
if ARGV.empty?
abort "Error: No filename was specified. #{$0} --help for details."
else
TARGET = ARGV.shift
end
Origami::OPTIONS[:enable_type_guessing] = Origami::OPTIONS[:enable_type_propagation] = true
TARGET_DIR = File.basename(TARGET, '.pdf')
TARGET_FILE = File.join(TARGET_DIR, "#{TARGET_DIR}.rb")
STREAM_DIR = "streams"
def objectToRuby(obj, inclevel = 0, internalname = nil, do_convert = false)
code = ""
code <<
case obj
when Origami::Null
"Null.new"
when Origami::Boolean, Origami::Number
obj.value.to_s
when Origami::String
obj.inspect
when Origami::Dictionary
customclass = nil
if obj.class != Origami::Dictionary
p = (obj.class == Origami::Encoding) ? 0 : 1
customclass = obj.class.to_s.split('::')[p..-1].join('::') # strip Origami prefix if there is no collision
end
dictionaryToRuby(obj, inclevel, internalname, customclass)
when Origami::Array
arrayToRuby(obj, inclevel, internalname)
when Origami::Stream
streamToRuby(obj, internalname) unless obj.is_a?(ObjectStream) or obj.is_a?(XRefStream)
when Origami::Name
nameToRuby(obj)
when Origami::Reference
referenceToRuby(obj, internalname)
else
raise RuntimeError, "Unknown object type: #{obj.class}"
end
case obj
when Origami::String, Origami::Dictionary, Origami::Array, Origami::Name
code << ".to_o" if do_convert
end
code
end
def referenceToRuby(ref, internalname)
varname = @var_hash[ref]
if varname.nil?
"nil"
elsif @obj_route[0..@current_idx].include?(varname)
@code_hash[varname] ||= {}
@code_hash[varname][:afterDecl] ||= []
@code_hash[varname][:afterDecl] << "#{internalname} = #{varname}"#.to_o.set_indirect(true)"
"nil"
else
@obj_route.push(varname) unless @obj_route.include?(varname)
varname
end
end
def nameToRuby(name)
code = ':'
valid = (name.value.to_s =~ /[+.:-]/).nil?
code << '"' unless valid
code << name.value.to_s
code << '"' unless valid
code
end
def arrayToRuby(arr, inclevel, internalname)
i = 0
code = "\n" + " " * inclevel + "["
arr.each do |obj|
subintname = "#{internalname}[#{i}]"
code << "#{objectToRuby(obj, inclevel + 1, subintname)}"
code << ", " unless i == arr.length - 1
i = i + 1
end
code << "]"
code
end
def dictionaryToRuby(dict, inclevel, internalname, customtype = nil)
i = 0
code = "\n" + " " * inclevel
if customtype
code << "#{customtype}.new(#{dictionaryToHashMap(dict, inclevel, internalname)}"
code << " " * inclevel + ")"
else
code << "{\n"
dict.each_pair do |key, val|
rubyname = nameToRuby(key)
subintname = "#{internalname}[#{rubyname}]"
if val.is_a?(Origami::Reference) and @var_hash[val] and @var_hash[val][0,3] == "obj"
oldname = @var_hash[val]
newname = (key.value.to_s.downcase.gsub(/[^[[:alnum:]]]/,'_') + "_" + @var_hash[val][4..-1]).gsub('.','_')
if not @obj_route.include?(oldname)
@var_hash[val] = newname
@code_hash[newname] = @code_hash[oldname]
@code_hash.delete(oldname)
end
end
code << " " * (inclevel + 1) +
"#{rubyname} => #{objectToRuby(val, inclevel + 2, subintname)}"
code << ", " unless i == dict.length - 1
i = i + 1
code << "\n"
end
code << " " * inclevel + "}"
end
code
end
def dictionaryToHashMap(dict, inclevel, internalname)
i = 0
code = "\n"
dict.each_pair do |key, val|
rubyname = nameToRuby(key)
subintname = "#{internalname}[#{rubyname}]"
if val.is_a?(Origami::Reference) and @var_hash[val] and @var_hash[val][0,3] == "obj"
oldname = @var_hash[val]
newname = (key.value.to_s.downcase + "_" + @var_hash[val][4..-1]).gsub('.','_')
if not @obj_route.include?(oldname)
@var_hash[val] = newname
@code_hash[newname] = @code_hash[oldname]
@code_hash.delete(oldname)
end
end
code << " " * (inclevel + 1) +
"#{rubyname} => #{objectToRuby(val, inclevel + 2, subintname)}"
code << ", " unless i == dict.length - 1
i = i + 1
code << "\n"
end
code
end
def streamToRuby(stm, internalname)
dict = stm.dictionary.dup.delete_if{|k,v| k == :Length}
code = "Stream.new("
if @options[:xstreams]
stmdir = File.join(TARGET_DIR, STREAM_DIR)
Dir::mkdir(stmdir) unless File.directory? stmdir
stmfile = File.join(stmdir, "stm_#{stm.reference.refno}.data")
File.binwrite(stmfile, stm.data)
code << "File.binread('#{stmfile}')"
else
code << stm.data.inspect << ".b"
end
code << ", #{dictionaryToHashMap(dict, 1, internalname)}" unless dict.empty?
code << ")"
code
end
puts "[*] ".red + "Loading document '#{TARGET}'"
verbosity = @options[:verbose] ? Parser::VERBOSE_TRACE : Parser::VERBOSE_QUIET
target = PDF.read(TARGET, verbosity: verbosity)
puts "[*] ".red + "Document successfully loaded into Origami"
Dir::mkdir(TARGET_DIR) unless File.directory? TARGET_DIR
fd = File.open(TARGET_FILE, 'w', 0700)
DOCREF = "pdf"
fd.puts <