From aeabdef63219b5369907c767f692e929013c3507 Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Wed, 6 Feb 2013 10:07:00 +0100 Subject: Add fonts (and font-lists) used in document to top of Text tool-bar font-family drop-down menu. If font is not on system, draws strikethrough on top of font name. (bzr r12104) --- src/ink-comboboxentry-action.cpp | 34 +++++-- src/libnrtype/font-lister.cpp | 2 +- src/libnrtype/font-lister.h | 5 + src/widgets/text-toolbar.cpp | 213 +++++++++++++++++++++++++++++++++++---- 4 files changed, 224 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/ink-comboboxentry-action.cpp b/src/ink-comboboxentry-action.cpp index a28ec4f53..78becbd53 100644 --- a/src/ink-comboboxentry-action.cpp +++ b/src/ink-comboboxentry-action.cpp @@ -37,7 +37,7 @@ static GtkWidget* create_tool_item( GtkAction* action ); static GtkWidget* create_menu_item( GtkAction* action ); // Internal -static gint get_active_row_from_text( Ink_ComboBoxEntry_Action* action, const gchar* target_text ); +static gint get_active_row_from_text( Ink_ComboBoxEntry_Action* action, const gchar* target_text, gboolean exclude = false ); static Glib::ustring check_comma_separated_text( Ink_ComboBoxEntry_Action* action ); // Callbacks @@ -611,8 +611,11 @@ void ink_comboboxentry_action_set_altx_name( Ink_ComboBoxEntry_Action* actio // Internal --------------------------------------------------- -// Return row of active text or -1 if not found. -gint get_active_row_from_text( Ink_ComboBoxEntry_Action* action, const gchar* target_text ) { +// Return row of active text or -1 if not found. If exclude is true, +// use 3d colunm if available to exclude row from checking (useful to +// skip rows added for font-families included in doc and not on +// system) +gint get_active_row_from_text( Ink_ComboBoxEntry_Action* action, const gchar* target_text, gboolean exclude ) { // Check if text in list gint row = 0; @@ -621,15 +624,24 @@ gint get_active_row_from_text( Ink_ComboBoxEntry_Action* action, const gchar* ta gboolean valid = gtk_tree_model_get_iter_first( action->model, &iter ); while ( valid ) { - // Get text from list entry - gchar* text = 0; - gtk_tree_model_get( action->model, &iter, 0, &text, -1 ); // Column 0 + // See if we should exclude a row + gboolean check = true; // If true, font-family is on system. + if( exclude && gtk_tree_model_get_n_columns( action->model ) > 2 ) { + gtk_tree_model_get( action->model, &iter, 2, &check, -1 ); + } + + if( check ) { + // Get text from list entry + gchar* text = 0; + gtk_tree_model_get( action->model, &iter, 0, &text, -1 ); // Column 0 - // Check for match - if( strcmp( target_text, text ) == 0 ){ - found = true; - break; + // Check for match + if( strcmp( target_text, text ) == 0 ){ + found = true; + break; + } } + ++row; valid = gtk_tree_model_iter_next( action->model, &iter ); } @@ -665,7 +677,7 @@ static Glib::ustring check_comma_separated_text( Ink_ComboBoxEntry_Action* actio // Remove any surrounding white space. g_strstrip( tokens[i] ); - if( get_active_row_from_text( action, tokens[i] ) == -1 ) { + if( get_active_row_from_text( action, tokens[i], true ) == -1 ) { missing += tokens[i]; missing += ", "; } diff --git a/src/libnrtype/font-lister.cpp b/src/libnrtype/font-lister.cpp index 710e0b84f..6df576866 100644 --- a/src/libnrtype/font-lister.cpp +++ b/src/libnrtype/font-lister.cpp @@ -52,7 +52,7 @@ namespace Inkscape } (*treeModelIter)[FontList.styles] = styles; - + (*treeModelIter)[FontList.onSystem] = true; font_list_store_iter_map.insert(std::make_pair(familyName, Gtk::TreePath(treeModelIter))); } } diff --git a/src/libnrtype/font-lister.h b/src/libnrtype/font-lister.h index c9ab7b21d..7a7db5615 100644 --- a/src/libnrtype/font-lister.h +++ b/src/libnrtype/font-lister.h @@ -54,10 +54,15 @@ namespace Inkscape */ Gtk::TreeModelColumn styles; + /** Column containing flag if font is on system + */ + Gtk::TreeModelColumn onSystem; + FontListClass () { add (font); add (styles); + add (onSystem); } }; diff --git a/src/widgets/text-toolbar.cpp b/src/widgets/text-toolbar.cpp index 3eccf1d2f..8b3612db4 100644 --- a/src/widgets/text-toolbar.cpp +++ b/src/widgets/text-toolbar.cpp @@ -18,7 +18,7 @@ * * Copyright (C) 2004 David Turner * Copyright (C) 2003 MenTaLguY - * Copyright (C) 1999-2011 authors + * Copyright (C) 1999-2013 authors * Copyright (C) 2001-2002 Ximian, Inc. * * Released under GNU GPL, read the file 'COPYING' for more information @@ -39,6 +39,7 @@ #include "../desktop-handles.h" #include "../desktop-style.h" #include "document-undo.h" +#include "../sp-root.h" #include "../verbs.h" #include "../inkscape.h" #include "../connection-pool.h" @@ -105,6 +106,10 @@ static void sp_print_font( SPStyle *query ) { << " FontSpec: " << (query->text->font_specification.value ? query->text->font_specification.value : "No value") << std::endl; + std::cout << " LineHeight: " << query->line_height.computed + << " WordSpacing: " << query->word_spacing.computed + << " LetterSpacing: " << query->letter_spacing.computed + << std::endl; } static void sp_print_fontweight( SPStyle *query ) { @@ -128,40 +133,88 @@ static void sp_print_fontstyle( SPStyle *query ) { } #endif +void sp_text_toolbox_get_font_list_in_doc (SPObject *r, std::list *l); +void sp_text_toolbox_update_font_list( GtkListStore* model ); + // Format family drop-down menu. static void cell_data_func(GtkCellLayout * /*cell_layout*/, GtkCellRenderer *cell, - GtkTreeModel *tree_model, + GtkTreeModel *model, GtkTreeIter *iter, gpointer /*data*/) { gchar *family; - gtk_tree_model_get(tree_model, iter, 0, &family, -1); - gchar *const family_escaped = g_markup_escape_text(family, -1); + gboolean onSystem = false; + gtk_tree_model_get(model, iter, 0, &family, 2, &onSystem, -1); + Glib::ustring family_escaped = g_markup_escape_text(family, -1); + g_free(family); + Glib::ustring markup; + + if( !onSystem ) { + markup = ""; + + /* See if font-family on system */ + std::vector tokens = Glib::Regex::split_simple("\\s*,\\s*", family_escaped ); + for( size_t i=0; i < tokens.size(); ++i ) { + + Glib::ustring token = tokens[i]; + + GtkTreeIter iter; + gboolean valid; + gchar *family = 0; + gboolean onSystem = true; + gboolean found = false; + for( valid = gtk_tree_model_get_iter_first( GTK_TREE_MODEL(model), &iter ); + valid; + valid = gtk_tree_model_iter_next( GTK_TREE_MODEL(model), &iter ) ) { + + gtk_tree_model_get(model, &iter, 0, &family, 2, &onSystem, -1); + if( onSystem && token.compare( family ) == 0 ) { + found = true; + break; + } + } + if( found ) { + markup += g_markup_escape_text(token.c_str(), -1); + markup += ", "; + } else { + markup += ""; + markup += g_markup_escape_text(token.c_str(), -1); + markup += ""; + markup += ", "; + } + } + // Remove extra comma and space from end. + if( markup.size() >= 2 ) { + markup.resize( markup.size()-2 ); + } + markup += ""; + // std::cout << markup << std::endl; + } else { + markup = family_escaped; + } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int show_sample = prefs->getInt("/tools/text/show_sample_in_list", 1); if (show_sample) { Glib::ustring sample = prefs->getString("/tools/text/font_sample"); - gchar *const sample_escaped = g_markup_escape_text(sample.data(), -1); - - std::stringstream markup; - markup << family_escaped << " " << sample_escaped << ""; - g_object_set (G_OBJECT (cell), "markup", markup.str().c_str(), NULL); + Glib::ustring sample_escaped = g_markup_escape_text(sample.data(), -1); - g_free(sample_escaped); - } else { - g_object_set (G_OBJECT (cell), "markup", family_escaped, NULL); + markup += " "; + markup += sample_escaped; + markup += ""; } + + g_object_set (G_OBJECT (cell), "markup", markup.c_str(), NULL); + // This doesn't work for two reasons... it set both selected and not selected backgrounds // to white.. which means that white foreground text is invisible. It also only effects // the text region, leaving the padding untouched. // g_object_set (G_OBJECT (cell), "cell-background", "white", "cell-background-set", true, NULL); - g_free(family); - g_free(family_escaped); } /* @@ -256,7 +309,6 @@ static void sp_text_fontstyle_populate(GObject *tbl, font_instance *font=NULL) } else if (current_style) { ink_comboboxentry_action_set_active_text( fontStyleAction, current_style ); } - } // Font family @@ -1184,6 +1236,14 @@ static void sp_text_toolbox_selection_changed(Inkscape::Selection */*selection*/ } g_object_set_data( tbl, "freeze", GINT_TO_POINTER(TRUE) ); + // Update font list, but only if widget already created. + Ink_ComboBoxEntry_Action* fontFamilyAction = + INK_COMBOBOXENTRY_ACTION( g_object_get_data( tbl, "TextFontFamilyAction" ) ); + if( fontFamilyAction->combobox != NULL ) { + sp_text_toolbox_update_font_list( GTK_LIST_STORE(ink_comboboxentry_action_get_model(fontFamilyAction)) ); + } + + // Only flowed text can be justified, only normal text can be kerned... // Find out if we have flowed text now so we can use it several places gboolean isFlow = false; @@ -1238,8 +1298,6 @@ static void sp_text_toolbox_selection_changed(Inkscape::Selection */*selection*/ // To ensure the value of the combobox is properly set on start-up, only mark // the prefs set if the combobox has already been constructed. - Ink_ComboBoxEntry_Action* fontFamilyAction = - INK_COMBOBOXENTRY_ACTION( g_object_get_data( tbl, "TextFontFamilyAction" ) ); if( fontFamilyAction->combobox != NULL ) { g_object_set_data(tbl, "text_style_from_prefs", GINT_TO_POINTER(TRUE)); } @@ -1482,6 +1540,124 @@ sp_text_toolbox_subselection_changed (gpointer /*tc*/, GObject *tbl) sp_text_toolbox_selection_changed (NULL, tbl); } + +/* Recursively extract all "font-family" attributes from a document. */ +void +sp_text_toolbox_get_font_list_in_doc_recursive (SPObject *r, std::list *l) +{ + if (!r) { + return; + } + + const gchar *style = r->getRepr()->attribute("style"); + if( style != NULL ) { + //std::cout << style << std::endl; + std::vector tokens = Glib::Regex::split_simple(";", style ); + for( size_t i=0; i < tokens.size(); ++i ) { + Glib::ustring token = tokens[i]; + size_t found = token.find("font-family:"); + if( found != Glib::ustring::npos ) { + // Remove "font-family:" + token.erase(found,12); + // Remove any leading single or double quote + if( token[0] == '\'' || token[0] == '"' ) { + token.erase(0,1); + } + // Remove any trailing single or double quote + if( token[token.length()-1] == '\'' || token[token.length()-1] == '"' ) { + token.erase(token.length()-1); + } + l->push_back( token ); + } + } + } + + for (SPObject *child = r->firstChild(); child; child = child->getNext()) { + sp_text_toolbox_get_font_list_in_doc_recursive( child, l ); + } +} + +/* Extract all unique "font-family" attributes (including font-family fallbacks) + * from a document in a reverse sorted list. + */ +void +sp_text_toolbox_get_font_list_in_doc (SPObject *r, std::list *l) { + + sp_text_toolbox_get_font_list_in_doc_recursive (r, l); + + l->sort(); + l->unique(); + l->reverse(); + + // for(std::list::iterator i = l->begin(); i != l->end(); ++i) { + // std::cout << " font_family in doc: " << *i << std::endl; + // } +} + +/* Update font-family list with "font-family" attributes used in a document. */ +void +sp_text_toolbox_update_font_list( GtkListStore* model ) { + + /* Create default styles for use when font-family is unknown on system. */ + static GList *default_styles = NULL; + if( default_styles == NULL ) { + default_styles = g_list_append( default_styles, g_strdup("Normal") ); + default_styles = g_list_append( default_styles, g_strdup("Italic") ); + default_styles = g_list_append( default_styles, g_strdup("Bold") ); + default_styles = g_list_append( default_styles, g_strdup("Bold Italic") ); + } + + /* Get "font-family" attributes used in document */ + std::list fontfamilies; + sp_text_toolbox_get_font_list_in_doc( (sp_desktop_document(SP_ACTIVE_DESKTOP))->getRoot(), &fontfamilies ); + + /* Delete all old doc font-family entries */ + GtkTreeIter iter; + gboolean valid; + for( valid = gtk_tree_model_get_iter_first( GTK_TREE_MODEL(model), &iter ); valid; ) { + gchar *family = 0; + gboolean onSystem = true; + gtk_tree_model_get( GTK_TREE_MODEL(model), &iter, 0, &family, 2, &onSystem, -1 ); + //std::cout << "List: " << family << ": " << (onSystem ? "Yes" : "No") << std::endl; + if( !onSystem ) { + valid = gtk_list_store_remove( model, &iter ); + } else { + valid = gtk_tree_model_iter_next( GTK_TREE_MODEL(model), &iter ); + } + } + + /* Insert doc font-family entries, list is already reverse sorted with duplicates removed. */ + std::list::iterator i; + for(i=fontfamilies.begin(); i != fontfamilies.end(); ++i) { + + GList *styles = default_styles; + gtk_list_store_insert( model, &iter, 0 ); // iter points to new row + + /* See if font-family (or first in fallback list) is on system. If so, get styles. */ + std::vector tokens = Glib::Regex::split_simple(",", *i ); + if( !tokens[0].empty() ) { + + GtkTreeIter iter2; + gboolean valid2; + for( valid2 = gtk_tree_model_get_iter_first( GTK_TREE_MODEL(model), &iter2 ); + valid2; + valid2 = gtk_tree_model_iter_next( GTK_TREE_MODEL(model), &iter2 ) ) { + + gchar* family = 0; + gboolean onSystem = true; + gtk_tree_model_get( GTK_TREE_MODEL(model), &iter2, 0, &family, 2, &onSystem, -1 ); + if( onSystem && tokens[0].compare( family ) == 0 ) { + gtk_tree_model_get( GTK_TREE_MODEL(model), &iter2, 1, &styles, -1 ); + break; + } + } + + } + + gtk_list_store_set( model, &iter, 0, (*i).c_str(), 1, styles, 2, false, -1 ); + } +} + // Define all the "widgets" in the toolbar. void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObject* holder) { @@ -1498,6 +1674,7 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje // Font list Glib::RefPtr store = Inkscape::FontLister::get_instance()->get_font_list(); GtkListStore* model = store->gobj(); + sp_text_toolbox_update_font_list( model ); Ink_ComboBoxEntry_Action* act = ink_comboboxentry_action_new( "TextFontFamilyAction", _("Font Family"), -- cgit v1.2.3 From a3d3d3df4c67f666083e7c4c2ea56bb94705bbbf Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Thu, 7 Feb 2013 12:47:37 +0100 Subject: Add separator between fonts in document and fonts on sytem in font-family drop-down menu. Separator style depends on GTK theme (may be invisible). (bzr r12105) --- src/ink-comboboxentry-action.cpp | 28 +++++++++++++++++++++++++++- src/ink-comboboxentry-action.h | 2 ++ src/widgets/text-toolbar.cpp | 39 ++++++++++++++++++++++++++++++--------- 3 files changed, 59 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/ink-comboboxentry-action.cpp b/src/ink-comboboxentry-action.cpp index 78becbd53..5adc3e73a 100644 --- a/src/ink-comboboxentry-action.cpp +++ b/src/ink-comboboxentry-action.cpp @@ -53,6 +53,7 @@ enum { PROP_ENTRY_WIDTH, PROP_EXTRA_WIDTH, PROP_CELL_DATA_FUNC, + PROP_SEPARATOR_FUNC, PROP_POPUP, PROP_FOCUS_WIDGET }; @@ -109,6 +110,10 @@ static void ink_comboboxentry_action_set_property (GObject *object, guint proper action->cell_data_func = g_value_get_pointer( value ); break; + case PROP_SEPARATOR_FUNC: + action->separator_func = g_value_get_pointer( value ); + break; + case PROP_POPUP: action->popup = g_value_get_boolean( value ); break; @@ -154,6 +159,10 @@ static void ink_comboboxentry_action_get_property (GObject *object, guint proper g_value_set_pointer (value, action->cell_data_func); break; + case PROP_SEPARATOR_FUNC: + g_value_set_pointer (value, action->separator_func); + break; + case PROP_POPUP: g_value_set_boolean (value, action->popup); break; @@ -247,6 +256,14 @@ ink_comboboxentry_action_class_init (Ink_ComboBoxEntry_ActionClass *klass) "Cell Deta Function", (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property ( + gobject_class, + PROP_SEPARATOR_FUNC, + g_param_spec_pointer ("separator_func", + "Separator Func", + "Separator Function", + (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property ( gobject_class, PROP_POPUP, @@ -303,6 +320,7 @@ Ink_ComboBoxEntry_Action *ink_comboboxentry_action_new (const gchar *name, gint entry_width, gint extra_width, void *cell_data_func, + void *separator_func, GtkWidget *focusWidget) { g_return_val_if_fail (name != NULL, NULL); @@ -316,6 +334,7 @@ Ink_ComboBoxEntry_Action *ink_comboboxentry_action_new (const gchar *name, "entry_width", entry_width, "extra_width", extra_width, "cell_data_func", cell_data_func, + "separator_func", separator_func, "focus-widget", focusWidget, NULL); } @@ -365,6 +384,13 @@ GtkWidget* create_tool_item( GtkAction* action ) NULL, NULL ); } + // Optionally add separator function... + if( ink_comboboxentry_action->separator_func != NULL ) { + gtk_combo_box_set_row_separator_func( ink_comboboxentry_action->combobox, + GtkTreeViewRowSeparatorFunc (ink_comboboxentry_action->separator_func), + NULL, NULL ); + } + // Optionally widen the combobox width... which widens the drop-down list in list mode. if( ink_comboboxentry_action->extra_width > 0 ) { GtkRequisition req; @@ -469,7 +495,7 @@ gboolean ink_comboboxentry_action_set_active_text( Ink_ComboBoxEntry_Action* ink // Explicitly set text in GtkEntry box (won't be set if text not in list). gtk_entry_set_text( ink_comboboxentry_action->entry, text ); - // Show or hide warning + // Show or hide warning -- this might be better moved to text-toolbox.cpp bool clear = true; if( ink_comboboxentry_action->active == -1 && ink_comboboxentry_action->warning != NULL ) { diff --git a/src/ink-comboboxentry-action.h b/src/ink-comboboxentry-action.h index 7d4093f4e..f0dc0ee7e 100644 --- a/src/ink-comboboxentry-action.h +++ b/src/ink-comboboxentry-action.h @@ -51,6 +51,7 @@ struct _Ink_ComboBoxEntry_Action { GtkWidget *indicator; gpointer cell_data_func; // drop-down menu format + gpointer separator_func; gint active; // Index of active menu item (-1 if not in list). gchar *text; // Text of active menu item or entry box. @@ -76,6 +77,7 @@ Ink_ComboBoxEntry_Action *ink_comboboxentry_action_new ( const gchar *name, gint entry_width = -1, gint extra_width = -1, gpointer cell_data_func = NULL, + gpointer separator_func = NULL, GtkWidget* focusWidget = NULL); GtkTreeModel *ink_comboboxentry_action_get_model( Ink_ComboBoxEntry_Action* action ); diff --git a/src/widgets/text-toolbar.cpp b/src/widgets/text-toolbar.cpp index 8b3612db4..42d309994 100644 --- a/src/widgets/text-toolbar.cpp +++ b/src/widgets/text-toolbar.cpp @@ -217,6 +217,16 @@ static void cell_data_func(GtkCellLayout * /*cell_layout*/, } +// Separator function (if true, a separator will be drawn) +static gboolean separator_func(GtkTreeModel *model, + GtkTreeIter *iter, + gpointer /*data*/) +{ + gchar* text = 0; + gtk_tree_model_get(model, iter, 0, &text, -1 ); // Column 0 + return (text && strcmp(text,"separatoR") == 0); +} + /* * Fill the font style combobox with the available font styles for the selected font family * Set the selected style to that in font @@ -1626,6 +1636,13 @@ sp_text_toolbox_update_font_list( GtkListStore* model ) { } } + /* Insert separator */ + if( !fontfamilies.empty() ) { + gtk_list_store_insert( model, &iter, 0 ); // iter points to new row + gtk_list_store_set( model, &iter, 0, "separatoR", -1 ); + } + + /* Insert doc font-family entries, list is already reverse sorted with duplicates removed. */ std::list::iterator i; for(i=fontfamilies.begin(); i != fontfamilies.end(); ++i) { @@ -1676,15 +1693,17 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje GtkListStore* model = store->gobj(); sp_text_toolbox_update_font_list( model ); - Ink_ComboBoxEntry_Action* act = ink_comboboxentry_action_new( "TextFontFamilyAction", - _("Font Family"), - _("Select Font Family (Alt-X to access)"), - NULL, - GTK_TREE_MODEL(model), - -1, // Entry width - 50, // Extra list width - (gpointer)cell_data_func,// Cell layout - GTK_WIDGET(desktop->canvas)); // Focus widget + Ink_ComboBoxEntry_Action* act = + ink_comboboxentry_action_new( "TextFontFamilyAction", + _("Font Family"), + _("Select Font Family (Alt-X to access)"), + NULL, + GTK_TREE_MODEL(model), + -1, // Entry width + 50, // Extra list width + (gpointer)cell_data_func, // Cell layout + (gpointer)separator_func, + GTK_WIDGET(desktop->canvas)); // Focus widget ink_comboboxentry_action_popup_enable( act ); // Enable entry completion gchar *const warning = _("Font not found on system"); ink_comboboxentry_action_set_warning( act, warning ); // Show icon with tooltip if missing font @@ -1721,6 +1740,7 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje 4, // Width in characters 0, // Extra list width NULL, // Cell layout + NULL, // Separator GTK_WIDGET(desktop->canvas)); // Focus widget g_signal_connect( G_OBJECT(act), "changed", G_CALLBACK(sp_text_fontsize_value_changed), holder ); @@ -1740,6 +1760,7 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje 12, // Width in characters 0, // Extra list width NULL, // Cell layout + NULL, // Separator GTK_WIDGET(desktop->canvas)); // Focus widget g_signal_connect( G_OBJECT(act), "changed", G_CALLBACK(sp_text_fontstyle_value_changed), holder ); -- cgit v1.2.3 From 55e21b98d8eda49df5d2c2d8ea940dd2d0802bc5 Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Thu, 7 Feb 2013 15:14:00 +0100 Subject: Widen the separator in font-family drop-down so it is visible in more themes. (bzr r12106) --- src/widgets/text-toolbar.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/widgets/text-toolbar.cpp b/src/widgets/text-toolbar.cpp index 42d309994..8d37891ac 100644 --- a/src/widgets/text-toolbar.cpp +++ b/src/widgets/text-toolbar.cpp @@ -1718,7 +1718,13 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje "{\n" " GtkComboBox::appears-as-list = 1\n" "}\n" - "widget \"*.TextFontFamilyAction_combobox\" style \"dropdown-as-list-style\""); + "widget \"*.TextFontFamilyAction_combobox\" style \"dropdown-as-list-style\"" + "style \"fontfamily-separator-style\"\n" + "{\n" + " GtkWidget::wide-separators = 1\n" + " GtkWidget::separator-height = 6\n" + "}\n" + "class \"GtkTreeView\" style \"fontfamily-separator-style\""); } /* Font size */ -- cgit v1.2.3 From 1db4e9f22c0412532f0c3fb9798cd1983a74c9de Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Fri, 8 Feb 2013 09:08:06 +0100 Subject: Better rc matching for text-toolbar font-family drop-down separator. From John Smith. (bzr r12107) --- src/widgets/text-toolbar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/widgets/text-toolbar.cpp b/src/widgets/text-toolbar.cpp index 8d37891ac..f19ee7cee 100644 --- a/src/widgets/text-toolbar.cpp +++ b/src/widgets/text-toolbar.cpp @@ -1724,7 +1724,7 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje " GtkWidget::wide-separators = 1\n" " GtkWidget::separator-height = 6\n" "}\n" - "class \"GtkTreeView\" style \"fontfamily-separator-style\""); + "widget \"*gtk-combobox-popup-window.GtkScrolledWindow.GtkTreeView\" style \"fontfamily-separator-style\""); } /* Font size */ -- cgit v1.2.3 From ecdaa96827420efb95a897e56660c33e30553f6a Mon Sep 17 00:00:00 2001 From: Kris De Gussem Date: Fri, 8 Feb 2013 20:48:24 +0100 Subject: cppcheck (should fix a.o. copy paste error in SVGAnimatedPreserveAspectRatio) (bzr r12108) --- src/dom/svgimpl.h | 9 +- src/dom/svgtypes.h | 239 +++++++++++++++++++++++++++-------------------------- 2 files changed, 128 insertions(+), 120 deletions(-) (limited to 'src') diff --git a/src/dom/svgimpl.h b/src/dom/svgimpl.h index 83d56fa22..2ee5c8bc7 100644 --- a/src/dom/svgimpl.h +++ b/src/dom/svgimpl.h @@ -980,7 +980,14 @@ public: /** * */ - SVGSVGElementImpl() : SVGElementImpl() + SVGSVGElementImpl() : SVGElementImpl(), + pixelUnitToMillimeterX(0), + pixelUnitToMillimeterY(0), + screenPixelToMillimeterX(0), + screenPixelToMillimeterY(0), + useCurrentView(false), + currentScale(0), + currentTime(0) {} diff --git a/src/dom/svgtypes.h b/src/dom/svgtypes.h index 41b4de307..bb828571f 100644 --- a/src/dom/svgtypes.h +++ b/src/dom/svgtypes.h @@ -645,20 +645,20 @@ public: /** * */ - SVGTransform() + SVGTransform() : + type (SVG_TRANSFORM_UNKNOWN), + angle (0.0) { - type = SVG_TRANSFORM_UNKNOWN; - angle = 0.0; } /** * */ - SVGTransform(const SVGTransform &other) + SVGTransform(const SVGTransform &other) : + type (other.type), + angle (other.angle), + matrix (other.matrix) { - type = other.type; - angle = other.angle; - matrix = other.matrix; } /** @@ -834,9 +834,9 @@ public: /** * */ - SVGTransformList(const SVGTransformList &other) + SVGTransformList(const SVGTransformList &other) : + items (other.items) { - items = other.items; } /** @@ -893,10 +893,10 @@ public: /** * */ - SVGAnimatedTransformList(const SVGAnimatedTransformList &other) + SVGAnimatedTransformList(const SVGAnimatedTransformList &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -1181,9 +1181,9 @@ public: /** * */ - SVGStringList(const SVGStringList &other) + SVGStringList(const SVGStringList &other) : + items (other.items) { - items = other.items; } /** @@ -1657,9 +1657,9 @@ public: /** * */ - SVGNumberList(const SVGNumberList &other) + SVGNumberList(const SVGNumberList &other) : + items (other.items) { - items = other.items; } /** @@ -1719,10 +1719,10 @@ public: /** * */ - SVGAnimatedNumberList(const SVGAnimatedNumberList &other) + SVGAnimatedNumberList(const SVGAnimatedNumberList &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -1934,10 +1934,10 @@ public: /** * */ - SVGAnimatedLength(const SVGAnimatedLength &other) + SVGAnimatedLength(const SVGAnimatedLength &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -2085,9 +2085,9 @@ public: /** * */ - SVGLengthList(const SVGLengthList &other) + SVGLengthList(const SVGLengthList &other) : + items (other.items) { - items = other.items; } /** @@ -2147,10 +2147,10 @@ public: /** * */ - SVGAnimatedLengthList(const SVGAnimatedLengthList &other) + SVGAnimatedLengthList(const SVGAnimatedLengthList &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -2357,16 +2357,17 @@ public: /** * */ - SVGAnimatedAngle(const SVGAngle &angle) - { baseVal = angle; } + SVGAnimatedAngle(const SVGAngle &angle) : + baseVal (angle) + {} /** * */ - SVGAnimatedAngle(const SVGAnimatedAngle &other) + SVGAnimatedAngle(const SVGAnimatedAngle &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -2434,10 +2435,10 @@ public: /** * */ - SVGICCColor(const SVGICCColor &other) + SVGICCColor(const SVGICCColor &other) : + colorProfile (other.colorProfile), + colors (other.colors) { - colorProfile = other.colorProfile; - colors = other.colors; } /** @@ -2448,7 +2449,6 @@ public: protected: DOMString colorProfile; - SVGNumberList colors; }; @@ -2732,10 +2732,10 @@ public: /** * */ - SVGAnimatedRect(const SVGAnimatedRect &other) + SVGAnimatedRect(const SVGAnimatedRect &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - animVal = other.animVal; } /** @@ -2956,9 +2956,9 @@ public: /** * */ - SVGPointList(const SVGPointList &other) + SVGPointList(const SVGPointList &other) : + items (other.items) { - items = other.items; } @@ -3071,10 +3071,10 @@ public: /** * */ - SVGStylable(const SVGStylable &other) + SVGStylable(const SVGStylable &other) : + className (other.className), + style (other.style) { - className = other.className; - style = other.style; } /** @@ -3168,7 +3168,10 @@ public: /** * */ - SVGLocatable(const SVGLocatable &/*other*/) + SVGLocatable(const SVGLocatable &/*other*/) : + bbox(), + ctm(), + screenCtm() { } @@ -3224,9 +3227,9 @@ public: /** * */ - SVGTransformable(const SVGTransformable &other) : SVGLocatable(other) + SVGTransformable(const SVGTransformable &other) : SVGLocatable(other), + transforms (other.transforms) { - transforms = other.transforms; } /** @@ -3303,11 +3306,11 @@ public: /** * */ - SVGTests(const SVGTests &other) + SVGTests(const SVGTests &other) : + requiredFeatures (other.requiredFeatures), + requiredExtensions (other.requiredExtensions), + systemLanguage (other.systemLanguage) { - requiredFeatures = other.requiredFeatures; - requiredExtensions = other.requiredExtensions; - systemLanguage = other.systemLanguage; } /** @@ -3445,9 +3448,9 @@ public: /** * */ - SVGExternalResourcesRequired(const SVGExternalResourcesRequired &other) + SVGExternalResourcesRequired(const SVGExternalResourcesRequired &other) : + required (other.required) { - required = other.required; } /** @@ -3611,10 +3614,10 @@ public: /** * */ - SVGAnimatedPreserveAspectRatio(const SVGAnimatedPreserveAspectRatio &other) + SVGAnimatedPreserveAspectRatio(const SVGAnimatedPreserveAspectRatio &other) : + baseVal (other.baseVal), + animVal (other.animVal) { - baseVal = other.baseVal; - baseVal = other.animVal; } /** @@ -3671,10 +3674,10 @@ public: * */ - SVGFitToViewBox(const SVGFitToViewBox &other) + SVGFitToViewBox(const SVGFitToViewBox &other) : + viewBox (other.viewBox), + preserveAspectRatio (other.preserveAspectRatio) { - viewBox = other.viewBox; - preserveAspectRatio = other.preserveAspectRatio; } /** @@ -3685,7 +3688,6 @@ public: protected: SVGAnimatedRect viewBox; - SVGAnimatedPreserveAspectRatio preserveAspectRatio; }; @@ -3828,18 +3830,19 @@ public: /** * */ - SVGViewSpec() + SVGViewSpec() : + viewTarget (NULL), + transform () { - viewTarget = NULL; } /** * */ - SVGViewSpec(const SVGViewSpec &other) : SVGZoomAndPan(other), SVGFitToViewBox(other) + SVGViewSpec(const SVGViewSpec &other) : SVGZoomAndPan(other), SVGFitToViewBox(other), + viewTarget (other.viewTarget), + transform (other.transform) { - viewTarget = other.viewTarget; - transform = other.transform; } /** @@ -3884,14 +3887,16 @@ public: /** * */ - SVGURIReference() {} + SVGURIReference() : + href () + {} /** * */ - SVGURIReference(const SVGURIReference &other) + SVGURIReference(const SVGURIReference &other) : + href (other.href) { - href = other.href; } /** @@ -6135,9 +6140,9 @@ public: /** * */ - SVGPathSegList(const SVGPathSegList &other) + SVGPathSegList(const SVGPathSegList &other) : + items (other.items) { - items = other.items; } @@ -6272,10 +6277,10 @@ public: /** * */ - SVGAnimatedPoints(const SVGAnimatedPoints &other) + SVGAnimatedPoints(const SVGAnimatedPoints &other) : + points (other.points), + animatedPoints (other.animatedPoints) { - points = other.points; - animatedPoints = other.animatedPoints; } /** @@ -6366,19 +6371,19 @@ public: /** * */ - SVGPaint() + SVGPaint() : + paintType (SVG_PAINTTYPE_UNKNOWN), + uri ("") { - uri = ""; - paintType = SVG_PAINTTYPE_UNKNOWN; } /** * */ - SVGPaint(const SVGPaint &other) : css::CSSValue(other), SVGColor(other) + SVGPaint(const SVGPaint &other) : css::CSSValue(other), SVGColor(other), + paintType (SVG_PAINTTYPE_UNKNOWN), + uri ("") { - uri = ""; - paintType = SVG_PAINTTYPE_UNKNOWN; } /** @@ -6452,17 +6457,19 @@ public: /** * */ - SVGColorProfileRule() {} + SVGColorProfileRule() : + renderingIntent(0) + {} /** * */ SVGColorProfileRule(const SVGColorProfileRule &other) - : SVGCSSRule(other), SVGRenderingIntent(other) + : SVGCSSRule(other), SVGRenderingIntent(other), + renderingIntent (other.renderingIntent), + src (other.src), + name (other.name) { - renderingIntent = other.renderingIntent; - src = other.src; - name = other.name; } /** @@ -6540,13 +6547,13 @@ public: * */ SVGFilterPrimitiveStandardAttributes(const SVGFilterPrimitiveStandardAttributes &other) - : SVGStylable(other) + : SVGStylable(other), + x (other.x), + y (other.y), + width (other.width), + height (other.height), + result (other.result) { - x = other.x; - y = other.y; - width = other.width; - height = other.height; - result = other.result; } /** @@ -6567,13 +6574,6 @@ protected: - - - - - - - /*######################################################################### ## SVGEvent #########################################################################*/ @@ -6660,20 +6660,26 @@ public: /** * */ - SVGZoomEvent() + SVGZoomEvent(): + zoomRectScreen(), + previousScale(0), + previousTranslate(), + newScale(0), + newTranslate() {} /** * */ - SVGZoomEvent(const SVGZoomEvent &other) : events::Event(other), - events::UIEvent(other) + SVGZoomEvent(const SVGZoomEvent &other) : + events::Event(other), + events::UIEvent(other), + zoomRectScreen(other.zoomRectScreen), + previousScale(other.previousScale), + previousTranslate(other.previousTranslate), + newScale(other.newScale), + newTranslate(other.newTranslate) { - zoomRectScreen = other.zoomRectScreen; - previousScale = other.previousScale; - previousTranslate = other.previousTranslate; - newScale = other.newScale; - newTranslate = other.newTranslate; } /** @@ -6776,13 +6782,18 @@ public: /** * */ - SVGElementInstance() {} + SVGElementInstance() : + correspondingElement(NULL), + correspondingUseElement(NULL) + {} /** * */ SVGElementInstance(const SVGElementInstance &other) - : events::EventTarget(other) + : events::EventTarget(other), + correspondingElement(NULL), + correspondingUseElement(NULL) { } @@ -6858,9 +6869,9 @@ public: /** * */ - SVGElementInstanceList(const SVGElementInstanceList &other) + SVGElementInstanceList(const SVGElementInstanceList &other) : + items (other.items) { - items = other.items; } /** @@ -6877,16 +6888,6 @@ protected: - - - - - - - - - - } //namespace svg } //namespace dom } //namespace w3c -- cgit v1.2.3 From c7c7405b0417093650d312ce00a3e9009ca49ee6 Mon Sep 17 00:00:00 2001 From: Kris De Gussem Date: Fri, 8 Feb 2013 20:59:10 +0100 Subject: removed some unused files (bzr r12109) --- src/dom/CMakeLists.txt | 12 - src/dom/Makefile_insert | 11 +- src/dom/odf/odfdocument.cpp | 167 --- src/dom/odf/odfdocument.h | 150 --- src/dom/util/digest.cpp | 1456 --------------------- src/dom/util/digest.h | 654 ---------- src/dom/util/thread.cpp | 126 -- src/dom/util/thread.h | 156 --- src/dom/util/ziptool.cpp | 3025 ------------------------------------------- src/dom/util/ziptool.h | 567 -------- 10 files changed, 1 insertion(+), 6323 deletions(-) delete mode 100644 src/dom/odf/odfdocument.cpp delete mode 100644 src/dom/odf/odfdocument.h delete mode 100644 src/dom/util/digest.cpp delete mode 100644 src/dom/util/digest.h delete mode 100644 src/dom/util/thread.cpp delete mode 100644 src/dom/util/thread.h delete mode 100644 src/dom/util/ziptool.cpp delete mode 100644 src/dom/util/ziptool.h (limited to 'src') diff --git a/src/dom/CMakeLists.txt b/src/dom/CMakeLists.txt index df2411b13..bc2f58c29 100644 --- a/src/dom/CMakeLists.txt +++ b/src/dom/CMakeLists.txt @@ -26,12 +26,6 @@ set(dom_SRC io/stringstream.cpp io/uristream.cpp - odf/odfdocument.cpp - - util/digest.cpp - util/thread.cpp - util/ziptool.cpp - # ------- # Headers @@ -64,18 +58,12 @@ set(dom_SRC xpathparser.h xpathtoken.h - odf/odfdocument.h - io/base64stream.h io/bufferstream.h io/domstream.h io/gzipstream.h io/stringstream.h io/uristream.h - - util/digest.h - util/thread.h - util/ziptool.h ) add_inkscape_lib(dom_LIB "${dom_SRC}") diff --git a/src/dom/Makefile_insert b/src/dom/Makefile_insert index ace53b4a2..66333ba47 100644 --- a/src/dom/Makefile_insert +++ b/src/dom/Makefile_insert @@ -63,13 +63,4 @@ dom_libdom_a_SOURCES = \ dom/io/stringstream.cpp \ dom/io/stringstream.h \ dom/io/uristream.cpp \ - dom/io/uristream.h \ - dom/odf/odfdocument.cpp \ - dom/odf/odfdocument.h \ - dom/util/digest.h \ - dom/util/digest.cpp \ - dom/util/thread.h \ - dom/util/thread.cpp \ - dom/util/ziptool.h \ - dom/util/ziptool.cpp - + dom/io/uristream.h diff --git a/src/dom/odf/odfdocument.cpp b/src/dom/odf/odfdocument.cpp deleted file mode 100644 index cf460c964..000000000 --- a/src/dom/odf/odfdocument.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* - * - * This class contains an ODF Document. - * Initially, we are just concerned with .odg content.xml + resources - * - * --------------------------------------------------------------------- - * - * Copyright (C) 2006-2008 Bob Jamison - * - * 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 2 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, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * For more information, please write to rwjj@earthlink.net - * - * RWJ : 080207: Changed to GPL2 by me - * - */ - -#include "odfdocument.h" - - -namespace odf -{ - - -//######################################################################## -//# I M A G E D A T A -//######################################################################## - - -/** - * - */ -ImageData::ImageData(const std::string &fname, - const std::vector &buf) - : fileName (fname), - data (buf) - -{ -} - -/** - * - */ -ImageData::ImageData(const ImageData &other) - : fileName (other.fileName), - data (other.data) - -{ -} - -/** - * - */ -ImageData::~ImageData() -{ -} - -/** - * - */ -std::string ImageData::getFileName() -{ - return fileName; -} - -/** - * - */ -void ImageData::setFileName(const std::string &val) -{ - fileName = val; -} - -/** - * - */ -std::vector &ImageData::getData() -{ - return data; -} - -/** - * - */ -void ImageData::setData(const std::vector &buf) -{ - data = buf; -} - - - - - -//######################################################################## -//# O D F D O C U M E N T -//######################################################################## - - - -/** - * - */ -OdfDocument::OdfDocument() : - content(0), - images() -{ -} - - -/** - * - */ -OdfDocument::OdfDocument(const OdfDocument &other) : - content (other.content), - images (other.images) -{ -} - - -/** - * - */ -OdfDocument::~OdfDocument() -{ -} - -/** - * - */ -bool OdfDocument::readFile(const std::string &/*fileName*/) -{ - return true; -} - -/** - * - */ -bool OdfDocument::writeFile(const std::string &/*fileName*/) -{ - return true; -} - - - - - -} //namespace odf - - - - -//######################################################################## -//# E N D O F F I L E -//######################################################################## - diff --git a/src/dom/odf/odfdocument.h b/src/dom/odf/odfdocument.h deleted file mode 100644 index 168df11c7..000000000 --- a/src/dom/odf/odfdocument.h +++ /dev/null @@ -1,150 +0,0 @@ -#ifndef SEEN_ODF_DOCUMENT_H -#define SEEN_ODF_DOCUMENT_H -/* - * Copyright (C) 2006 Bob Jamison - * - * 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 2 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, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * For more information, please write to rwjj@earthlink.net - * - * RWJ : 080207: Changed to GPL2 by me - */ - -#include -#include - -#include "dom/dom.h" - -namespace odf -{ - - -//######################################################################## -//# I M A G E D A T A -//######################################################################## - -/** - * - */ -class ImageData -{ -public: - - /** - * - */ - ImageData(const std::string &fileName, - const std::vector &buf); - - /** - * - */ - ImageData(const ImageData &other); - - /** - * - */ - virtual ~ImageData(); - - /** - * - */ - virtual std::string getFileName(); - - /** - * - */ - virtual void setFileName(const std::string &val); - - /** - * - */ - virtual std::vector &getData(); - - /** - * - */ - virtual void setData(const std::vector &buf); - -private: - - std::string fileName; - - std::vector data; - -}; - - - - - -//######################################################################## -//# O D F D O C U M E N T -//######################################################################## - - -/** - * - * This class contains an ODF Document. - * Initially, we are just concerned with .odg content.xml + resources - */ -class OdfDocument -{ -public: - - /** - * - */ - OdfDocument(); - - /** - * Copy constructor - */ - OdfDocument(const OdfDocument &other); - - /** - * - */ - virtual ~OdfDocument(); - - /** - * - */ - virtual bool readFile(const std::string &fileName); - - /** - * - */ - virtual bool writeFile(const std::string &fileName); - - -private: - - org::w3c::dom::Document *content; - - std::vector images; - -}; - -} //namespace odf - - - -#endif // SEEN_ODF_DOCUMENT_H - -//######################################################################## -//# E N D O F F I L E -//######################################################################## - diff --git a/src/dom/util/digest.cpp b/src/dom/util/digest.cpp deleted file mode 100644 index 2baed4860..000000000 --- a/src/dom/util/digest.cpp +++ /dev/null @@ -1,1456 +0,0 @@ -/* - * Secure Hashing Tool - * * - * Authors: - * Bob Jamison - * - * Copyright (C) 2006-2008 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "digest.h" - - -//######################################################################## -//## U T I L I T Y -//######################################################################## - -/** - * Use this to print out a 64-bit int when otherwise difficult - */ -/* -static void pl(uint64_t val) -{ - for (int shift=56 ; shift>=0 ; shift-=8) - { - int ch = (val >> shift) & 0xff; - printf("%02x", ch); - } -} -*/ - - - -/** - * 3These truncate their arguments to - * unsigned 32-bit or unsigned 64-bit. - */ -#define TR32(x) ((x) & 0xffffffffL) -#define TR64(x) ((x) & 0xffffffffffffffffLL) - - -static const char *hexDigits = "0123456789abcdef"; - -static std::string toHex(const std::vector &bytes) -{ - std::string str; - std::vector::const_iterator iter; - for (iter = bytes.begin() ; iter != bytes.end() ; ++iter) - { - unsigned char ch = *iter; - str.push_back(hexDigits[(ch>>4) & 0x0f]); - str.push_back(hexDigits[(ch ) & 0x0f]); - } - return str; -} - - -//######################################################################## -//## D I G E S T -//######################################################################## - - -/** - * - */ -std::string Digest::finishHex() -{ - std::vector hash = finish(); - std::string str = toHex(hash); - return str; -} - -/** - * Convenience method. This is a simple way of getting a hash - */ -std::vector Digest::hash(Digest::HashType typ, - unsigned char *buf, - int len) -{ - std::vector ret; - switch (typ) - { - case HASH_MD5: - { - Md5 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - case HASH_SHA1: - { - Sha1 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - case HASH_SHA224: - { - Sha224 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - case HASH_SHA256: - { - Sha256 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - case HASH_SHA384: - { - Sha384 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - case HASH_SHA512: - { - Sha512 digest; - digest.append(buf, len); - ret = digest.finish(); - break; - } - default: - { - break; - } - } - return ret; -} - - -/** - * Convenience method. Same as above, but for a std::string - */ -std::vector Digest::hash(Digest::HashType typ, - const std::string &str) -{ - return hash(typ, (unsigned char *)str.c_str(), str.size()); -} - -/** - * Convenience method. Return a hexidecimal string of the hash of the buffer. - */ -std::string Digest::hashHex(Digest::HashType typ, - unsigned char *buf, - int len) -{ - std::vector dig = hash(typ, buf, len); - return toHex(dig); -} - -/** - * Convenience method. Return a hexidecimal string of the hash of the - * string argument - */ -std::string Digest::hashHex(Digest::HashType typ, - const std::string &str) -{ - std::vector dig = hash(typ, str); - return toHex(dig); -} - - - -//4.1.1 and 4.1.2 -#define SHA_ROTL(X,n) ((((X) << (n)) & 0xffffffffL) | (((X) >> (32-(n))) & 0xffffffffL)) -#define SHA_Ch(x,y,z) ((z)^((x)&((y)^(z)))) -#define SHA_Maj(x,y,z) (((x)&(y))^((z)&((x)^(y)))) - - -//######################################################################## -//## S H A 1 -//######################################################################## - - -/** - * - */ -void Sha1::reset() -{ - longNr = 0; - byteNr = 0; - - // Initialize H with the magic constants (see FIPS180 for constants) - hashBuf[0] = 0x67452301L; - hashBuf[1] = 0xefcdab89L; - hashBuf[2] = 0x98badcfeL; - hashBuf[3] = 0x10325476L; - hashBuf[4] = 0xc3d2e1f0L; - - for (int i = 0; i < 4; i++) - inb[i] = 0; - - for (int i = 0; i < 80; i++) - inBuf[i] = 0; - - clearByteCount(); -} - - -/** - * - */ -void Sha1::update(unsigned char ch) -{ - incByteCount(); - - inb[byteNr++] = (uint32_t)ch; - if (byteNr >= 4) - { - inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | - inb[2] << 8 | inb[3]; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - -void Sha1::transform() -{ - uint32_t *W = inBuf; - uint32_t *H = hashBuf; - - //for (int t = 0; t < 16 ; t++) - // printf("%2d %08lx\n", t, W[t]); - - //see 6.1.2 - for (int t = 16; t < 80 ; t++) - W[t] = SHA_ROTL((W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]), 1); - - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - uint32_t e = H[4]; - - uint32_t T; - - int t = 0; - for ( ; t < 20 ; t++) - { - //see 4.1.1 for the boolops on B,C, and D - T = TR32(SHA_ROTL(a,5) + ((b&c)|((~b)&d)) + //Ch(b,c,d)) - e + 0x5a827999L + W[t]); - e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; - //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); - } - for ( ; t < 40 ; t++) - { - T = TR32(SHA_ROTL(a,5) + (b^c^d) + e + 0x6ed9eba1L + W[t]); - e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; - //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); - } - for ( ; t < 60 ; t++) - { - T = TR32(SHA_ROTL(a,5) + ((b&c)^(b&d)^(c&d)) + - e + 0x8f1bbcdcL + W[t]); - e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; - //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); - } - for ( ; t < 80 ; t++) - { - T = TR32(SHA_ROTL(a,5) + (b^c^d) + - e + 0xca62c1d6L + W[t]); - e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; - //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); - } - - H[0] = TR32(H[0] + a); - H[1] = TR32(H[1] + b); - H[2] = TR32(H[2] + c); - H[3] = TR32(H[3] + d); - H[4] = TR32(H[4] + e); -} - - - - -/** - * - */ -std::vector Sha1::finish() -{ - //snapshot the bit count now before padding - getBitCount(); - - //Append terminal char - update(0x80); - - //pad until we have a 56 of 64 bytes, allowing for 8 bytes at the end - while ((nrBytes & 63) != 56) - update(0); - - //##### Append length in bits - appendBitCount(); - - //copy out answer - std::vector res; - for (int i=0 ; i<5 ; i++) - { - res.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - } - - // Re-initialize the context (also zeroizes contents) - reset(); - - return res; -} - - - - -//######################################################################## -//## SHA224 -//######################################################################## - - -/** - * SHA-224 and SHA-512 share the same operations and constants - */ - -#define SHA_Rot32(x,s) ((((x) >> s)&0xffffffffL) | (((x) << (32 - s))&0xffffffffL)) -#define SHA_SIGMA0(x) (SHA_Rot32(x, 2) ^ SHA_Rot32(x, 13) ^ SHA_Rot32(x, 22)) -#define SHA_SIGMA1(x) (SHA_Rot32(x, 6) ^ SHA_Rot32(x, 11) ^ SHA_Rot32(x, 25)) -#define SHA_sigma0(x) (SHA_Rot32(x, 7) ^ SHA_Rot32(x, 18) ^ ((x) >> 3)) -#define SHA_sigma1(x) (SHA_Rot32(x, 17) ^ SHA_Rot32(x, 19) ^ ((x) >> 10)) - - -static uint32_t sha256table[64] = -{ - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, - 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, - 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, - 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, - 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, - 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, - 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, - 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, - 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, - 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, - 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, - 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, - 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; - - - - - -/** - * - */ -void Sha224::reset() -{ - longNr = 0; - byteNr = 0; - - // Initialize H with the magic constants (see FIPS180 for constants) - hashBuf[0] = 0xc1059ed8L; - hashBuf[1] = 0x367cd507L; - hashBuf[2] = 0x3070dd17L; - hashBuf[3] = 0xf70e5939L; - hashBuf[4] = 0xffc00b31L; - hashBuf[5] = 0x68581511L; - hashBuf[6] = 0x64f98fa7L; - hashBuf[7] = 0xbefa4fa4L; - - for (int i = 0 ; i < 64 ; i++) - inBuf[i] = 0; - - for (int i = 0 ; i < 4 ; i++) - inb[i] = 0; - - clearByteCount(); -} - - -/** - * - */ -void Sha224::update(unsigned char ch) -{ - incByteCount(); - - inb[byteNr++] = (uint32_t)ch; - if (byteNr >= 4) - { - inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | - inb[2] << 8 | inb[3]; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - -void Sha224::transform() -{ - uint32_t *W = inBuf; - uint32_t *H = hashBuf; - - //for (int t = 0; t < 16 ; t++) - // printf("%2d %08lx\n", t, W[t]); - - //see 6.2.2 - for (int t = 16; t < 64 ; t++) - W[t] = TR32(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); - - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - uint32_t e = H[4]; - uint32_t f = H[5]; - uint32_t g = H[6]; - uint32_t h = H[7]; - - for (int t = 0 ; t < 64 ; t++) - { - //see 4.1.1 for the boolops - uint32_t T1 = TR32(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + - sha256table[t] + W[t]); - uint32_t T2 = TR32(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); - h = g; g = f; f = e; e = TR32(d + T1); d = c; c = b; b = a; a = TR32(T1 + T2); - //printf("%2d %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n", - // t, a, b, c, d, e, f, g, h); - } - - H[0] = TR32(H[0] + a); - H[1] = TR32(H[1] + b); - H[2] = TR32(H[2] + c); - H[3] = TR32(H[3] + d); - H[4] = TR32(H[4] + e); - H[5] = TR32(H[5] + f); - H[6] = TR32(H[6] + g); - H[7] = TR32(H[7] + h); -} - - - -/** - * - */ -std::vector Sha224::finish() -{ - //save our size before padding - getBitCount(); - - // Pad with a binary 1 (0x80) - update(0x80); - //append 0's to make a 56-byte buf. - while ((nrBytes & 63) != 56) - update(0); - - //##### Append length in bits - appendBitCount(); - - // Output hash - std::vector ret; - for (int i = 0 ; i < 7 ; i++) - { - ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - } - - // Re-initialize the context (also zeroizes contents) - reset(); - - return ret; - -} - - - -//######################################################################## -//## SHA256 -//######################################################################## - - -/** - * - */ -void Sha256::reset() -{ - longNr = 0; - byteNr = 0; - - // Initialize H with the magic constants (see FIPS180 for constants) - hashBuf[0] = 0x6a09e667L; - hashBuf[1] = 0xbb67ae85L; - hashBuf[2] = 0x3c6ef372L; - hashBuf[3] = 0xa54ff53aL; - hashBuf[4] = 0x510e527fL; - hashBuf[5] = 0x9b05688cL; - hashBuf[6] = 0x1f83d9abL; - hashBuf[7] = 0x5be0cd19L; - - for (int i = 0 ; i < 64 ; i++) - inBuf[i] = 0; - for (int i = 0 ; i < 4 ; i++) - inb[i] = 0; - - clearByteCount(); -} - - -/** - * - */ -void Sha256::update(unsigned char ch) -{ - incByteCount(); - - inb[byteNr++] = (uint32_t)ch; - if (byteNr >= 4) - { - inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | - inb[2] << 8 | inb[3]; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - - - -void Sha256::transform() -{ - uint32_t *H = hashBuf; - uint32_t *W = inBuf; - - //for (int t = 0; t < 16 ; t++) - // printf("%2d %08lx\n", t, W[t]); - - //see 6.2.2 - for (int t = 16; t < 64 ; t++) - W[t] = TR32(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); - - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - uint32_t e = H[4]; - uint32_t f = H[5]; - uint32_t g = H[6]; - uint32_t h = H[7]; - - for (int t = 0 ; t < 64 ; t++) - { - //see 4.1.1 for the boolops - uint32_t T1 = TR32(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + - sha256table[t] + W[t]); - uint32_t T2 = TR32(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); - h = g; g = f; f = e; e = TR32(d + T1); d = c; c = b; b = a; a = TR32(T1 + T2); - //printf("%2d %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n", - // t, a, b, c, d, e, f, g, h); - } - - H[0] = TR32(H[0] + a); - H[1] = TR32(H[1] + b); - H[2] = TR32(H[2] + c); - H[3] = TR32(H[3] + d); - H[4] = TR32(H[4] + e); - H[5] = TR32(H[5] + f); - H[6] = TR32(H[6] + g); - H[7] = TR32(H[7] + h); -} - - - -/** - * - */ -std::vector Sha256::finish() -{ - //save our size before padding - getBitCount(); - - // Pad with a binary 1 (0x80) - update(0x80); - //append 0's to make a 56-byte buf. - while ((nrBytes & 63) != 56) - update(0); - - //##### Append length in bits - appendBitCount(); - - // Output hash - std::vector ret; - for (int i = 0 ; i < 8 ; i++) - { - ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - } - - // Re-initialize the context (also zeroizes contents) - reset(); - - return ret; - -} - - - -//######################################################################## -//## SHA384 -//######################################################################## - - -/** - * SHA-384 and SHA-512 share the same operations and constants - */ - -#undef SHA_SIGMA0 -#undef SHA_SIGMA1 -#undef SHA_sigma0 -#undef SHA_sigma1 - -#define SHA_Rot64(x,s) (((x) >> s) | ((x) << (64 - s))) -#define SHA_SIGMA0(x) (SHA_Rot64(x, 28) ^ SHA_Rot64(x, 34) ^ SHA_Rot64(x, 39)) -#define SHA_SIGMA1(x) (SHA_Rot64(x, 14) ^ SHA_Rot64(x, 18) ^ SHA_Rot64(x, 41)) -#define SHA_sigma0(x) (SHA_Rot64(x, 1) ^ SHA_Rot64(x, 8) ^ ((x) >> 7)) -#define SHA_sigma1(x) (SHA_Rot64(x, 19) ^ SHA_Rot64(x, 61) ^ ((x) >> 6)) - - -static uint64_t sha512table[80] = -{ - 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL -}; - - - - -/** - * - */ -void Sha384::reset() -{ - longNr = 0; - byteNr = 0; - - // SHA-384 differs from SHA-512 by these constants - hashBuf[0] = 0xcbbb9d5dc1059ed8ULL; - hashBuf[1] = 0x629a292a367cd507ULL; - hashBuf[2] = 0x9159015a3070dd17ULL; - hashBuf[3] = 0x152fecd8f70e5939ULL; - hashBuf[4] = 0x67332667ffc00b31ULL; - hashBuf[5] = 0x8eb44a8768581511ULL; - hashBuf[6] = 0xdb0c2e0d64f98fa7ULL; - hashBuf[7] = 0x47b5481dbefa4fa4ULL; - - for (int i = 0 ; i < 80 ; i++) - inBuf[i] = 0; - for (int i = 0 ; i < 8 ; i++) - inb[i] = 0; - - clearByteCount(); -} - - -/** - * Note that this version of update() handles 64-bit inBuf - * values. - */ -void Sha384::update(unsigned char ch) -{ - incByteCount(); - - inb[byteNr++] = (uint64_t)ch; - if (byteNr >= 8) - { - inBuf[longNr++] = inb[0] << 56 | inb[1] << 48 | - inb[2] << 40 | inb[3] << 32 | - inb[4] << 24 | inb[5] << 16 | - inb[6] << 8 | inb[7]; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - - - -void Sha384::transform() -{ - uint64_t *H = hashBuf; - uint64_t *W = inBuf; - - /* - for (int t = 0; t < 16 ; t++) - { - printf("%2d ", t); - pl(W[t]); - printf("\n"); - } - */ - - //see 6.2.2 - for (int t = 16; t < 80 ; t++) - W[t] = TR64(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); - - uint64_t a = H[0]; - uint64_t b = H[1]; - uint64_t c = H[2]; - uint64_t d = H[3]; - uint64_t e = H[4]; - uint64_t f = H[5]; - uint64_t g = H[6]; - uint64_t h = H[7]; - - for (int t = 0 ; t < 80 ; t++) - { - //see 4.1.1 for the boolops - uint64_t T1 = TR64(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + - sha512table[t] + W[t]); - uint64_t T2 = TR64(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); - h = g; g = f; f = e; e = TR64(d + T1); d = c; c = b; b = a; a = TR64(T1 + T2); - } - - H[0] = TR64(H[0] + a); - H[1] = TR64(H[1] + b); - H[2] = TR64(H[2] + c); - H[3] = TR64(H[3] + d); - H[4] = TR64(H[4] + e); - H[5] = TR64(H[5] + f); - H[6] = TR64(H[6] + g); - H[7] = TR64(H[7] + h); -} - - - -/** - * - */ -std::vector Sha384::finish() -{ - //save our size before padding - getBitCount(); - - // Pad with a binary 1 (0x80) - update((unsigned char)0x80); - //append 0's to make a 112-byte buf. - //we will loop around once if already over 112 - while ((nrBytes & 127) != 112) - update(0); - - //append 128-bit size - //64 upper bits - for (int i = 0 ; i < 8 ; i++) - update((unsigned char)0x00); - //64 lower bits - //##### Append length in bits - appendBitCount(); - - // Output hash - //for SHA-384, we use the left-most 6 64-bit words - std::vector ret; - for (int i = 0 ; i < 6 ; i++) - { - ret.push_back((unsigned char)((hashBuf[i] >> 56) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 48) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 40) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 32) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - } - - // Re-initialize the context (also zeroizes contents) - reset(); - - return ret; - -} - - -//######################################################################## -//## SHA512 -//######################################################################## - - - - - -/** - * - */ -void Sha512::reset() -{ - longNr = 0; - byteNr = 0; - - // Initialize H with the magic constants (see FIPS180 for constants) - hashBuf[0] = 0x6a09e667f3bcc908ULL; - hashBuf[1] = 0xbb67ae8584caa73bULL; - hashBuf[2] = 0x3c6ef372fe94f82bULL; - hashBuf[3] = 0xa54ff53a5f1d36f1ULL; - hashBuf[4] = 0x510e527fade682d1ULL; - hashBuf[5] = 0x9b05688c2b3e6c1fULL; - hashBuf[6] = 0x1f83d9abfb41bd6bULL; - hashBuf[7] = 0x5be0cd19137e2179ULL; - - for (int i = 0 ; i < 80 ; i++) - inBuf[i] = 0; - for (int i = 0 ; i < 8 ; i++) - inb[i] = 0; - - clearByteCount(); -} - - -/** - * Note that this version of update() handles 64-bit inBuf - * values. - */ -void Sha512::update(unsigned char ch) -{ - incByteCount(); - - inb[byteNr++] = (uint64_t)ch; - if (byteNr >= 8) - { - inBuf[longNr++] = inb[0] << 56 | inb[1] << 48 | - inb[2] << 40 | inb[3] << 32 | - inb[4] << 24 | inb[5] << 16 | - inb[6] << 8 | inb[7]; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - - - -void Sha512::transform() -{ - uint64_t *W = inBuf; - uint64_t *H = hashBuf; - - /* - for (int t = 0; t < 16 ; t++) - { - printf("%2d ", t); - pl(W[t]); - printf("\n"); - } - */ - - //see 6.2.2 - for (int t = 16; t < 80 ; t++) - W[t] = TR64(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); - - uint64_t a = H[0]; - uint64_t b = H[1]; - uint64_t c = H[2]; - uint64_t d = H[3]; - uint64_t e = H[4]; - uint64_t f = H[5]; - uint64_t g = H[6]; - uint64_t h = H[7]; - - for (int t = 0 ; t < 80 ; t++) - { - //see 4.1.1 for the boolops - uint64_t T1 = TR64(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + - sha512table[t] + W[t]); - uint64_t T2 = TR64(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); - h = g; g = f; f = e; e = TR64(d + T1); d = c; c = b; b = a; a = TR64(T1 + T2); - } - - H[0] = TR64(H[0] + a); - H[1] = TR64(H[1] + b); - H[2] = TR64(H[2] + c); - H[3] = TR64(H[3] + d); - H[4] = TR64(H[4] + e); - H[5] = TR64(H[5] + f); - H[6] = TR64(H[6] + g); - H[7] = TR64(H[7] + h); -} - - - -/** - * - */ -std::vector Sha512::finish() -{ - //save our size before padding - getBitCount(); - - // Pad with a binary 1 (0x80) - update(0x80); - //append 0's to make a 112-byte buf. - //we will loop around once if already over 112 - while ((nrBytes & 127) != 112) - update(0); - - //append 128-bit size - //64 upper bits - for (int i = 0 ; i < 8 ; i++) - update((unsigned char)0x00); - //64 lower bits - //##### Append length in bits - appendBitCount(); - - // Output hash - std::vector ret; - for (int i = 0 ; i < 8 ; i++) - { - ret.push_back((unsigned char)((hashBuf[i] >> 56) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 48) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 40) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 32) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - } - - // Re-initialize the context (also zeroizes contents) - reset(); - - return ret; - -} - - - -//######################################################################## -//## M D 5 -//######################################################################## - -/** - * - */ -void Md5::reset() -{ - hashBuf[0] = 0x67452301; - hashBuf[1] = 0xefcdab89; - hashBuf[2] = 0x98badcfe; - hashBuf[3] = 0x10325476; - - for (int i=0 ; i<16 ; i++) - inBuf[i] = 0; - for (int i=0 ; i<4 ; i++) - inb[i] = 0; - - clearByteCount(); - - byteNr = 0; - longNr = 0; -} - - -/** - * - */ -void Md5::update(unsigned char ch) -{ - incByteCount(); - - //pack 64 bytes into 16 longs - inb[byteNr++] = (uint32_t)ch; - if (byteNr >= 4) - { - //note the little-endianness - uint32_t val = - inb[3] << 24 | inb[2] << 16 | inb[1] << 8 | inb[0]; - inBuf[longNr++] = val; - byteNr = 0; - } - if (longNr >= 16) - { - transform(); - longNr = 0; - } -} - - - -//# The four core functions - F1 is optimized somewhat - -// #define F1(x, y, z) (x & y | ~x & z) -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -// ## This is the central step in the MD5 algorithm. -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w = TR32(w + (f(x, y, z) + data)), w = w<>(32-s), w = TR32(w + x) ) - -/* - * The core of the MD5 algorithm, this alters an existing MD5 hash to - * reflect the addition of 16 longwords of new data. MD5Update blocks - * the data and converts bytes into longwords for this routine. - * @parm buf points to an array of 4 unsigned 32bit (at least) integers - * @parm in points to an array of 16 unsigned 32bit (at least) integers - */ -void Md5::transform() -{ - uint32_t *i = inBuf; - uint32_t a = hashBuf[0]; - uint32_t b = hashBuf[1]; - uint32_t c = hashBuf[2]; - uint32_t d = hashBuf[3]; - - MD5STEP(F1, a, b, c, d, i[ 0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, i[ 1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, i[ 2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, i[ 3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, i[ 4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, i[ 5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, i[ 6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, i[ 7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, i[ 8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, i[ 9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, i[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, i[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, i[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, i[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, i[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, i[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, i[ 1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, i[ 6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, i[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, i[ 0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, i[ 5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, i[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, i[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, i[ 4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, i[ 9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, i[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, i[ 3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, i[ 8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, i[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, i[ 2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, i[ 7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, i[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, i[ 5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, i[ 8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, i[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, i[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, i[ 1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, i[ 4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, i[ 7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, i[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, i[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, i[ 0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, i[ 3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, i[ 6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, i[ 9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, i[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, i[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, i[ 2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, i[ 0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, i[ 7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, i[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, i[ 5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, i[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, i[ 3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, i[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, i[ 1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, i[ 8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, i[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, i[ 6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, i[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, i[ 4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, i[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, i[ 2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, i[ 9] + 0xeb86d391, 21); - - hashBuf[0] = TR32(hashBuf[0] + a); - hashBuf[1] = TR32(hashBuf[1] + b); - hashBuf[2] = TR32(hashBuf[2] + c); - hashBuf[3] = TR32(hashBuf[3] + d); -} - - -/** - * - */ -std::vector Md5::finish() -{ - //snapshot the bit count now before padding - getBitCount(); - - //Append terminal char - update(0x80); - - //pad until we have a 56 of 64 bytes, allowing for 8 bytes at the end - while (longNr != 14) - update(0); - - //##### Append length in bits - // Don't use appendBitCount(), since md5 is little-endian - update((unsigned char)((nrBits ) & 0xff)); - update((unsigned char)((nrBits>> 8) & 0xff)); - update((unsigned char)((nrBits>>16) & 0xff)); - update((unsigned char)((nrBits>>24) & 0xff)); - update((unsigned char)((nrBits>>32) & 0xff)); - update((unsigned char)((nrBits>>40) & 0xff)); - update((unsigned char)((nrBits>>48) & 0xff)); - update((unsigned char)((nrBits>>56) & 0xff)); - - //copy out answer - std::vector res; - for (int i=0 ; i<4 ; i++) - { - //note the little-endianness - res.push_back((unsigned char)((hashBuf[i] ) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); - res.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); - } - - reset(); // Security! ;-) - - return res; -} - - - - - - -//######################################################################## -//## T E S T S -//######################################################################## - -/** - * Compile this file alone with -DDIGEST_TEST to run the - * tests below: - * > gcc -DDIGEST_TEST digest.cpp -o testdigest - * > testdigest - * - * If you add any new algorithms to this suite, then it is highly - * recommended that you add it to these tests and run it. - */ - -#ifdef DIGEST_TEST - - -typedef struct -{ - const char *msg; - const char *val; -} TestPair; - -static TestPair md5tests[] = -{ - { - "", - "d41d8cd98f00b204e9800998ecf8427e" - }, - { - "a", - "0cc175b9c0f1b6a831c399e269772661" - }, - { - "abc", - "900150983cd24fb0d6963f7d28e17f72" - }, - { - "message digest", - "f96b697d7cb7938d525a2f31aaf161d0" - }, - { - "abcdefghijklmnopqrstuvwxyz", - "c3fcd3d76192e4007dfb496cca67e13b" - }, - { - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "d174ab98d277d9f5a5611c2c9f419d9f" - }, - { - "12345678901234567890123456789012345678901234567890123456789012345678901234567890", - "57edf4a22be3c955ac49da2e2107b67a" - }, - { - NULL, - NULL - } -}; - - - -static TestPair sha1tests[] = -{ - { - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "84983e441c3bd26ebaae4aa1f95129e5e54670f1" - }, - { - NULL, - NULL - } -}; - -static TestPair sha224tests[] = -{ - { - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525" - }, - { - NULL, - NULL - } -}; - -static TestPair sha256tests[] = -{ - { - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" - }, - { - NULL, - NULL - } -}; - -static TestPair sha384tests[] = -{ - { - "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712" - "fcc7c71a557e2db966c3e9fa91746039" - }, - { - NULL, - NULL - } -}; - -static TestPair sha512tests[] = -{ - { - "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" - "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909" - }, - { - NULL, - NULL - } -}; - - -bool hashTests(Digest &digest, TestPair *tp) -{ - for (TestPair *pair = tp ; pair->msg ; pair++) - { - digest.reset(); - std::string msg = pair->msg; - std::string val = pair->val; - digest.append(msg); - std::string res = digest.finishHex(); - printf("### Msg '%s':\n hash '%s'\n exp '%s'\n", - msg.c_str(), res.c_str(), val.c_str()); - if (res != val) - { - printf("ERROR: Hash mismatch\n"); - return false; - } - } - return true; -} - - -bool millionATest(Digest &digest, const std::string &exp) -{ - digest.reset(); - for (int i=0 ; i<1000000 ; i++) - digest.append('a'); - std::string res = digest.finishHex(); - printf("\nHash of 1,000,000 'a'\n calc %s\n exp %s\n", - res.c_str(), exp.c_str()); - if (res != exp) - { - printf("ERROR: Mismatch.\n"); - return false; - } - return true; -} - -static bool doTests() -{ - printf("##########################################\n"); - printf("## MD5\n"); - printf("##########################################\n"); - Md5 md5; - if (!hashTests(md5, md5tests)) - return false; - if (!millionATest(md5, "7707d6ae4e027c70eea2a935c2296f21")) - return false; - printf("\n\n\n"); - printf("##########################################\n"); - printf("## SHA1\n"); - printf("##########################################\n"); - Sha1 sha1; - if (!hashTests(sha1, sha1tests)) - return false; - if (!millionATest(sha1, "34aa973cd4c4daa4f61eeb2bdbad27316534016f")) - return false; - printf("\n\n\n"); - printf("##########################################\n"); - printf("## SHA224\n"); - printf("##########################################\n"); - Sha224 sha224; - if (!hashTests(sha224, sha224tests)) - return false; - if (!millionATest(sha224, - "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")) - return false; - printf("\n\n\n"); - printf("##########################################\n"); - printf("## SHA256\n"); - printf("##########################################\n"); - Sha256 sha256; - if (!hashTests(sha256, sha256tests)) - return false; - if (!millionATest(sha256, - "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")) - return false; - printf("\n\n\n"); - printf("##########################################\n"); - printf("## SHA384\n"); - printf("##########################################\n"); - Sha384 sha384; - if (!hashTests(sha384, sha384tests)) - return false; - /**/ - if (!millionATest(sha384, - "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b" - "07b8b3dc38ecc4ebae97ddd87f3d8985")) - return false; - /**/ - printf("\n\n\n"); - printf("##########################################\n"); - printf("## SHA512\n"); - printf("##########################################\n"); - Sha512 sha512; - if (!hashTests(sha512, sha512tests)) - return false; - if (!millionATest(sha512, - "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" - "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")) - return false; - return true; -} - - -int main(int argc, char **argv) -{ - doTests(); - printf("####### done ########\n"); - return 0; -} - - -#endif /* DIGEST_TEST */ - -//######################################################################## -//## E N D O F F I L E -//######################################################################## diff --git a/src/dom/util/digest.h b/src/dom/util/digest.h deleted file mode 100644 index c161b86bb..000000000 --- a/src/dom/util/digest.h +++ /dev/null @@ -1,654 +0,0 @@ -#ifndef SEEN_DIGEST_H -#define SEEN_DIGEST_H -/* - * - * Author: - * Bob Jamison - * - * Copyright (C) 2006-2008 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * This base class and its subclasses provide an easy API for providing - * several different types of secure hashing functions for whatever use - * a developer might need. This is not intended as a high-performance - * replacement for the fine implementations already available. Rather, it - * is a small and simple (and maybe a bit slow?) tool for moderate common - * hashing requirements, like for communications and authentication. - * - * These hashes are intended to be simple to use. For example: - * Sha256 digest; - * digest.append("The quick brown dog"); - * std::string result = digest.finishHex(); - * - * Or, use one of the static convenience methods: - * - * example: std::string digest = - * Digest::hashHex(Digest::HASH_XXX, str); - * - * ...where HASH_XXX represents one of the hash - * algorithms listed in HashType. - * - * There are several forms of append() for convenience. - * finish() and finishHex() call reset() for both security and - * to prepare for the next use. - * - * - * Much effort has been applied to make this code portable, and it - * has been tested on various 32- and 64-bit machines. If you - * add another algorithm, please test it likewise. - * - * - * The SHA algorithms are derived directly from FIPS-180-3. The - * SHA tests at the bottom of digest.cpp are also directly from - * that document. - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - * - * The MD5 algorithm is from RFC 1321 - * - * To run the tests, compile standalone with -DDIGEST_TEST. Example: - * - * g++ -DDIGEST_TEST digest.cpp -o testdigest - * or - * g++ -DDIGEST_TEST -m64 digest.cpp -o testdigest - * - */ - -#include -#include - -#include - - - -/** - * Base class. Do not use instantiate class directly. Rather, use of of the - * subclasses below, or call one of this class's static convenience methods. - * - * For all subclasses, overload reset(), update(unsigned char), - * transform(), and finish() - */ -class Digest -{ -public: - - /** - * Different types of hash algorithms. - */ - typedef enum - { - HASH_NONE, - HASH_SHA1, - HASH_SHA224, - HASH_SHA256, - HASH_SHA384, - HASH_SHA512, - HASH_MD5 - } HashType; - - /** - * Constructor, with no type - */ - Digest() : hashType(HASH_NONE) - { reset(); } - - /** - * Destructor - */ - virtual ~Digest() - { reset(); } - - /** - * Return one of the enumerated hash types above - */ - virtual int getType() - { return hashType; } - - /** - * Append a single byte to the hash - */ - void append(unsigned char ch) - { update(ch); } - - /** - * Append a string to the hash - */ - virtual void append(const std::string &str) - { - for (unsigned int i=0 ; i &buf) - { //NOTE: function seems to be unused - for (unsigned int i=0 ; i finish() - { - std::vector ret; - return ret; - } - - - //######################## - //# Convenience methods - //######################## - - /** - * Convenience method. This is a simple way of getting a hash. - * Returns a byte buffer with the digest output. - * call with: std::vector digest = - * Digest::hash(Digest::HASH_XXX, buf, len); - */ - static std::vector hash(HashType typ, - unsigned char *buf, - int len); - /** - * Convenience method. This is a simple way of getting a hash. - * Returns a byte buffer with the digest output. - * call with: std::vector digest = - * Digest::hash(Digest::HASH_XXX, str); - */ - static std::vector hash(HashType typ, - const std::string &str); - - /** - * Convenience method. This is a simple way of getting a hash. - * Returns a string with the hexidecimal form of the digest output. - * call with: std::string digest = - * Digest::hash(Digest::HASH_XXX, buf, len); - */ - static std::string hashHex(HashType typ, - unsigned char *buf, - int len); - /** - * Convenience method. This is a simple way of getting a hash. - * Returns a string with the hexidecimal form of the digest output. - * call with: std::string digest = - * Digest::hash(Digest::HASH_XXX, str); - */ - static std::string hashHex(HashType typ, - const std::string &str); - -protected: - - /** - * Update the hash with a given byte - * Overload this in every subclass - */ - virtual void update(unsigned char /*ch*/) - {} - - /** - * Perform the particular block hashing algorithm for a - * particular type of hash. - * Overload this in every subclass - */ - virtual void transform() - {} - - - /** - * The enumerated type of the hash - */ - int hashType; - - /** - * Increment the count of bytes processed so far. Should be called - * in update() - */ - void incByteCount() - { - nrBytes++; - } - - /** - * Clear the byte / bit count information. Both for processing - * another message, also for security. Should be called in reset() - */ - void clearByteCount() - { - nrBytes = nrBits = 0; - } - - /** - * Calculates the bit count from the current byte count. Should be called - * in finish(), before any padding is added. This basically does a - * snapshot of the bitcount value before the padding. - */ - void getBitCount() - { - nrBits = (nrBytes << 3) & 0xFFFFFFFFFFFFFFFFLL; - } - - /** - * Common code for appending the 64-bit bitcount to the end of the - * message, after the padding. Should be called after padding, just - * before outputting the result. - */ - void appendBitCount() - { - update((unsigned char)((nrBits>>56) & 0xff)); - update((unsigned char)((nrBits>>48) & 0xff)); - update((unsigned char)((nrBits>>40) & 0xff)); - update((unsigned char)((nrBits>>32) & 0xff)); - update((unsigned char)((nrBits>>24) & 0xff)); - update((unsigned char)((nrBits>>16) & 0xff)); - update((unsigned char)((nrBits>> 8) & 0xff)); - update((unsigned char)((nrBits ) & 0xff)); - } - - /** - * Bit and byte counts - */ - uint64_t nrBytes; - uint64_t nrBits; -}; - - - - - -/** - * SHA-1, - * Section 6.1, SECURE HASH STANDARD - * Federal Information Processing Standards Publication 180-2 - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - */ -class Sha1 : public Digest -{ -public: - - /** - * Constructor - */ - Sha1() - { hashType = HASH_SHA1; reset(); } - - /** - * Destructor - */ - virtual ~Sha1() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - -private: - - uint32_t hashBuf[5]; - uint32_t inBuf[80]; - - int longNr; - int byteNr; - uint32_t inb[4]; - -}; - - - - - - -/** - * SHA-224, - * Section 6.1, SECURE HASH STANDARD - * Federal Information Processing Standards Publication 180-2 - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - */ -class Sha224 : public Digest -{ -public: - - /** - * Constructor - */ - Sha224() - { hashType = HASH_SHA224; reset(); } - - /** - * Destructor - */ - virtual ~Sha224() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - -private: - - uint32_t hashBuf[8]; - uint32_t inBuf[64]; - int longNr; - int byteNr; - uint32_t inb[4]; - -}; - - - -/** - * SHA-256, - * Section 6.1, SECURE HASH STANDARD - * Federal Information Processing Standards Publication 180-2 - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - */ -class Sha256 : public Digest -{ -public: - - /** - * Constructor - */ - Sha256() - { hashType = HASH_SHA256; reset(); } - - /** - * Destructor - */ - virtual ~Sha256() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - -private: - - uint32_t hashBuf[8]; - uint32_t inBuf[64]; - int longNr; - int byteNr; - uint32_t inb[4]; - -}; - - - -/** - * SHA-384, - * Section 6.1, SECURE HASH STANDARD - * Federal Information Processing Standards Publication 180-2 - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - */ -class Sha384 : public Digest -{ -public: - - /** - * Constructor - */ - Sha384() - { hashType = HASH_SHA384; reset(); } - - /** - * Destructor - */ - virtual ~Sha384() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - - - -private: - - uint64_t hashBuf[8]; - uint64_t inBuf[80]; - int longNr; - int byteNr; - uint64_t inb[8]; - -}; - - - - -/** - * SHA-512, - * Section 6.1, SECURE HASH STANDARD - * Federal Information Processing Standards Publication 180-2 - * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf - */ -class Sha512 : public Digest -{ -public: - - /** - * Constructor - */ - Sha512() - { hashType = HASH_SHA512; reset(); } - - /** - * Destructor - */ - virtual ~Sha512() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - -private: - - uint64_t hashBuf[8]; - uint64_t inBuf[80]; - int longNr; - int byteNr; - uint64_t inb[8]; - -}; - - - - - - - - - -/** - * IETF RFC 1321, MD5 Specification - * http://www.ietf.org/rfc/rfc1321.txt - */ -class Md5 : public Digest -{ -public: - - /** - * Constructor - */ - Md5() - { hashType = HASH_MD5; reset(); } - - /** - * Destructor - */ - virtual ~Md5() - { reset(); } - - /** - * Overloaded from Digest - */ - virtual void reset(); - - /** - * Overloaded from Digest - */ - virtual std::vector finish(); - -protected: - - /** - * Overloaded from Digest - */ - virtual void update(unsigned char val); - - /** - * Overloaded from Digest - */ - virtual void transform(); - -private: - - uint32_t hashBuf[4]; - uint32_t inBuf[16]; - - uint32_t inb[4]; // Buffer for input bytes as longs - int byteNr; // which byte in long - int longNr; // which long in 16-long buffer - -}; - - - - - - - - - -#endif /* __DIGEST_H__ */ - - diff --git a/src/dom/util/thread.cpp b/src/dom/util/thread.cpp deleted file mode 100644 index d5368ef59..000000000 --- a/src/dom/util/thread.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Phoebe DOM Implementation. - * - * This is a C++ approximation of the W3C DOM model, which follows - * fairly closely the specifications in the various .idl files, copies of - * which are provided for reference. Most important is this one: - * - * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html - * - * Authors: - * Bob Jamison - * - * Copyright (C) 2006 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * Thread wrapper. This provides a platform-independent thread - * class for IO and testing. - * - */ - -#include "thread.h" -#include -#include - -namespace org -{ -namespace w3c -{ -namespace dom -{ -namespace util -{ - - -#ifdef __WIN32__ -#include - -static DWORD WINAPI WinThreadFunction(LPVOID context) -{ - Thread *thread = static_cast(context); - thread->execute(); - return 0; -} - - -void Thread::start() -{ - DWORD dwThreadId; - HANDLE hThread = CreateThread(NULL, 0, WinThreadFunction, - (LPVOID)this, 0, &dwThreadId); - //Make sure the thread is started before 'this' is deallocated - while (!started) - sleep(10); - CloseHandle(hThread); -} - -void Thread::sleep(unsigned long millis) -{ - Sleep(millis); -} - - - -#else /* UNIX */ -#include - -void *PthreadThreadFunction(void *context) -{ - Thread *thread = static_cast(context); - thread->execute(); - return NULL; -} - - -void Thread::start() -{ - pthread_t thread; - - int ret = pthread_create(&thread, NULL, - PthreadThreadFunction, (void *)this); - if (ret != 0) - printf("Thread::start: thread creation failed: %s\n", strerror(ret)); - - //Make sure the thread is started before 'this' is deallocated - while (!started) - sleep(10); - -} - -void Thread::sleep(unsigned long millis) -{ - timespec requested; - requested.tv_sec = millis / 1000; - requested.tv_nsec = (millis % 1000 ) * 1000000L; - nanosleep(&requested, NULL); -} - -#endif /* __WIN32__ */ - -} //namespace util -} //namespace dom -} //namespace w3c -} //namespace org - - - -//######################################################################### -//# E N D O F F I L E -//######################################################################### - - diff --git a/src/dom/util/thread.h b/src/dom/util/thread.h deleted file mode 100644 index 1408cd78f..000000000 --- a/src/dom/util/thread.h +++ /dev/null @@ -1,156 +0,0 @@ -#ifndef SEEN_DOM_THREAD_H -#define SEEN_DOM_THREAD_H -/** - * Phoebe DOM Implementation. - * - * This is a C++ approximation of the W3C DOM model, which follows - * fairly closely the specifications in the various .idl files, copies of - * which are provided for reference. Most important is this one: - * - * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html - */ -/* - * Authors: - * Bob Jamison - * - * Copyright (C) 2006 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* - * Thread wrapper. This provides a platform-independent thread - * class for IO and testing. - * - */ - - -namespace org -{ -namespace w3c -{ -namespace dom -{ -namespace util -{ - - -/** - * This is the interface for a delegate class which can - * be run by a Thread. - * Thread thread(runnable); - * thread.start(); - */ -class Runnable -{ -public: - - Runnable() - {} - virtual ~Runnable() - {} - - /** - * The method of a delegate class which can - * be run by a Thread. Thread is completed when this - * method is done. - */ - virtual void run() = 0; - -}; - - - -/** - * A simple wrapper of native threads in a portable class. - * It can be used either to execute its own run() method, or - * delegate to a Runnable class's run() method. - */ -class Thread -{ -public: - - /** - * Create a thread which will execute its own run() method. - */ - Thread() - { runnable = (Runnable *)0 ; started = false; } - - /** - * Create a thread which will run a Runnable class's run() method. - */ - Thread(const Runnable &runner) - { runnable = (Runnable *)&runner; started = false; } - - /** - * This does not kill a spawned thread. - */ - virtual ~Thread() - {} - - /** - * Static method to pause the current thread for a given - * number of milliseconds. - */ - static void sleep(unsigned long millis); - - /** - * This method will be executed if the Thread was created with - * no delegated Runnable class. The thread is completed when - * the method is done. - */ - virtual void run() - {} - - /** - * Starts the thread. - */ - virtual void start(); - - /** - * Calls either this class's run() method, or that of a Runnable. - * A user would normally not call this directly. - */ - virtual void execute() - { - started = true; - if (runnable) - runnable->run(); - else - run(); - } - -private: - - Runnable *runnable; - - bool started; - -}; - - -} //namespace util -} //namespace dom -} //namespace w3c -} //namespace org - - - -#endif // SEEN_DOM_THREAD_H -//######################################################################### -//# E N D O F F I L E -//######################################################################### - - diff --git a/src/dom/util/ziptool.cpp b/src/dom/util/ziptool.cpp deleted file mode 100644 index 9d9d5685c..000000000 --- a/src/dom/util/ziptool.cpp +++ /dev/null @@ -1,3025 +0,0 @@ -/* - * This is intended to be a standalone, reduced capability - * implementation of Gzip and Zip functionality. Its - * targeted use case is for archiving and retrieving single files - * which use these encoding types. Being memory based and - * non-optimized, it is not useful in cases where very large - * archives are needed or where high performance is desired. - * However, it should hopefully work very well for smaller, - * one-at-a-time tasks. What you get in return is the ability - * to drop these files into your project and remove the dependencies - * on ZLib and Info-Zip. Enjoy. - * - * Authors: - * Bob Jamison - * - * Copyright (C) 2006-2007 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include -#include -#include - -#include - -#include "ziptool.h" - - - - - - -//######################################################################## -//# A D L E R 3 2 -//######################################################################## - -/** - * Constructor - */ -Adler32::Adler32() -{ - reset(); -} - -/** - * Destructor - */ -Adler32::~Adler32() -{ -} - -/** - * Reset Adler-32 checksum to initial value. - */ -void Adler32::reset() -{ - value = 1; -} - -// ADLER32_BASE is the largest prime number smaller than 65536 -#define ADLER32_BASE 65521 - -void Adler32::update(unsigned char b) -{ - unsigned long s1 = value & 0xffff; - unsigned long s2 = (value >> 16) & 0xffff; - s1 += b & 0xff; - s2 += s1; - value = ((s2 % ADLER32_BASE) << 16) | (s1 % ADLER32_BASE); -} - -void Adler32::update(char *str) -{ - if (str) - while (*str) - update((unsigned char)*str++); -} - - -/** - * Returns current checksum value. - */ -unsigned long Adler32::getValue() -{ - return value & 0xffffffffL; -} - - - -//######################################################################## -//# C R C 3 2 -//######################################################################## - -/** - * Constructor - */ -Crc32::Crc32() -{ - reset(); -} - -/** - * Destructor - */ -Crc32::~Crc32() -{ -} - -static bool crc_table_ready = false; -static unsigned long crc_table[256]; - -/** - * make the table for a fast CRC. - */ -static void makeCrcTable() -{ - if (crc_table_ready) - return; - for (int n = 0; n < 256; n++) - { - unsigned long c = n; - for (int k = 8; --k >= 0; ) - { - if ((c & 1) != 0) - c = 0xedb88320 ^ (c >> 1); - else - c >>= 1; - } - crc_table[n] = c; - } - crc_table_ready = true; -} - - -/** - * Reset CRC-32 checksum to initial value. - */ -void Crc32::reset() -{ - value = 0; - makeCrcTable(); -} - -void Crc32::update(unsigned char b) -{ - unsigned long c = ~value; - - c &= 0xffffffff; - c = crc_table[(c ^ b) & 0xff] ^ (c >> 8); - value = ~c; -} - - -void Crc32::update(char *str) -{ - if (str) - while (*str) - update((unsigned char)*str++); -} - -void Crc32::update(const std::vector &buf) -{ - std::vector::const_iterator iter; - for (iter=buf.begin() ; iter!=buf.end() ; ++iter) - { - unsigned char ch = *iter; - update(ch); - } -} - - -/** - * Returns current checksum value. - */ -unsigned long Crc32::getValue() -{ - return value & 0xffffffffL; -} - -//######################################################################## -//# I N F L A T E R -//######################################################################## - - -/** - * - */ -typedef struct -{ - int *count; // number of symbols of each length - int *symbol; // canonically ordered symbols -} Huffman; - -/** - * - */ -class Inflater -{ -public: - - Inflater(); - - virtual ~Inflater(); - - static const int MAXBITS = 15; // max bits in a code - static const int MAXLCODES = 286; // max number of literal/length codes - static const int MAXDCODES = 30; // max number of distance codes - static const int MAXCODES = 316; // max codes lengths to read - static const int FIXLCODES = 288; // number of fixed literal/length codes - - /** - * - */ - bool inflate(std::vector &destination, - std::vector &source); - -private: - - /** - * - */ - void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - /** - * - */ - void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - /** - * - */ - void dump(); - - /** - * - */ - int buildHuffman(Huffman *h, int *length, int n); - - /** - * - */ - bool getBits(int need, int *oval); - - /** - * - */ - int doDecode(Huffman *h); - - /** - * - */ - bool doCodes(Huffman *lencode, Huffman *distcode); - - /** - * - */ - bool doStored(); - - /** - * - */ - bool doFixed(); - - /** - * - */ - bool doDynamic(); - - - std::vectordest; - - std::vectorsrc; - unsigned long srcPos; //current read position - int bitBuf; - int bitCnt; - -}; - - -/** - * - */ -Inflater::Inflater() : - dest(), - src(), - srcPos(0), - bitBuf(0), - bitCnt(0) -{ -} - -/** - * - */ -Inflater::~Inflater() -{ -} - -/** - * - */ -void Inflater::error(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "Inflater error:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -/** - * - */ -void Inflater::trace(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "Inflater:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - - -/** - * - */ -void Inflater::dump() -{ - for (unsigned int i=0 ; icount[len] = 0; - for (int symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; // assumes lengths are within bounds - if (h->count[0] == n) // no codes! - { - error("huffman tree will result in failed decode"); - return -1; - } - - // check for an over-subscribed or incomplete set of lengths - int left = 1; // number of possible codes left of current length - for (int len = 1; len <= MAXBITS; len++) - { - left <<= 1; // one more bit, double codes left - left -= h->count[len]; // deduct count from possible codes - if (left < 0) - { - error("huffman over subscribed"); - return -1; - } - } - - // generate offsets into symbol table for each length for sorting - int offs[MAXBITS+1]; //offsets in symbol table for each length - offs[1] = 0; - for (int len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + h->count[len]; - - /* - * put symbols in table sorted by length, by symbol order within each - * length - */ - for (int symbol = 0; symbol < n; symbol++) - if (length[symbol] != 0) - h->symbol[offs[length[symbol]]++] = symbol; - - // return zero for complete set, positive for incomplete set - return left; -} - - -/** - * - */ -bool Inflater::getBits(int requiredBits, int *oval) -{ - long val = bitBuf; - - //add more bytes if needed - while (bitCnt < requiredBits) - { - if (srcPos >= src.size()) - { - error("premature end of input"); - return false; - } - val |= ((long)(src[srcPos++])) << bitCnt; - bitCnt += 8; - } - - //update the buffer and return the data - bitBuf = (int)(val >> requiredBits); - bitCnt -= requiredBits; - *oval = (int)(val & ((1L << requiredBits) - 1)); - - return true; -} - - -/** - * - */ -int Inflater::doDecode(Huffman *h) -{ - int bitTmp = bitBuf; - int left = bitCnt; - int code = 0; - int first = 0; - int index = 0; - int len = 1; - int *next = h->count + 1; - while (true) - { - while (left--) - { - code |= bitTmp & 1; - bitTmp >>= 1; - int count = *next++; - if (code < first + count) - { /* if length len, return symbol */ - bitBuf = bitTmp; - bitCnt = (bitCnt - len) & 7; - return h->symbol[index + (code - first)]; - } - index += count; - first += count; - first <<= 1; - code <<= 1; - len++; - } - left = (MAXBITS+1) - len; - if (left == 0) - break; - if (srcPos >= src.size()) - { - error("premature end of input"); - dump(); - return -1; - } - bitTmp = src[srcPos++]; - if (left > 8) - left = 8; - } - - error("no end of block found"); - return -1; -} - -/** - * - */ -bool Inflater::doCodes(Huffman *lencode, Huffman *distcode) -{ - static const int lens[29] = { // Size base for length codes 257..285 - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static const int lext[29] = { // Extra bits for length codes 257..285 - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static const int dists[30] = { // Offset base for distance codes 0..29 - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577}; - static const int dext[30] = { // Extra bits for distance codes 0..29 - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13}; - - //decode literals and length/distance pairs - while (true) - { - int symbol = doDecode(lencode); - if (symbol == 256) - break; - if (symbol < 0) - { - return false; - } - if (symbol < 256) //literal - { - dest.push_back(symbol); - } - else if (symbol > 256)//length - { - symbol -= 257; - if (symbol >= 29) - { - error("invalid fixed code"); - return false; - } - int ret; - if (!getBits(lext[symbol], &ret)) - return false; - int len = lens[symbol] + ret; - - symbol = doDecode(distcode);//distance - if (symbol < 0) - { - return false; - } - - if (!getBits(dext[symbol], &ret)) - return false; - unsigned int dist = dists[symbol] + ret; - if (dist > dest.size()) - { - error("distance too far back %d/%d", dist, dest.size()); - dump(); - //printf("pos:%d\n", srcPos); - return false; - } - - // copy length bytes from distance bytes back - //dest.push_back('{'); - while (len--) - { - dest.push_back(dest[dest.size() - dist]); - } - //dest.push_back('}'); - - } - } - - return true; -} - -/** - */ -bool Inflater::doStored() -{ - //trace("### stored ###"); - - // clear bits from current byte - bitBuf = 0; - bitCnt = 0; - - // length - if (srcPos + 4 > src.size()) - { - error("not enough input"); - return false; - } - - int len = src[srcPos++]; - len |= src[srcPos++] << 8; - //trace("### len:%d", len); - // check complement - if (src[srcPos++] != (~len & 0xff) || - src[srcPos++] != ((~len >> 8) & 0xff)) - { - error("twos complement for storage size do not match"); - return false; - } - - // copy data - if (srcPos + len > src.size()) - { - error("Not enough input for stored block"); - return false; - } - while (len--) - dest.push_back(src[srcPos++]); - - return true; -} - -/** - */ -bool Inflater::doFixed() -{ - //trace("### fixed ###"); - - static bool firstTime = true; - static int lencnt[MAXBITS+1], lensym[FIXLCODES]; - static int distcnt[MAXBITS+1], distsym[MAXDCODES]; - static Huffman lencode = {lencnt, lensym}; - static Huffman distcode = {distcnt, distsym}; - - if (firstTime) - { - firstTime = false; - - int lengths[FIXLCODES]; - - // literal/length table - int symbol = 0; - for ( ; symbol < 144; symbol++) - lengths[symbol] = 8; - for ( ; symbol < 256; symbol++) - lengths[symbol] = 9; - for ( ; symbol < 280; symbol++) - lengths[symbol] = 7; - for ( ; symbol < FIXLCODES; symbol++) - lengths[symbol] = 8; - buildHuffman(&lencode, lengths, FIXLCODES); - - // distance table - for (int symbol = 0; symbol < MAXDCODES; symbol++) - lengths[symbol] = 5; - buildHuffman(&distcode, lengths, MAXDCODES); - } - - // decode data until end-of-block code - bool ret = doCodes(&lencode, &distcode); - return ret; -} - -/** - */ -bool Inflater::doDynamic() -{ - //trace("### dynamic ###"); - int lengths[MAXCODES]; // descriptor code lengths - int lencnt[MAXBITS+1], lensym[MAXLCODES]; // lencode memory - int distcnt[MAXBITS+1], distsym[MAXDCODES]; // distcode memory - Huffman lencode = {lencnt, lensym}; // length code - Huffman distcode = {distcnt, distsym}; // distance code - static const int order[19] = // permutation of code length codes - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - // get number of lengths in each table, check lengths - int ret; - if (!getBits(5, &ret)) - return false; - int nlen = ret + 257; - if (!getBits(5, &ret)) - return false; - int ndist = ret + 1; - if (!getBits(4, &ret)) - return false; - int ncode = ret + 4; - if (nlen > MAXLCODES || ndist > MAXDCODES) - { - error("Bad codes"); - return false; - } - - // get code length code lengths - int index = 0; - for ( ; index < ncode; index++) - { - if (!getBits(3, &ret)) - return false; - lengths[order[index]] = ret; - } - for ( ; index < 19; index++) - lengths[order[index]] = 0; - - // build huffman table for code lengths codes - if (buildHuffman(&lencode, lengths, 19) != 0) - return false; - - // read length/literal and distance code length tables - index = 0; - while (index < nlen + ndist) - { - int symbol = doDecode(&lencode); - if (symbol < 16) // length in 0..15 - lengths[index++] = symbol; - else - { // repeat instruction - int len = 0; // assume repeating zeros - if (symbol == 16) - { // repeat last length 3..6 times - if (index == 0) - { - error("no last length"); - return false; - } - len = lengths[index - 1];// last length - if (!getBits(2, &ret)) - return false; - symbol = 3 + ret; - } - else if (symbol == 17) // repeat zero 3..10 times - { - if (!getBits(3, &ret)) - return false; - symbol = 3 + ret; - } - else // == 18, repeat zero 11..138 times - { - if (!getBits(7, &ret)) - return false; - symbol = 11 + ret; - } - if (index + symbol > nlen + ndist) - { - error("too many lengths"); - return false; - } - while (symbol--) // repeat last or zero symbol times - lengths[index++] = len; - } - } - - // build huffman table for literal/length codes - int err = buildHuffman(&lencode, lengths, nlen); - if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) - { - error("incomplete length codes"); - //return false; - } - // build huffman table for distance codes - err = buildHuffman(&distcode, lengths + nlen, ndist); - if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) - { - error("incomplete dist codes"); - return false; - } - - // decode data until end-of-block code - bool retn = doCodes(&lencode, &distcode); - return retn; -} - -/** - */ -bool Inflater::inflate(std::vector &destination, - std::vector &source) -{ - dest.clear(); - src = source; - srcPos = 0; - bitBuf = 0; - bitCnt = 0; - - while (true) - { - int last; // one if last block - if (!getBits(1, &last)) - return false; - int type; // block type 0..3 - if (!getBits(2, &type)) - return false; - switch (type) - { - case 0: - if (!doStored()) - return false; - break; - case 1: - if (!doFixed()) - return false; - break; - case 2: - if (!doDynamic()) - return false; - break; - default: - error("Unknown block type %d", type); - return false; - } - if (last) - break; - } - - destination = dest; - - return true; -} - - - - - - -//######################################################################## -//# D E F L A T E R -//######################################################################## - - -#define DEFLATER_BUF_SIZE 32768 -class Deflater -{ -public: - - /** - * - */ - Deflater(); - - /** - * - */ - virtual ~Deflater(); - - /** - * - */ - virtual void reset(); - - /** - * - */ - virtual bool update(int ch); - - /** - * - */ - virtual bool finish(); - - /** - * - */ - virtual std::vector &getCompressed(); - - /** - * - */ - bool deflate(std::vector &dest, - const std::vector &src); - - void encodeDistStatic(unsigned int len, unsigned int dist); - -private: - - //debug messages - void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - bool compressWindow(); - - bool compress(); - - std::vector compressed; - - std::vector uncompressed; - - std::vector window; - - unsigned int windowPos; - - //#### Output - unsigned int outputBitBuf; - unsigned int outputNrBits; - - void put(int ch); - - void putWord(int ch); - - void putFlush(); - - void putBits(unsigned int ch, unsigned int bitsWanted); - - void putBitsR(unsigned int ch, unsigned int bitsWanted); - - //#### Huffman Encode - void encodeLiteralStatic(unsigned int ch); - - unsigned char windowBuf[DEFLATER_BUF_SIZE]; - //assume 32-bit ints - unsigned int windowHashBuf[DEFLATER_BUF_SIZE]; -}; - - -//######################################################################## -//# A P I -//######################################################################## - - -/** - * - */ -Deflater::Deflater() -{ - reset(); -} - -/** - * - */ -Deflater::~Deflater() -{ - -} - -/** - * - */ -void Deflater::reset() -{ - compressed.clear(); - uncompressed.clear(); - window.clear(); - windowPos = 0; - outputBitBuf = 0; - outputNrBits = 0; - for (int k=0; k &Deflater::getCompressed() -{ - return compressed; -} - - -/** - * - */ -bool Deflater::deflate(std::vector &dest, - const std::vector &src) -{ - reset(); - uncompressed = src; - if (!compress()) - return false; - dest = compressed; - return true; -} - - - - - - - -//######################################################################## -//# W O R K I N G C O D E -//######################################################################## - - -//############################# -//# M E S S A G E S -//############################# - -/** - * Print error messages - */ -void Deflater::error(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "Deflater error:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -/** - * Print trace messages - */ -void Deflater::trace(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "Deflater:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - - - - -//############################# -//# O U T P U T -//############################# - -/** - * - */ -void Deflater::put(int ch) -{ - compressed.push_back(ch); - outputBitBuf = 0; - outputNrBits = 0; -} - -/** - * - */ -void Deflater::putWord(int ch) -{ - int lo = (ch ) & 0xff; - int hi = (ch>>8) & 0xff; - put(lo); - put(hi); -} - -/** - * - */ -void Deflater::putFlush() -{ - if (outputNrBits > 0) - { - put(outputBitBuf & 0xff); - } - outputBitBuf = 0; - outputNrBits = 0; -} - -/** - * - */ -void Deflater::putBits(unsigned int ch, unsigned int bitsWanted) -{ - //trace("n:%4u, %d\n", ch, bitsWanted); - - while (bitsWanted--) - { - //add bits to position 7. shift right - outputBitBuf = (outputBitBuf>>1) + (ch<<7 & 0x80); - ch >>= 1; - outputNrBits++; - if (outputNrBits >= 8) - { - unsigned char b = outputBitBuf & 0xff; - //printf("b:%02x\n", b); - put(b); - } - } -} - -static unsigned int bitReverse(unsigned int code, unsigned int nrBits) -{ - unsigned int outb = 0; - while (nrBits--) - { - outb = (outb << 1) | (code & 0x01); - code >>= 1; - } - return outb; -} - - -/** - * - */ -void Deflater::putBitsR(unsigned int ch, unsigned int bitsWanted) -{ - //trace("r:%4u, %d", ch, bitsWanted); - - unsigned int rcode = bitReverse(ch, bitsWanted); - - putBits(rcode, bitsWanted); - -} - - -//############################# -//# E N C O D E -//############################# - - - -void Deflater::encodeLiteralStatic(unsigned int ch) -{ - //trace("c: %d", ch); - - if (ch < 144) - { - putBitsR(ch + 0x0030 , 8); // 00110000 - } - else if (ch < 256) - { - putBitsR(ch - 144 + 0x0190 , 9); // 110010000 - } - else if (ch < 280) - { - putBitsR(ch - 256 + 0x0000 , 7); // 0000000 - } - else if (ch < 288) - { - putBitsR(ch - 280 + 0x00c0 , 8); // 11000000 - } - else //out of range - { - error("Literal out of range: %d", ch); - } - -} - - -typedef struct -{ - unsigned int base; - unsigned int range; - unsigned int bits; -} LenBase; - -LenBase lenBases[] = -{ - { 3, 1, 0 }, - { 4, 1, 0 }, - { 5, 1, 0 }, - { 6, 1, 0 }, - { 7, 1, 0 }, - { 8, 1, 0 }, - { 9, 1, 0 }, - { 10, 1, 0 }, - { 11, 2, 1 }, - { 13, 2, 1 }, - { 15, 2, 1 }, - { 17, 2, 1 }, - { 19, 4, 2 }, - { 23, 4, 2 }, - { 27, 4, 2 }, - { 31, 4, 2 }, - { 35, 8, 3 }, - { 43, 8, 3 }, - { 51, 8, 3 }, - { 59, 8, 3 }, - { 67, 16, 4 }, - { 83, 16, 4 }, - { 99, 16, 4 }, - { 115, 16, 4 }, - { 131, 32, 5 }, - { 163, 32, 5 }, - { 195, 32, 5 }, - { 227, 32, 5 }, - { 258, 1, 0 } -}; - -typedef struct -{ - unsigned int base; - unsigned int range; - unsigned int bits; -} DistBase; - -DistBase distBases[] = -{ - { 1, 1, 0 }, - { 2, 1, 0 }, - { 3, 1, 0 }, - { 4, 1, 0 }, - { 5, 2, 1 }, - { 7, 2, 1 }, - { 9, 4, 2 }, - { 13, 4, 2 }, - { 17, 8, 3 }, - { 25, 8, 3 }, - { 33, 16, 4 }, - { 49, 16, 4 }, - { 65, 32, 5 }, - { 97, 32, 5 }, - { 129, 64, 6 }, - { 193, 64, 6 }, - { 257, 128, 7 }, - { 385, 128, 7 }, - { 513, 256, 8 }, - { 769, 256, 8 }, - { 1025, 512, 9 }, - { 1537, 512, 9 }, - { 2049, 1024, 10 }, - { 3073, 1024, 10 }, - { 4097, 2048, 11 }, - { 6145, 2048, 11 }, - { 8193, 4096, 12 }, - { 12289, 4096, 12 }, - { 16385, 8192, 13 }, - { 24577, 8192, 13 } -}; - -void Deflater::encodeDistStatic(unsigned int len, unsigned int dist) -{ - - //## Output length - - if (len < 3 || len > 258) - { - error("Length out of range:%d", len); - return; - } - - bool found = false; - for (int i=0 ; i<30 ; i++) - { - unsigned int base = lenBases[i].base; - unsigned int range = lenBases[i].range; - if (base + range > len) - { - unsigned int lenCode = 257 + i; - unsigned int length = len - base; - //trace("--- %d %d %d %d", len, base, range, length); - encodeLiteralStatic(lenCode); - putBits(length, lenBases[i].bits); - found = true; - break; - } - } - if (!found) - { - error("Length not found in table:%d", len); - return; - } - - //## Output distance - - if (dist < 4 || dist > 32768) - { - error("Distance out of range:%d", dist); - return; - } - - found = false; - for (int i=0 ; i<30 ; i++) - { - unsigned int base = distBases[i].base; - unsigned int range = distBases[i].range; - if (base + range > dist) - { - unsigned int distCode = i; - unsigned int distance = dist - base; - //error("--- %d %d %d %d", dist, base, range, distance); - putBitsR(distCode, 5); - putBits(distance, distBases[i].bits); - found = true; - break; - } - } - if (!found) - { - error("Distance not found in table:%d", dist); - return; - } -} - - -//############################# -//# C O M P R E S S -//############################# - - -/** - * This method does the dirty work of dictionary - * compression. Basically it looks for redundant - * strings and has the current duplicate refer back - * to the previous one. - */ -bool Deflater::compressWindow() -{ - windowPos = 0; - unsigned int windowSize = window.size(); - //### Compress as much of the window as possible - - unsigned int hash = 0; - //Have each value be a long with the byte at this position, - //plus the 3 bytes after it in the window - for (int i=windowSize-1 ; i>=0 ; i--) - { - unsigned char ch = window[i]; - windowBuf[i] = ch; - hash = ((hash<<8) & 0xffffff00) | ch; - windowHashBuf[i] = hash; - } - - while (windowPos < windowSize - 3) - { - //### Find best match, if any - unsigned int bestMatchLen = 0; - unsigned int bestMatchDist = 0; - if (windowPos >= 4) - { - for (unsigned int lookBack=0 ; lookBack= windowPos -4 ) - lookAheadMax = windowPos - 4 - lookBack; - if (lookAheadMax > 258) - lookAheadMax = 258; - unsigned char *wp = &(windowBuf[windowPos+4]); - unsigned char *lb = &(windowBuf[lookBack+4]); - while (lookAhead bestMatchLen) - { - bestMatchLen = lookAhead; - bestMatchDist = windowPos - lookBack; - } - } - } - } - if (bestMatchLen > 3) - { - //Distance encode - //trace("### distance"); - /* - printf("### 1 '"); - for (int i=0 ; i < bestMatchLen ; i++) - fputc(window[windowPos+i], stdout); - printf("'\n### 2 '"); - for (int i=0 ; i < bestMatchLen ; i++) - fputc(window[windowPos-bestMatchDist+i], stdout); - printf("'\n"); - */ - encodeDistStatic(bestMatchLen, bestMatchDist); - windowPos += bestMatchLen; - } - else - { - //Literal encode - //trace("### literal"); - encodeLiteralStatic(windowBuf[windowPos]); - windowPos++; - } - } - - while (windowPos < windowSize) - encodeLiteralStatic(windowBuf[windowPos++]); - - encodeLiteralStatic(256); - return true; -} - - -/** - * - */ -bool Deflater::compress() -{ - //trace("compress"); - unsigned long total = 0L; - windowPos = 0; - std::vector::iterator iter; - for (iter = uncompressed.begin(); iter != uncompressed.end() ; ) - { - total += windowPos; - trace("total:%ld", total); - if (windowPos > window.size()) - windowPos = window.size(); - window.erase(window.begin() , window.begin()+windowPos); - while (window.size() < 32768 && iter != uncompressed.end()) - { - window.push_back(*iter); - ++iter; - } - if (window.size() >= 32768) - putBits(0x00, 1); //0 -- more blocks - else - putBits(0x01, 1); //1 -- last block - putBits(0x01, 2); //01 -- static trees - if (!compressWindow()) - return false; - } - putFlush(); - return true; -} - - - - - -//######################################################################## -//# G Z I P F I L E -//######################################################################## - -/** - * Constructor - */ -GzipFile::GzipFile() : - data(), - fileName(), - fileBuf(), - fileBufPos(0), - compressionMethod(0) -{ -} - -/** - * Destructor - */ -GzipFile::~GzipFile() -{ -} - -/** - * Print error messages - */ -void GzipFile::error(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "GzipFile error:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -/** - * Print trace messages - */ -void GzipFile::trace(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "GzipFile:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -/** - * - */ -void GzipFile::put(unsigned char ch) -{ - data.push_back(ch); -} - -/** - * - */ -void GzipFile::setData(const std::vector &str) -{ - data = str; -} - -/** - * - */ -void GzipFile::clearData() -{ - data.clear(); -} - -/** - * - */ -std::vector &GzipFile::getData() -{ - return data; -} - -/** - * - */ -std::string &GzipFile::getFileName() -{ - return fileName; -} - -/** - * - */ -void GzipFile::setFileName(const std::string &val) -{ - fileName = val; -} - - - -//##################################### -//# U T I L I T Y -//##################################### - -/** - * Loads a new file into an existing GzipFile - */ -bool GzipFile::loadFile(const std::string &fName) -{ - FILE *f = fopen(fName.c_str() , "rb"); - if (!f) - { - error("Cannot open file %s", fName.c_str()); - return false; - } - while (true) - { - int ch = fgetc(f); - if (ch < 0) - break; - data.push_back(ch); - } - fclose(f); - setFileName(fName); - return true; -} - - - -//##################################### -//# W R I T E -//##################################### - -/** - * - */ -bool GzipFile::putByte(unsigned char ch) -{ - fileBuf.push_back(ch); - return true; -} - - - -/** - * - */ -bool GzipFile::putLong(unsigned long val) -{ - fileBuf.push_back( (unsigned char)((val ) & 0xff)); - fileBuf.push_back( (unsigned char)((val>> 8) & 0xff)); - fileBuf.push_back( (unsigned char)((val>>16) & 0xff)); - fileBuf.push_back( (unsigned char)((val>>24) & 0xff)); - return true; -} - - - -/** - * - */ -bool GzipFile::write() -{ - fileBuf.clear(); - - putByte(0x1f); //magic - putByte(0x8b); //magic - putByte( 8); //compression method - putByte(0x08); //flags. say we have a crc and file name - - unsigned long ltime = (unsigned long) time(NULL); - putLong(ltime); - - //xfl - putByte(0); - //OS - putByte(0); - - //file name - for (unsigned int i=0 ; i compBuf; - Deflater deflater; - if (!deflater.deflate(compBuf, data)) - { - return false; - } - - std::vector::iterator iter; - for (iter=compBuf.begin() ; iter!=compBuf.end() ; ++iter) - { - unsigned char ch = *iter; - putByte(ch); - } - - Crc32 crcEngine; - crcEngine.update(data); - unsigned long crc = crcEngine.getValue(); - putLong(crc); - - putLong(data.size()); - - return true; -} - - -/** - * - */ -bool GzipFile::writeBuffer(std::vector &outBuf) -{ - if (!write()) - return false; - outBuf.clear(); - outBuf = fileBuf; - return true; -} - - -/** - * - */ -bool GzipFile::writeFile(const std::string &fileName) -{ - if (!write()) - return false; - FILE *f = fopen(fileName.c_str(), "wb"); - if (!f) - return false; - std::vector::iterator iter; - for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) - { - unsigned char ch = *iter; - fputc(ch, f); - } - fclose(f); - return true; -} - - -//##################################### -//# R E A D -//##################################### - -bool GzipFile::getByte(unsigned char *ch) -{ - if (fileBufPos >= fileBuf.size()) - { - error("unexpected end of data"); - return false; - } - *ch = fileBuf[fileBufPos++]; - return true; -} - -/** - * - */ -bool GzipFile::getLong(unsigned long *val) -{ - if (fileBuf.size() - fileBufPos < 4) - return false; - int ch1 = fileBuf[fileBufPos++]; - int ch2 = fileBuf[fileBufPos++]; - int ch3 = fileBuf[fileBufPos++]; - int ch4 = fileBuf[fileBufPos++]; - *val = ((ch4<<24) & 0xff000000L) | - ((ch3<<16) & 0x00ff0000L) | - ((ch2<< 8) & 0x0000ff00L) | - ((ch1 ) & 0x000000ffL); - return true; -} - -bool GzipFile::read() -{ - fileBufPos = 0; - - unsigned char ch; - - //magic cookie - if (!getByte(&ch)) - return false; - if (ch != 0x1f) - { - error("bad gzip header"); - return false; - } - if (!getByte(&ch)) - return false; - if (ch != 0x8b) - { - error("bad gzip header"); - return false; - } - - //## compression method - if (!getByte(&ch)) - return false; - compressionMethod = ch & 0xff; - - //## flags - if (!getByte(&ch)) - return false; - //bool ftext = ch & 0x01; - bool fhcrc = ch & 0x02; - bool fextra = ch & 0x04; - bool fname = ch & 0x08; - bool fcomment = ch & 0x10; - - //trace("cm:%d ftext:%d fhcrc:%d fextra:%d fname:%d fcomment:%d", - // cm, ftext, fhcrc, fextra, fname, fcomment); - - //## file time - unsigned long ltime; - if (!getLong(<ime)) - return false; - //time_t mtime = (time_t)ltime; - - //## XFL - if (!getByte(&ch)) - return false; - //int xfl = ch; - - //## OS - if (!getByte(&ch)) - return false; - //int os = ch; - - //std::string timestr = ctime(&mtime); - //trace("xfl:%d os:%d mtime:%s", xfl, os, timestr.c_str()); - - if (fextra) - { - if (!getByte(&ch)) - return false; - long xlen = ch; - if (!getByte(&ch)) - return false; - xlen = (xlen << 8) + ch; - for (long l=0 ; l compBuf; - while (fileBufPos < fileBuf.size() - 8) - { - if (!getByte(&ch)) - return false; - compBuf.push_back(ch); - } - //uncompress - data.clear(); - Inflater inflater; - if (!inflater.inflate(data, compBuf)) - { - return false; - } - - //Get the CRC and compare - Crc32 crcEngine; - crcEngine.update(data); - unsigned long calcCrc = crcEngine.getValue(); - unsigned long givenCrc; - if (!getLong(&givenCrc)) - return false; - if (givenCrc != calcCrc) - { - error("Specified crc, %ud, not what received: %ud", - givenCrc, calcCrc); - return false; - } - - //Get the file size and compare - unsigned long givenFileSize; - if (!getLong(&givenFileSize)) - return false; - if (givenFileSize != data.size()) - { - error("Specified data size, %ld, not what received: %ld", - givenFileSize, data.size()); - return false; - } - - return true; -} - - - -/** - * - */ -bool GzipFile::readBuffer(const std::vector &inbuf) -{ - fileBuf = inbuf; - if (!read()) - return false; - return true; -} - - -/** - * - */ -bool GzipFile::readFile(const std::string &fileName) -{ - fileBuf.clear(); - FILE *f = fopen(fileName.c_str(), "rb"); - if (!f) - return false; - while (true) - { - int ch = fgetc(f); - if (ch < 0) - break; - fileBuf.push_back(ch); - } - fclose(f); - if (!read()) - return false; - return true; -} - - - - - - - - -//######################################################################## -//# Z I P F I L E -//######################################################################## - -/** - * Constructor - */ -ZipEntry::ZipEntry() -{ - crc = 0L; - compressionMethod = 8; - position = 0; -} - -/** - * - */ -ZipEntry::ZipEntry(const std::string &fileNameArg, - const std::string &commentArg) -{ - crc = 0L; - compressionMethod = 8; - fileName = fileNameArg; - comment = commentArg; - position = 0; -} - -/** - * Destructor - */ -ZipEntry::~ZipEntry() -{ -} - - -/** - * - */ -std::string ZipEntry::getFileName() -{ - return fileName; -} - -/** - * - */ -void ZipEntry::setFileName(const std::string &val) -{ - fileName = val; -} - -/** - * - */ -std::string ZipEntry::getComment() -{ - return comment; -} - -/** - * - */ -void ZipEntry::setComment(const std::string &val) -{ - comment = val; -} - -/** - * - */ -unsigned long ZipEntry::getCompressedSize() -{ - return (unsigned long)compressedData.size(); -} - -/** - * - */ -int ZipEntry::getCompressionMethod() -{ - return compressionMethod; -} - -/** - * - */ -void ZipEntry::setCompressionMethod(int val) -{ - compressionMethod = val; -} - -/** - * - */ -std::vector &ZipEntry::getCompressedData() -{ - return compressedData; -} - -/** - * - */ -void ZipEntry::setCompressedData(const std::vector &val) -{ - compressedData = val; -} - -/** - * - */ -unsigned long ZipEntry::getUncompressedSize() -{ - return (unsigned long)uncompressedData.size(); -} - -/** - * - */ -std::vector &ZipEntry::getUncompressedData() -{ - return uncompressedData; -} - -/** - * - */ -void ZipEntry::setUncompressedData(const std::vector &val) -{ - uncompressedData = val; -} - -/** - * - */ -unsigned long ZipEntry::getCrc() -{ - return crc; -} - -/** - * - */ -void ZipEntry::setCrc(unsigned long val) -{ - crc = val; -} - -/** - * - */ -void ZipEntry::write(unsigned char ch) -{ - uncompressedData.push_back(ch); -} - -/** - * - */ -void ZipEntry::finish() -{ - Crc32 c32; - std::vector::iterator iter; - for (iter = uncompressedData.begin() ; - iter!= uncompressedData.end() ; ++iter) - { - unsigned char ch = *iter; - c32.update(ch); - } - crc = c32.getValue(); - switch (compressionMethod) - { - case 0: //none - { - for (iter = uncompressedData.begin() ; - iter!= uncompressedData.end() ; ++iter) - { - unsigned char ch = *iter; - compressedData.push_back(ch); - } - break; - } - case 8: //deflate - { - Deflater deflater; - if (!deflater.deflate(compressedData, uncompressedData)) - { - //some error - } - break; - } - default: - { - printf("error: unknown compression method %d\n", - compressionMethod); - } - } -} - - - - -/** - * - */ -bool ZipEntry::readFile(const std::string &fileNameArg, - const std::string &commentArg) -{ - crc = 0L; - uncompressedData.clear(); - fileName = fileNameArg; - comment = commentArg; - FILE *f = fopen(fileName.c_str(), "rb"); - if (!f) - { - return false; - } - while (true) - { - int ch = fgetc(f); - if (ch < 0) - break; - uncompressedData.push_back((unsigned char)ch); - } - fclose(f); - finish(); - return true; -} - - -/** - * - */ -void ZipEntry::setPosition(unsigned long val) -{ - position = val; -} - -/** - * - */ -unsigned long ZipEntry::getPosition() -{ - return position; -} - - - - - - - -/** - * Constructor - */ -ZipFile::ZipFile() : - entries(), - fileBuf(), - fileBufPos(0), - comment() -{ -} - -/** - * Destructor - */ -ZipFile::~ZipFile() -{ - std::vector::iterator iter; - for (iter=entries.begin() ; iter!=entries.end() ; ++iter) - { - ZipEntry *entry = *iter; - delete entry; - } - entries.clear(); -} - -/** - * - */ -void ZipFile::setComment(const std::string &val) -{ - comment = val; -} - -/** - * - */ -std::string ZipFile::getComment() -{ - return comment; -} - - -/** - * - */ -std::vector &ZipFile::getEntries() -{ - return entries; -} - - - -//##################################### -//# M E S S A G E S -//##################################### - -void ZipFile::error(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "ZipFile error:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -void ZipFile::trace(char const *fmt, ...) -{ - va_list args; - va_start(args, fmt); - fprintf(stdout, "ZipFile:"); - vfprintf(stdout, fmt, args); - fprintf(stdout, "\n"); - va_end(args); -} - -//##################################### -//# U T I L I T Y -//##################################### - -/** - * - */ -ZipEntry *ZipFile::addFile(const std::string &fileName, - const std::string &comment) -{ - ZipEntry *ze = new ZipEntry(); - if (!ze->readFile(fileName, comment)) - { - delete ze; - return NULL; - } - entries.push_back(ze); - return ze; -} - - -/** - * - */ -ZipEntry *ZipFile::newEntry(const std::string &fileName, - const std::string &comment) -{ - ZipEntry *ze = new ZipEntry(fileName, comment); - entries.push_back(ze); - return ze; -} - - -//##################################### -//# W R I T E -//##################################### - -/** - * - */ -bool ZipFile::putLong(unsigned long val) -{ - fileBuf.push_back( ((int)(val )) & 0xff); - fileBuf.push_back( ((int)(val>> 8)) & 0xff); - fileBuf.push_back( ((int)(val>>16)) & 0xff); - fileBuf.push_back( ((int)(val>>24)) & 0xff); - return true; -} - - -/** - * - */ -bool ZipFile::putInt(unsigned int val) -{ - fileBuf.push_back( (val ) & 0xff); - fileBuf.push_back( (val>> 8) & 0xff); - return true; -} - -/** - * - */ -bool ZipFile::putByte(unsigned char val) -{ - fileBuf.push_back(val); - return true; -} - -/** - * - */ -bool ZipFile::writeFileData() -{ - std::vector::iterator iter; - for (iter = entries.begin() ; iter != entries.end() ; ++iter) - { - ZipEntry *entry = *iter; - entry->setPosition(fileBuf.size()); - //##### HEADER - std::string fname = entry->getFileName(); - putLong(0x04034b50L); - putInt(20); //versionNeeded - putInt(0); //gpBitFlag - //putInt(0); //compression method - putInt(entry->getCompressionMethod()); //compression method - putInt(0); //mod time - putInt(0); //mod date - putLong(entry->getCrc()); //crc32 - putLong(entry->getCompressedSize()); - putLong(entry->getUncompressedSize()); - putInt(fname.size());//fileName length - putInt(8);//extra field length - //file name - for (unsigned int i=0 ; i &buf = entry->getCompressedData(); - std::vector::iterator iter; - for (iter = buf.begin() ; iter != buf.end() ; ++iter) - { - unsigned char ch = (unsigned char) *iter; - putByte(ch); - } - } - return true; -} - -/** - * - */ -bool ZipFile::writeCentralDirectory() -{ - unsigned long cdPosition = fileBuf.size(); - std::vector::iterator iter; - for (iter = entries.begin() ; iter != entries.end() ; ++iter) - { - ZipEntry *entry = *iter; - std::string fname = entry->getFileName(); - std::string ecomment = entry->getComment(); - putLong(0x02014b50L); //magic cookie - putInt(2386); //versionMadeBy - putInt(20); //versionNeeded - putInt(0); //gpBitFlag - putInt(entry->getCompressionMethod()); //compression method - putInt(0); //mod time - putInt(0); //mod date - putLong(entry->getCrc()); //crc32 - putLong(entry->getCompressedSize()); - putLong(entry->getUncompressedSize()); - putInt(fname.size());//fileName length - putInt(4);//extra field length - putInt(ecomment.size());//comment length - putInt(0); //disk number start - putInt(0); //internal attributes - putLong(0); //external attributes - putLong(entry->getPosition()); - - //file name - for (unsigned int i=0 ; i &outBuf) -{ - if (!write()) - return false; - outBuf.clear(); - outBuf = fileBuf; - return true; -} - - -/** - * - */ -bool ZipFile::writeFile(const std::string &fileName) -{ - if (!write()) - return false; - FILE *f = fopen(fileName.c_str(), "wb"); - if (!f) - return false; - std::vector::iterator iter; - for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) - { - unsigned char ch = *iter; - fputc(ch, f); - } - fclose(f); - return true; -} - -//##################################### -//# R E A D -//##################################### - -/** - * - */ -bool ZipFile::getLong(unsigned long *val) -{ - if (fileBuf.size() - fileBufPos < 4) - return false; - int ch1 = fileBuf[fileBufPos++]; - int ch2 = fileBuf[fileBufPos++]; - int ch3 = fileBuf[fileBufPos++]; - int ch4 = fileBuf[fileBufPos++]; - *val = ((ch4<<24) & 0xff000000L) | - ((ch3<<16) & 0x00ff0000L) | - ((ch2<< 8) & 0x0000ff00L) | - ((ch1 ) & 0x000000ffL); - return true; -} - -/** - * - */ -bool ZipFile::getInt(unsigned int *val) -{ - if (fileBuf.size() - fileBufPos < 2) - return false; - int ch1 = fileBuf[fileBufPos++]; - int ch2 = fileBuf[fileBufPos++]; - *val = ((ch2<< 8) & 0xff00) | - ((ch1 ) & 0x00ff); - return true; -} - - -/** - * - */ -bool ZipFile::getByte(unsigned char *val) -{ - if (fileBuf.size() <= fileBufPos) - return false; - *val = fileBuf[fileBufPos++]; - return true; -} - - -/** - * - */ -bool ZipFile::readFileData() -{ - //printf("#################################################\n"); - //printf("###D A T A\n"); - //printf("#################################################\n"); - while (true) - { - unsigned long magicCookie; - if (!getLong(&magicCookie)) - { - error("magic cookie not found"); - break; - } - trace("###Cookie:%lx", magicCookie); - if (magicCookie == 0x02014b50L) //central directory - break; - if (magicCookie != 0x04034b50L) - { - error("file header not found"); - return false; - } - unsigned int versionNeeded; - if (!getInt(&versionNeeded)) - { - error("bad version needed found"); - return false; - } - unsigned int gpBitFlag; - if (!getInt(&gpBitFlag)) - { - error("bad bit flag found"); - return false; - } - unsigned int compressionMethod; - if (!getInt(&compressionMethod)) - { - error("bad compressionMethod found"); - return false; - } - unsigned int modTime; - if (!getInt(&modTime)) - { - error("bad modTime found"); - return false; - } - unsigned int modDate; - if (!getInt(&modDate)) - { - error("bad modDate found"); - return false; - } - unsigned long crc32; - if (!getLong(&crc32)) - { - error("bad crc32 found"); - return false; - } - unsigned long compressedSize; - if (!getLong(&compressedSize)) - { - error("bad compressedSize found"); - return false; - } - unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { - error("bad uncompressedSize found"); - return false; - } - unsigned int fileNameLength; - if (!getInt(&fileNameLength)) - { - error("bad fileNameLength found"); - return false; - } - unsigned int extraFieldLength; - if (!getInt(&extraFieldLength)) - { - error("bad extraFieldLength found"); - return false; - } - std::string fileName; - for (unsigned int i=0 ; i compBuf; - if (gpBitFlag & 0x8)//bit 3 was set. means we dont know compressed size - { - unsigned char c1, c2, c3, c4; - c1 = c2 = c3 = c4 = 0; - while (true) - { - unsigned char ch; - if (!getByte(&ch)) - { - error("premature end of data"); - break; - } - compBuf.push_back(ch); - c1 = c2; c2 = c3; c3 = c4; c4 = ch; - if (c1 == 0x50 && c2 == 0x4b && c3 == 0x07 && c4 == 0x08) - { - trace("found end of compressed data"); - //remove the cookie - compBuf.erase(compBuf.end() -4, compBuf.end()); - break; - } - } - } - else - { - for (unsigned long bnr = 0 ; bnr < compressedSize ; bnr++) - { - unsigned char ch; - if (!getByte(&ch)) - { - error("premature end of data"); - break; - } - compBuf.push_back(ch); - } - } - - printf("### data: "); - for (int i=0 ; i<10 ; i++) - printf("%02x ", compBuf[i] & 0xff); - printf("\n"); - - if (gpBitFlag & 0x8)//only if bit 3 set - { - /* this cookie was read in the loop above - unsigned long dataDescriptorSignature ; - if (!getLong(&dataDescriptorSignature)) - break; - if (dataDescriptorSignature != 0x08074b50L) - { - error("bad dataDescriptorSignature found"); - return false; - } - */ - unsigned long crc32; - if (!getLong(&crc32)) - { - error("bad crc32 found"); - return false; - } - unsigned long compressedSize; - if (!getLong(&compressedSize)) - { - error("bad compressedSize found"); - return false; - } - unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { - error("bad uncompressedSize found"); - return false; - } - }//bit 3 was set - //break; - - std::vector uncompBuf; - switch (compressionMethod) - { - case 8: //deflate - { - Inflater inflater; - if (!inflater.inflate(uncompBuf, compBuf)) - { - return false; - } - break; - } - default: - { - error("Unimplemented compression method %d", compressionMethod); - return false; - } - } - - if (uncompressedSize != uncompBuf.size()) - { - error("Size mismatch. Expected %ld, received %ld", - uncompressedSize, uncompBuf.size()); - return false; - } - - Crc32 crcEngine; - crcEngine.update(uncompBuf); - unsigned long crc = crcEngine.getValue(); - if (crc != crc32) - { - error("Crc mismatch. Calculated %08ux, received %08ux", crc, crc32); - return false; - } - - ZipEntry *ze = new ZipEntry(fileName, comment); - ze->setCompressionMethod(compressionMethod); - ze->setCompressedData(compBuf); - ze->setUncompressedData(uncompBuf); - ze->setCrc(crc); - entries.push_back(ze); - - - } - return true; -} - - -/** - * - */ -bool ZipFile::readCentralDirectory() -{ - //printf("#################################################\n"); - //printf("###D I R E C T O R Y\n"); - //printf("#################################################\n"); - while (true) - { - //We start with a central directory cookie already - //Check at the bottom of the loop. - unsigned int version; - if (!getInt(&version)) - { - error("bad version found"); - return false; - } - unsigned int versionNeeded; - if (!getInt(&versionNeeded)) - { - error("bad version found"); - return false; - } - unsigned int gpBitFlag; - if (!getInt(&gpBitFlag)) - { - error("bad bit flag found"); - return false; - } - unsigned int compressionMethod; - if (!getInt(&compressionMethod)) - { - error("bad compressionMethod found"); - return false; - } - unsigned int modTime; - if (!getInt(&modTime)) - { - error("bad modTime found"); - return false; - } - unsigned int modDate; - if (!getInt(&modDate)) - { - error("bad modDate found"); - return false; - } - unsigned long crc32; - if (!getLong(&crc32)) - { - error("bad crc32 found"); - return false; - } - unsigned long compressedSize; - if (!getLong(&compressedSize)) - { - error("bad compressedSize found"); - return false; - } - unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { - error("bad uncompressedSize found"); - return false; - } - unsigned int fileNameLength; - if (!getInt(&fileNameLength)) - { - error("bad fileNameLength found"); - return false; - } - unsigned int extraFieldLength; - if (!getInt(&extraFieldLength)) - { - error("bad extraFieldLength found"); - return false; - } - unsigned int fileCommentLength; - if (!getInt(&fileCommentLength)) - { - error("bad fileCommentLength found"); - return false; - } - unsigned int diskNumberStart; - if (!getInt(&diskNumberStart)) - { - error("bad diskNumberStart found"); - return false; - } - unsigned int internalFileAttributes; - if (!getInt(&internalFileAttributes)) - { - error("bad internalFileAttributes found"); - return false; - } - unsigned long externalFileAttributes; - if (!getLong(&externalFileAttributes)) - { - error("bad externalFileAttributes found"); - return false; - } - unsigned long localHeaderOffset; - if (!getLong(&localHeaderOffset)) - { - error("bad localHeaderOffset found"); - return false; - } - std::string fileName; - for (unsigned int i=0 ; i &inbuf) -{ - fileBuf = inbuf; - if (!read()) - return false; - return true; -} - - -/** - * - */ -bool ZipFile::readFile(const std::string &fileName) -{ - fileBuf.clear(); - FILE *f = fopen(fileName.c_str(), "rb"); - if (!f) - return false; - while (true) - { - int ch = fgetc(f); - if (ch < 0) - break; - fileBuf.push_back(ch); - } - fclose(f); - if (!read()) - return false; - return true; -} - - - - - - - - - -//######################################################################## -//# E N D O F F I L E -//######################################################################## - - diff --git a/src/dom/util/ziptool.h b/src/dom/util/ziptool.h deleted file mode 100644 index dbae8ac60..000000000 --- a/src/dom/util/ziptool.h +++ /dev/null @@ -1,567 +0,0 @@ -#ifndef SEEN_ZIPTOOL_H -#define SEEN_ZIPTOOL_H -/** - * This is intended to be a standalone, reduced capability - * implementation of Gzip and Zip functionality. Its - * targeted use case is for archiving and retrieving single files - * which use these encoding types. Being memory based and - * non-optimized, it is not useful in cases where very large - * archives are needed or where high performance is desired. - * However, it should hopefully work well for smaller, - * one-at-a-time tasks. What you get in return is the ability - * to drop these files into your project and remove the dependencies - * on ZLib and Info-Zip. Enjoy. - */ -/* - * Authors: - * Bob Jamison - * - * Copyright (C) 2006-2007 Bob Jamison - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include -#include - - -//######################################################################## -//# A D L E R 3 2 -//######################################################################## - -class Adler32 -{ -public: - - Adler32(); - - virtual ~Adler32(); - - void reset(); - - void update(unsigned char b); - - void update(char *str); - - unsigned long getValue(); - -private: - - unsigned long value; - -}; - - -//######################################################################## -//# C R C 3 2 -//######################################################################## - -class Crc32 -{ -public: - - Crc32(); - - virtual ~Crc32(); - - void reset(); - - void update(unsigned char b); - - void update(char *str); - - void update(const std::vector &buf); - - unsigned long getValue(); - -private: - - unsigned long value; - -}; - - - - - - -//######################################################################## -//# G Z I P S T R E A M S -//######################################################################## - -class GzipFile -{ -public: - - /** - * - */ - GzipFile(); - - /** - * - */ - virtual ~GzipFile(); - - /** - * - */ - virtual void put(unsigned char ch); - - /** - * - */ - virtual void setData(const std::vector &str); - - /** - * - */ - virtual void clearData(); - - /** - * - */ - virtual std::vector &getData(); - - /** - * - */ - virtual std::string &getFileName(); - - /** - * - */ - virtual void setFileName(const std::string &val); - - - //###################### - //# U T I L I T Y - //###################### - - /** - * - */ - virtual bool readFile(const std::string &fName); - - //###################### - //# W R I T E - //###################### - - /** - * - */ - virtual bool write(); - - /** - * - */ - virtual bool writeBuffer(std::vector &outbuf); - - /** - * - */ - virtual bool writeFile(const std::string &fileName); - - - //###################### - //# R E A D - //###################### - - - /** - * - */ - virtual bool read(); - - /** - * - */ - virtual bool readBuffer(const std::vector &inbuf); - - /** - * - */ - virtual bool loadFile(const std::string &fileName); - - - -private: - - std::vector data; - std::string fileName; - - //debug messages - void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - std::vector fileBuf; - unsigned long fileBufPos; - - bool getByte(unsigned char *ch); - bool getLong(unsigned long *val); - - bool putByte(unsigned char ch); - bool putLong(unsigned long val); - - int compressionMethod; -}; - - - - -//######################################################################## -//# Z I P F I L E -//######################################################################## - - -/** - * - */ -class ZipEntry -{ -public: - - /** - * - */ - ZipEntry(); - - /** - * - */ - ZipEntry(const std::string &fileName, - const std::string &comment); - - /** - * - */ - virtual ~ZipEntry(); - - /** - * - */ - virtual std::string getFileName(); - - /** - * - */ - virtual void setFileName(const std::string &val); - - /** - * - */ - virtual std::string getComment(); - - /** - * - */ - virtual void setComment(const std::string &val); - - /** - * - */ - virtual unsigned long getCompressedSize(); - - /** - * - */ - virtual int getCompressionMethod(); - - /** - * - */ - virtual void setCompressionMethod(int val); - - /** - * - */ - virtual std::vector &getCompressedData(); - - /** - * - */ - virtual void setCompressedData(const std::vector &val); - - /** - * - */ - virtual unsigned long getUncompressedSize(); - - /** - * - */ - virtual std::vector &getUncompressedData(); - - /** - * - */ - virtual void setUncompressedData(const std::vector &val); - - /** - * - */ - virtual void write(unsigned char ch); - - /** - * - */ - virtual void finish(); - - /** - * - */ - virtual unsigned long getCrc(); - - /** - * - */ - virtual void setCrc(unsigned long crc); - - /** - * - */ - virtual bool readFile(const std::string &fileNameArg, - const std::string &commentArg); - - /** - * - */ - virtual void setPosition(unsigned long val); - - /** - * - */ - virtual unsigned long getPosition(); - -private: - - unsigned long crc; - - std::string fileName; - std::string comment; - - int compressionMethod; - - std::vector compressedData; - std::vector uncompressedData; - - unsigned long position; -}; - - - - - - - - - -/** - * This class sits over the zlib and gzip code to - * implement a PKWare or Info-Zip .zip file reader and - * writer - */ -class ZipFile -{ -public: - - /** - * - */ - ZipFile(); - - /** - * - */ - virtual ~ZipFile(); - - //###################### - //# V A R I A B L E S - //###################### - - /** - * - */ - virtual void setComment(const std::string &val); - - /** - * - */ - virtual std::string getComment(); - - /** - * Return the list of entries currently in this file - */ - std::vector &getEntries(); - - - //###################### - //# U T I L I T Y - //###################### - - /** - * - */ - virtual ZipEntry *addFile(const std::string &fileNameArg, - const std::string &commentArg); - - /** - * - */ - virtual ZipEntry *newEntry(const std::string &fileNameArg, - const std::string &commentArg); - - //###################### - //# W R I T E - //###################### - - /** - * - */ - virtual bool write(); - - /** - * - */ - virtual bool writeBuffer(std::vector &outbuf); - - /** - * - */ - virtual bool writeFile(const std::string &fileName); - - - //###################### - //# R E A D - //###################### - - - /** - * - */ - virtual bool read(); - - /** - * - */ - virtual bool readBuffer(const std::vector &inbuf); - - /** - * - */ - virtual bool readFile(const std::string &fileName); - - -private: - - //debug messages - void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; - - //# Private writing methods - - /** - * - */ - bool putLong(unsigned long val); - - /** - * - */ - bool putInt(unsigned int val); - - - /** - * - */ - bool putByte(unsigned char val); - - /** - * - */ - bool writeFileData(); - - /** - * - */ - bool writeCentralDirectory(); - - - //# Private reading methods - - /** - * - */ - bool getLong(unsigned long *val); - - /** - * - */ - bool getInt(unsigned int *val); - - /** - * - */ - bool getByte(unsigned char *val); - - /** - * - */ - bool readFileData(); - - /** - * - */ - bool readCentralDirectory(); - - - std::vector entries; - - std::vector fileBuf; - unsigned long fileBufPos; - - std::string comment; -}; - - - - - - -#endif // SEEN_ZIPTOOL_H - - -//######################################################################## -//# E N D O F F I L E -//######################################################################## - -- cgit v1.2.3 From dba2f7dfcf0c7792a40acf5f1fc1e50b385adaa8 Mon Sep 17 00:00:00 2001 From: Kris De Gussem Date: Sat, 9 Feb 2013 07:53:01 +0100 Subject: partially reverted previous commit (bzr r12110) --- src/dom/CMakeLists.txt | 6 + src/dom/Makefile_insert | 7 +- src/dom/util/digest.cpp | 1456 ++++++++++++++++++++++ src/dom/util/digest.h | 654 ++++++++++ src/dom/util/ziptool.cpp | 3025 ++++++++++++++++++++++++++++++++++++++++++++++ src/dom/util/ziptool.h | 567 +++++++++ 6 files changed, 5714 insertions(+), 1 deletion(-) create mode 100644 src/dom/util/digest.cpp create mode 100644 src/dom/util/digest.h create mode 100644 src/dom/util/ziptool.cpp create mode 100644 src/dom/util/ziptool.h (limited to 'src') diff --git a/src/dom/CMakeLists.txt b/src/dom/CMakeLists.txt index bc2f58c29..15b4ba74d 100644 --- a/src/dom/CMakeLists.txt +++ b/src/dom/CMakeLists.txt @@ -26,6 +26,9 @@ set(dom_SRC io/stringstream.cpp io/uristream.cpp + util/digest.cpp + util/ziptool.cpp + # ------- # Headers @@ -64,6 +67,9 @@ set(dom_SRC io/gzipstream.h io/stringstream.h io/uristream.h + + util/digest.h + util/ziptool.h ) add_inkscape_lib(dom_LIB "${dom_SRC}") diff --git a/src/dom/Makefile_insert b/src/dom/Makefile_insert index 66333ba47..17bab94ac 100644 --- a/src/dom/Makefile_insert +++ b/src/dom/Makefile_insert @@ -63,4 +63,9 @@ dom_libdom_a_SOURCES = \ dom/io/stringstream.cpp \ dom/io/stringstream.h \ dom/io/uristream.cpp \ - dom/io/uristream.h + dom/io/uristream.h \ + dom/util/digest.h \ + dom/util/digest.cpp \ + dom/util/ziptool.h \ + dom/util/ziptool.cpp + diff --git a/src/dom/util/digest.cpp b/src/dom/util/digest.cpp new file mode 100644 index 000000000..2baed4860 --- /dev/null +++ b/src/dom/util/digest.cpp @@ -0,0 +1,1456 @@ +/* + * Secure Hashing Tool + * * + * Authors: + * Bob Jamison + * + * Copyright (C) 2006-2008 Bob Jamison + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "digest.h" + + +//######################################################################## +//## U T I L I T Y +//######################################################################## + +/** + * Use this to print out a 64-bit int when otherwise difficult + */ +/* +static void pl(uint64_t val) +{ + for (int shift=56 ; shift>=0 ; shift-=8) + { + int ch = (val >> shift) & 0xff; + printf("%02x", ch); + } +} +*/ + + + +/** + * 3These truncate their arguments to + * unsigned 32-bit or unsigned 64-bit. + */ +#define TR32(x) ((x) & 0xffffffffL) +#define TR64(x) ((x) & 0xffffffffffffffffLL) + + +static const char *hexDigits = "0123456789abcdef"; + +static std::string toHex(const std::vector &bytes) +{ + std::string str; + std::vector::const_iterator iter; + for (iter = bytes.begin() ; iter != bytes.end() ; ++iter) + { + unsigned char ch = *iter; + str.push_back(hexDigits[(ch>>4) & 0x0f]); + str.push_back(hexDigits[(ch ) & 0x0f]); + } + return str; +} + + +//######################################################################## +//## D I G E S T +//######################################################################## + + +/** + * + */ +std::string Digest::finishHex() +{ + std::vector hash = finish(); + std::string str = toHex(hash); + return str; +} + +/** + * Convenience method. This is a simple way of getting a hash + */ +std::vector Digest::hash(Digest::HashType typ, + unsigned char *buf, + int len) +{ + std::vector ret; + switch (typ) + { + case HASH_MD5: + { + Md5 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + case HASH_SHA1: + { + Sha1 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + case HASH_SHA224: + { + Sha224 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + case HASH_SHA256: + { + Sha256 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + case HASH_SHA384: + { + Sha384 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + case HASH_SHA512: + { + Sha512 digest; + digest.append(buf, len); + ret = digest.finish(); + break; + } + default: + { + break; + } + } + return ret; +} + + +/** + * Convenience method. Same as above, but for a std::string + */ +std::vector Digest::hash(Digest::HashType typ, + const std::string &str) +{ + return hash(typ, (unsigned char *)str.c_str(), str.size()); +} + +/** + * Convenience method. Return a hexidecimal string of the hash of the buffer. + */ +std::string Digest::hashHex(Digest::HashType typ, + unsigned char *buf, + int len) +{ + std::vector dig = hash(typ, buf, len); + return toHex(dig); +} + +/** + * Convenience method. Return a hexidecimal string of the hash of the + * string argument + */ +std::string Digest::hashHex(Digest::HashType typ, + const std::string &str) +{ + std::vector dig = hash(typ, str); + return toHex(dig); +} + + + +//4.1.1 and 4.1.2 +#define SHA_ROTL(X,n) ((((X) << (n)) & 0xffffffffL) | (((X) >> (32-(n))) & 0xffffffffL)) +#define SHA_Ch(x,y,z) ((z)^((x)&((y)^(z)))) +#define SHA_Maj(x,y,z) (((x)&(y))^((z)&((x)^(y)))) + + +//######################################################################## +//## S H A 1 +//######################################################################## + + +/** + * + */ +void Sha1::reset() +{ + longNr = 0; + byteNr = 0; + + // Initialize H with the magic constants (see FIPS180 for constants) + hashBuf[0] = 0x67452301L; + hashBuf[1] = 0xefcdab89L; + hashBuf[2] = 0x98badcfeL; + hashBuf[3] = 0x10325476L; + hashBuf[4] = 0xc3d2e1f0L; + + for (int i = 0; i < 4; i++) + inb[i] = 0; + + for (int i = 0; i < 80; i++) + inBuf[i] = 0; + + clearByteCount(); +} + + +/** + * + */ +void Sha1::update(unsigned char ch) +{ + incByteCount(); + + inb[byteNr++] = (uint32_t)ch; + if (byteNr >= 4) + { + inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | + inb[2] << 8 | inb[3]; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + +void Sha1::transform() +{ + uint32_t *W = inBuf; + uint32_t *H = hashBuf; + + //for (int t = 0; t < 16 ; t++) + // printf("%2d %08lx\n", t, W[t]); + + //see 6.1.2 + for (int t = 16; t < 80 ; t++) + W[t] = SHA_ROTL((W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]), 1); + + uint32_t a = H[0]; + uint32_t b = H[1]; + uint32_t c = H[2]; + uint32_t d = H[3]; + uint32_t e = H[4]; + + uint32_t T; + + int t = 0; + for ( ; t < 20 ; t++) + { + //see 4.1.1 for the boolops on B,C, and D + T = TR32(SHA_ROTL(a,5) + ((b&c)|((~b)&d)) + //Ch(b,c,d)) + e + 0x5a827999L + W[t]); + e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; + //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); + } + for ( ; t < 40 ; t++) + { + T = TR32(SHA_ROTL(a,5) + (b^c^d) + e + 0x6ed9eba1L + W[t]); + e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; + //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); + } + for ( ; t < 60 ; t++) + { + T = TR32(SHA_ROTL(a,5) + ((b&c)^(b&d)^(c&d)) + + e + 0x8f1bbcdcL + W[t]); + e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; + //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); + } + for ( ; t < 80 ; t++) + { + T = TR32(SHA_ROTL(a,5) + (b^c^d) + + e + 0xca62c1d6L + W[t]); + e = d; d = c; c = SHA_ROTL(b, 30); b = a; a = T; + //printf("%2d %08lx %08lx %08lx %08lx %08lx\n", t, a, b, c, d, e); + } + + H[0] = TR32(H[0] + a); + H[1] = TR32(H[1] + b); + H[2] = TR32(H[2] + c); + H[3] = TR32(H[3] + d); + H[4] = TR32(H[4] + e); +} + + + + +/** + * + */ +std::vector Sha1::finish() +{ + //snapshot the bit count now before padding + getBitCount(); + + //Append terminal char + update(0x80); + + //pad until we have a 56 of 64 bytes, allowing for 8 bytes at the end + while ((nrBytes & 63) != 56) + update(0); + + //##### Append length in bits + appendBitCount(); + + //copy out answer + std::vector res; + for (int i=0 ; i<5 ; i++) + { + res.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + } + + // Re-initialize the context (also zeroizes contents) + reset(); + + return res; +} + + + + +//######################################################################## +//## SHA224 +//######################################################################## + + +/** + * SHA-224 and SHA-512 share the same operations and constants + */ + +#define SHA_Rot32(x,s) ((((x) >> s)&0xffffffffL) | (((x) << (32 - s))&0xffffffffL)) +#define SHA_SIGMA0(x) (SHA_Rot32(x, 2) ^ SHA_Rot32(x, 13) ^ SHA_Rot32(x, 22)) +#define SHA_SIGMA1(x) (SHA_Rot32(x, 6) ^ SHA_Rot32(x, 11) ^ SHA_Rot32(x, 25)) +#define SHA_sigma0(x) (SHA_Rot32(x, 7) ^ SHA_Rot32(x, 18) ^ ((x) >> 3)) +#define SHA_sigma1(x) (SHA_Rot32(x, 17) ^ SHA_Rot32(x, 19) ^ ((x) >> 10)) + + +static uint32_t sha256table[64] = +{ + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, + 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, + 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, + 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, + 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, + 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, + 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, + 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, + 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, + 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, + 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, + 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, + 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + + + + + +/** + * + */ +void Sha224::reset() +{ + longNr = 0; + byteNr = 0; + + // Initialize H with the magic constants (see FIPS180 for constants) + hashBuf[0] = 0xc1059ed8L; + hashBuf[1] = 0x367cd507L; + hashBuf[2] = 0x3070dd17L; + hashBuf[3] = 0xf70e5939L; + hashBuf[4] = 0xffc00b31L; + hashBuf[5] = 0x68581511L; + hashBuf[6] = 0x64f98fa7L; + hashBuf[7] = 0xbefa4fa4L; + + for (int i = 0 ; i < 64 ; i++) + inBuf[i] = 0; + + for (int i = 0 ; i < 4 ; i++) + inb[i] = 0; + + clearByteCount(); +} + + +/** + * + */ +void Sha224::update(unsigned char ch) +{ + incByteCount(); + + inb[byteNr++] = (uint32_t)ch; + if (byteNr >= 4) + { + inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | + inb[2] << 8 | inb[3]; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + +void Sha224::transform() +{ + uint32_t *W = inBuf; + uint32_t *H = hashBuf; + + //for (int t = 0; t < 16 ; t++) + // printf("%2d %08lx\n", t, W[t]); + + //see 6.2.2 + for (int t = 16; t < 64 ; t++) + W[t] = TR32(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); + + uint32_t a = H[0]; + uint32_t b = H[1]; + uint32_t c = H[2]; + uint32_t d = H[3]; + uint32_t e = H[4]; + uint32_t f = H[5]; + uint32_t g = H[6]; + uint32_t h = H[7]; + + for (int t = 0 ; t < 64 ; t++) + { + //see 4.1.1 for the boolops + uint32_t T1 = TR32(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + + sha256table[t] + W[t]); + uint32_t T2 = TR32(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); + h = g; g = f; f = e; e = TR32(d + T1); d = c; c = b; b = a; a = TR32(T1 + T2); + //printf("%2d %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n", + // t, a, b, c, d, e, f, g, h); + } + + H[0] = TR32(H[0] + a); + H[1] = TR32(H[1] + b); + H[2] = TR32(H[2] + c); + H[3] = TR32(H[3] + d); + H[4] = TR32(H[4] + e); + H[5] = TR32(H[5] + f); + H[6] = TR32(H[6] + g); + H[7] = TR32(H[7] + h); +} + + + +/** + * + */ +std::vector Sha224::finish() +{ + //save our size before padding + getBitCount(); + + // Pad with a binary 1 (0x80) + update(0x80); + //append 0's to make a 56-byte buf. + while ((nrBytes & 63) != 56) + update(0); + + //##### Append length in bits + appendBitCount(); + + // Output hash + std::vector ret; + for (int i = 0 ; i < 7 ; i++) + { + ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + } + + // Re-initialize the context (also zeroizes contents) + reset(); + + return ret; + +} + + + +//######################################################################## +//## SHA256 +//######################################################################## + + +/** + * + */ +void Sha256::reset() +{ + longNr = 0; + byteNr = 0; + + // Initialize H with the magic constants (see FIPS180 for constants) + hashBuf[0] = 0x6a09e667L; + hashBuf[1] = 0xbb67ae85L; + hashBuf[2] = 0x3c6ef372L; + hashBuf[3] = 0xa54ff53aL; + hashBuf[4] = 0x510e527fL; + hashBuf[5] = 0x9b05688cL; + hashBuf[6] = 0x1f83d9abL; + hashBuf[7] = 0x5be0cd19L; + + for (int i = 0 ; i < 64 ; i++) + inBuf[i] = 0; + for (int i = 0 ; i < 4 ; i++) + inb[i] = 0; + + clearByteCount(); +} + + +/** + * + */ +void Sha256::update(unsigned char ch) +{ + incByteCount(); + + inb[byteNr++] = (uint32_t)ch; + if (byteNr >= 4) + { + inBuf[longNr++] = inb[0] << 24 | inb[1] << 16 | + inb[2] << 8 | inb[3]; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + + + +void Sha256::transform() +{ + uint32_t *H = hashBuf; + uint32_t *W = inBuf; + + //for (int t = 0; t < 16 ; t++) + // printf("%2d %08lx\n", t, W[t]); + + //see 6.2.2 + for (int t = 16; t < 64 ; t++) + W[t] = TR32(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); + + uint32_t a = H[0]; + uint32_t b = H[1]; + uint32_t c = H[2]; + uint32_t d = H[3]; + uint32_t e = H[4]; + uint32_t f = H[5]; + uint32_t g = H[6]; + uint32_t h = H[7]; + + for (int t = 0 ; t < 64 ; t++) + { + //see 4.1.1 for the boolops + uint32_t T1 = TR32(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + + sha256table[t] + W[t]); + uint32_t T2 = TR32(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); + h = g; g = f; f = e; e = TR32(d + T1); d = c; c = b; b = a; a = TR32(T1 + T2); + //printf("%2d %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n", + // t, a, b, c, d, e, f, g, h); + } + + H[0] = TR32(H[0] + a); + H[1] = TR32(H[1] + b); + H[2] = TR32(H[2] + c); + H[3] = TR32(H[3] + d); + H[4] = TR32(H[4] + e); + H[5] = TR32(H[5] + f); + H[6] = TR32(H[6] + g); + H[7] = TR32(H[7] + h); +} + + + +/** + * + */ +std::vector Sha256::finish() +{ + //save our size before padding + getBitCount(); + + // Pad with a binary 1 (0x80) + update(0x80); + //append 0's to make a 56-byte buf. + while ((nrBytes & 63) != 56) + update(0); + + //##### Append length in bits + appendBitCount(); + + // Output hash + std::vector ret; + for (int i = 0 ; i < 8 ; i++) + { + ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + } + + // Re-initialize the context (also zeroizes contents) + reset(); + + return ret; + +} + + + +//######################################################################## +//## SHA384 +//######################################################################## + + +/** + * SHA-384 and SHA-512 share the same operations and constants + */ + +#undef SHA_SIGMA0 +#undef SHA_SIGMA1 +#undef SHA_sigma0 +#undef SHA_sigma1 + +#define SHA_Rot64(x,s) (((x) >> s) | ((x) << (64 - s))) +#define SHA_SIGMA0(x) (SHA_Rot64(x, 28) ^ SHA_Rot64(x, 34) ^ SHA_Rot64(x, 39)) +#define SHA_SIGMA1(x) (SHA_Rot64(x, 14) ^ SHA_Rot64(x, 18) ^ SHA_Rot64(x, 41)) +#define SHA_sigma0(x) (SHA_Rot64(x, 1) ^ SHA_Rot64(x, 8) ^ ((x) >> 7)) +#define SHA_sigma1(x) (SHA_Rot64(x, 19) ^ SHA_Rot64(x, 61) ^ ((x) >> 6)) + + +static uint64_t sha512table[80] = +{ + 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, + 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, + 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, + 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, + 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, + 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, + 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, + 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, + 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, + 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, + 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, + 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, + 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, + 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, + 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, + 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, + 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, + 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, + 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, + 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, + 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, + 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, + 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, + 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, + 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, + 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, + 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, + 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, + 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, + 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, + 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, + 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, + 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, + 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, + 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, + 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, + 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, + 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, + 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, + 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL +}; + + + + +/** + * + */ +void Sha384::reset() +{ + longNr = 0; + byteNr = 0; + + // SHA-384 differs from SHA-512 by these constants + hashBuf[0] = 0xcbbb9d5dc1059ed8ULL; + hashBuf[1] = 0x629a292a367cd507ULL; + hashBuf[2] = 0x9159015a3070dd17ULL; + hashBuf[3] = 0x152fecd8f70e5939ULL; + hashBuf[4] = 0x67332667ffc00b31ULL; + hashBuf[5] = 0x8eb44a8768581511ULL; + hashBuf[6] = 0xdb0c2e0d64f98fa7ULL; + hashBuf[7] = 0x47b5481dbefa4fa4ULL; + + for (int i = 0 ; i < 80 ; i++) + inBuf[i] = 0; + for (int i = 0 ; i < 8 ; i++) + inb[i] = 0; + + clearByteCount(); +} + + +/** + * Note that this version of update() handles 64-bit inBuf + * values. + */ +void Sha384::update(unsigned char ch) +{ + incByteCount(); + + inb[byteNr++] = (uint64_t)ch; + if (byteNr >= 8) + { + inBuf[longNr++] = inb[0] << 56 | inb[1] << 48 | + inb[2] << 40 | inb[3] << 32 | + inb[4] << 24 | inb[5] << 16 | + inb[6] << 8 | inb[7]; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + + + +void Sha384::transform() +{ + uint64_t *H = hashBuf; + uint64_t *W = inBuf; + + /* + for (int t = 0; t < 16 ; t++) + { + printf("%2d ", t); + pl(W[t]); + printf("\n"); + } + */ + + //see 6.2.2 + for (int t = 16; t < 80 ; t++) + W[t] = TR64(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); + + uint64_t a = H[0]; + uint64_t b = H[1]; + uint64_t c = H[2]; + uint64_t d = H[3]; + uint64_t e = H[4]; + uint64_t f = H[5]; + uint64_t g = H[6]; + uint64_t h = H[7]; + + for (int t = 0 ; t < 80 ; t++) + { + //see 4.1.1 for the boolops + uint64_t T1 = TR64(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + + sha512table[t] + W[t]); + uint64_t T2 = TR64(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); + h = g; g = f; f = e; e = TR64(d + T1); d = c; c = b; b = a; a = TR64(T1 + T2); + } + + H[0] = TR64(H[0] + a); + H[1] = TR64(H[1] + b); + H[2] = TR64(H[2] + c); + H[3] = TR64(H[3] + d); + H[4] = TR64(H[4] + e); + H[5] = TR64(H[5] + f); + H[6] = TR64(H[6] + g); + H[7] = TR64(H[7] + h); +} + + + +/** + * + */ +std::vector Sha384::finish() +{ + //save our size before padding + getBitCount(); + + // Pad with a binary 1 (0x80) + update((unsigned char)0x80); + //append 0's to make a 112-byte buf. + //we will loop around once if already over 112 + while ((nrBytes & 127) != 112) + update(0); + + //append 128-bit size + //64 upper bits + for (int i = 0 ; i < 8 ; i++) + update((unsigned char)0x00); + //64 lower bits + //##### Append length in bits + appendBitCount(); + + // Output hash + //for SHA-384, we use the left-most 6 64-bit words + std::vector ret; + for (int i = 0 ; i < 6 ; i++) + { + ret.push_back((unsigned char)((hashBuf[i] >> 56) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 48) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 40) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 32) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + } + + // Re-initialize the context (also zeroizes contents) + reset(); + + return ret; + +} + + +//######################################################################## +//## SHA512 +//######################################################################## + + + + + +/** + * + */ +void Sha512::reset() +{ + longNr = 0; + byteNr = 0; + + // Initialize H with the magic constants (see FIPS180 for constants) + hashBuf[0] = 0x6a09e667f3bcc908ULL; + hashBuf[1] = 0xbb67ae8584caa73bULL; + hashBuf[2] = 0x3c6ef372fe94f82bULL; + hashBuf[3] = 0xa54ff53a5f1d36f1ULL; + hashBuf[4] = 0x510e527fade682d1ULL; + hashBuf[5] = 0x9b05688c2b3e6c1fULL; + hashBuf[6] = 0x1f83d9abfb41bd6bULL; + hashBuf[7] = 0x5be0cd19137e2179ULL; + + for (int i = 0 ; i < 80 ; i++) + inBuf[i] = 0; + for (int i = 0 ; i < 8 ; i++) + inb[i] = 0; + + clearByteCount(); +} + + +/** + * Note that this version of update() handles 64-bit inBuf + * values. + */ +void Sha512::update(unsigned char ch) +{ + incByteCount(); + + inb[byteNr++] = (uint64_t)ch; + if (byteNr >= 8) + { + inBuf[longNr++] = inb[0] << 56 | inb[1] << 48 | + inb[2] << 40 | inb[3] << 32 | + inb[4] << 24 | inb[5] << 16 | + inb[6] << 8 | inb[7]; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + + + +void Sha512::transform() +{ + uint64_t *W = inBuf; + uint64_t *H = hashBuf; + + /* + for (int t = 0; t < 16 ; t++) + { + printf("%2d ", t); + pl(W[t]); + printf("\n"); + } + */ + + //see 6.2.2 + for (int t = 16; t < 80 ; t++) + W[t] = TR64(SHA_sigma1(W[t-2]) + W[t-7] + SHA_sigma0(W[t-15]) + W[t-16]); + + uint64_t a = H[0]; + uint64_t b = H[1]; + uint64_t c = H[2]; + uint64_t d = H[3]; + uint64_t e = H[4]; + uint64_t f = H[5]; + uint64_t g = H[6]; + uint64_t h = H[7]; + + for (int t = 0 ; t < 80 ; t++) + { + //see 4.1.1 for the boolops + uint64_t T1 = TR64(h + SHA_SIGMA1(e) + SHA_Ch(e,f,g) + + sha512table[t] + W[t]); + uint64_t T2 = TR64(SHA_SIGMA0(a) + SHA_Maj(a,b,c)); + h = g; g = f; f = e; e = TR64(d + T1); d = c; c = b; b = a; a = TR64(T1 + T2); + } + + H[0] = TR64(H[0] + a); + H[1] = TR64(H[1] + b); + H[2] = TR64(H[2] + c); + H[3] = TR64(H[3] + d); + H[4] = TR64(H[4] + e); + H[5] = TR64(H[5] + f); + H[6] = TR64(H[6] + g); + H[7] = TR64(H[7] + h); +} + + + +/** + * + */ +std::vector Sha512::finish() +{ + //save our size before padding + getBitCount(); + + // Pad with a binary 1 (0x80) + update(0x80); + //append 0's to make a 112-byte buf. + //we will loop around once if already over 112 + while ((nrBytes & 127) != 112) + update(0); + + //append 128-bit size + //64 upper bits + for (int i = 0 ; i < 8 ; i++) + update((unsigned char)0x00); + //64 lower bits + //##### Append length in bits + appendBitCount(); + + // Output hash + std::vector ret; + for (int i = 0 ; i < 8 ; i++) + { + ret.push_back((unsigned char)((hashBuf[i] >> 56) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 48) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 40) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 32) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + ret.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + } + + // Re-initialize the context (also zeroizes contents) + reset(); + + return ret; + +} + + + +//######################################################################## +//## M D 5 +//######################################################################## + +/** + * + */ +void Md5::reset() +{ + hashBuf[0] = 0x67452301; + hashBuf[1] = 0xefcdab89; + hashBuf[2] = 0x98badcfe; + hashBuf[3] = 0x10325476; + + for (int i=0 ; i<16 ; i++) + inBuf[i] = 0; + for (int i=0 ; i<4 ; i++) + inb[i] = 0; + + clearByteCount(); + + byteNr = 0; + longNr = 0; +} + + +/** + * + */ +void Md5::update(unsigned char ch) +{ + incByteCount(); + + //pack 64 bytes into 16 longs + inb[byteNr++] = (uint32_t)ch; + if (byteNr >= 4) + { + //note the little-endianness + uint32_t val = + inb[3] << 24 | inb[2] << 16 | inb[1] << 8 | inb[0]; + inBuf[longNr++] = val; + byteNr = 0; + } + if (longNr >= 16) + { + transform(); + longNr = 0; + } +} + + + +//# The four core functions - F1 is optimized somewhat + +// #define F1(x, y, z) (x & y | ~x & z) +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +// ## This is the central step in the MD5 algorithm. +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w = TR32(w + (f(x, y, z) + data)), w = w<>(32-s), w = TR32(w + x) ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + * @parm buf points to an array of 4 unsigned 32bit (at least) integers + * @parm in points to an array of 16 unsigned 32bit (at least) integers + */ +void Md5::transform() +{ + uint32_t *i = inBuf; + uint32_t a = hashBuf[0]; + uint32_t b = hashBuf[1]; + uint32_t c = hashBuf[2]; + uint32_t d = hashBuf[3]; + + MD5STEP(F1, a, b, c, d, i[ 0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, i[ 1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, i[ 2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, i[ 3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, i[ 4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, i[ 5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, i[ 6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, i[ 7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, i[ 8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, i[ 9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, i[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, i[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, i[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, i[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, i[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, i[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, i[ 1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, i[ 6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, i[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, i[ 0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, i[ 5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, i[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, i[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, i[ 4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, i[ 9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, i[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, i[ 3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, i[ 8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, i[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, i[ 2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, i[ 7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, i[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, i[ 5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, i[ 8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, i[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, i[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, i[ 1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, i[ 4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, i[ 7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, i[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, i[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, i[ 0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, i[ 3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, i[ 6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, i[ 9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, i[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, i[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, i[ 2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, i[ 0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, i[ 7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, i[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, i[ 5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, i[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, i[ 3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, i[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, i[ 1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, i[ 8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, i[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, i[ 6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, i[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, i[ 4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, i[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, i[ 2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, i[ 9] + 0xeb86d391, 21); + + hashBuf[0] = TR32(hashBuf[0] + a); + hashBuf[1] = TR32(hashBuf[1] + b); + hashBuf[2] = TR32(hashBuf[2] + c); + hashBuf[3] = TR32(hashBuf[3] + d); +} + + +/** + * + */ +std::vector Md5::finish() +{ + //snapshot the bit count now before padding + getBitCount(); + + //Append terminal char + update(0x80); + + //pad until we have a 56 of 64 bytes, allowing for 8 bytes at the end + while (longNr != 14) + update(0); + + //##### Append length in bits + // Don't use appendBitCount(), since md5 is little-endian + update((unsigned char)((nrBits ) & 0xff)); + update((unsigned char)((nrBits>> 8) & 0xff)); + update((unsigned char)((nrBits>>16) & 0xff)); + update((unsigned char)((nrBits>>24) & 0xff)); + update((unsigned char)((nrBits>>32) & 0xff)); + update((unsigned char)((nrBits>>40) & 0xff)); + update((unsigned char)((nrBits>>48) & 0xff)); + update((unsigned char)((nrBits>>56) & 0xff)); + + //copy out answer + std::vector res; + for (int i=0 ; i<4 ; i++) + { + //note the little-endianness + res.push_back((unsigned char)((hashBuf[i] ) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] >> 8) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] >> 16) & 0xff)); + res.push_back((unsigned char)((hashBuf[i] >> 24) & 0xff)); + } + + reset(); // Security! ;-) + + return res; +} + + + + + + +//######################################################################## +//## T E S T S +//######################################################################## + +/** + * Compile this file alone with -DDIGEST_TEST to run the + * tests below: + * > gcc -DDIGEST_TEST digest.cpp -o testdigest + * > testdigest + * + * If you add any new algorithms to this suite, then it is highly + * recommended that you add it to these tests and run it. + */ + +#ifdef DIGEST_TEST + + +typedef struct +{ + const char *msg; + const char *val; +} TestPair; + +static TestPair md5tests[] = +{ + { + "", + "d41d8cd98f00b204e9800998ecf8427e" + }, + { + "a", + "0cc175b9c0f1b6a831c399e269772661" + }, + { + "abc", + "900150983cd24fb0d6963f7d28e17f72" + }, + { + "message digest", + "f96b697d7cb7938d525a2f31aaf161d0" + }, + { + "abcdefghijklmnopqrstuvwxyz", + "c3fcd3d76192e4007dfb496cca67e13b" + }, + { + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "d174ab98d277d9f5a5611c2c9f419d9f" + }, + { + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "57edf4a22be3c955ac49da2e2107b67a" + }, + { + NULL, + NULL + } +}; + + + +static TestPair sha1tests[] = +{ + { + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "84983e441c3bd26ebaae4aa1f95129e5e54670f1" + }, + { + NULL, + NULL + } +}; + +static TestPair sha224tests[] = +{ + { + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525" + }, + { + NULL, + NULL + } +}; + +static TestPair sha256tests[] = +{ + { + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + }, + { + NULL, + NULL + } +}; + +static TestPair sha384tests[] = +{ + { + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712" + "fcc7c71a557e2db966c3e9fa91746039" + }, + { + NULL, + NULL + } +}; + +static TestPair sha512tests[] = +{ + { + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" + "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909" + }, + { + NULL, + NULL + } +}; + + +bool hashTests(Digest &digest, TestPair *tp) +{ + for (TestPair *pair = tp ; pair->msg ; pair++) + { + digest.reset(); + std::string msg = pair->msg; + std::string val = pair->val; + digest.append(msg); + std::string res = digest.finishHex(); + printf("### Msg '%s':\n hash '%s'\n exp '%s'\n", + msg.c_str(), res.c_str(), val.c_str()); + if (res != val) + { + printf("ERROR: Hash mismatch\n"); + return false; + } + } + return true; +} + + +bool millionATest(Digest &digest, const std::string &exp) +{ + digest.reset(); + for (int i=0 ; i<1000000 ; i++) + digest.append('a'); + std::string res = digest.finishHex(); + printf("\nHash of 1,000,000 'a'\n calc %s\n exp %s\n", + res.c_str(), exp.c_str()); + if (res != exp) + { + printf("ERROR: Mismatch.\n"); + return false; + } + return true; +} + +static bool doTests() +{ + printf("##########################################\n"); + printf("## MD5\n"); + printf("##########################################\n"); + Md5 md5; + if (!hashTests(md5, md5tests)) + return false; + if (!millionATest(md5, "7707d6ae4e027c70eea2a935c2296f21")) + return false; + printf("\n\n\n"); + printf("##########################################\n"); + printf("## SHA1\n"); + printf("##########################################\n"); + Sha1 sha1; + if (!hashTests(sha1, sha1tests)) + return false; + if (!millionATest(sha1, "34aa973cd4c4daa4f61eeb2bdbad27316534016f")) + return false; + printf("\n\n\n"); + printf("##########################################\n"); + printf("## SHA224\n"); + printf("##########################################\n"); + Sha224 sha224; + if (!hashTests(sha224, sha224tests)) + return false; + if (!millionATest(sha224, + "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")) + return false; + printf("\n\n\n"); + printf("##########################################\n"); + printf("## SHA256\n"); + printf("##########################################\n"); + Sha256 sha256; + if (!hashTests(sha256, sha256tests)) + return false; + if (!millionATest(sha256, + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")) + return false; + printf("\n\n\n"); + printf("##########################################\n"); + printf("## SHA384\n"); + printf("##########################################\n"); + Sha384 sha384; + if (!hashTests(sha384, sha384tests)) + return false; + /**/ + if (!millionATest(sha384, + "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b" + "07b8b3dc38ecc4ebae97ddd87f3d8985")) + return false; + /**/ + printf("\n\n\n"); + printf("##########################################\n"); + printf("## SHA512\n"); + printf("##########################################\n"); + Sha512 sha512; + if (!hashTests(sha512, sha512tests)) + return false; + if (!millionATest(sha512, + "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" + "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")) + return false; + return true; +} + + +int main(int argc, char **argv) +{ + doTests(); + printf("####### done ########\n"); + return 0; +} + + +#endif /* DIGEST_TEST */ + +//######################################################################## +//## E N D O F F I L E +//######################################################################## diff --git a/src/dom/util/digest.h b/src/dom/util/digest.h new file mode 100644 index 000000000..c161b86bb --- /dev/null +++ b/src/dom/util/digest.h @@ -0,0 +1,654 @@ +#ifndef SEEN_DIGEST_H +#define SEEN_DIGEST_H +/* + * + * Author: + * Bob Jamison + * + * Copyright (C) 2006-2008 Bob Jamison + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * This base class and its subclasses provide an easy API for providing + * several different types of secure hashing functions for whatever use + * a developer might need. This is not intended as a high-performance + * replacement for the fine implementations already available. Rather, it + * is a small and simple (and maybe a bit slow?) tool for moderate common + * hashing requirements, like for communications and authentication. + * + * These hashes are intended to be simple to use. For example: + * Sha256 digest; + * digest.append("The quick brown dog"); + * std::string result = digest.finishHex(); + * + * Or, use one of the static convenience methods: + * + * example: std::string digest = + * Digest::hashHex(Digest::HASH_XXX, str); + * + * ...where HASH_XXX represents one of the hash + * algorithms listed in HashType. + * + * There are several forms of append() for convenience. + * finish() and finishHex() call reset() for both security and + * to prepare for the next use. + * + * + * Much effort has been applied to make this code portable, and it + * has been tested on various 32- and 64-bit machines. If you + * add another algorithm, please test it likewise. + * + * + * The SHA algorithms are derived directly from FIPS-180-3. The + * SHA tests at the bottom of digest.cpp are also directly from + * that document. + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + * + * The MD5 algorithm is from RFC 1321 + * + * To run the tests, compile standalone with -DDIGEST_TEST. Example: + * + * g++ -DDIGEST_TEST digest.cpp -o testdigest + * or + * g++ -DDIGEST_TEST -m64 digest.cpp -o testdigest + * + */ + +#include +#include + +#include + + + +/** + * Base class. Do not use instantiate class directly. Rather, use of of the + * subclasses below, or call one of this class's static convenience methods. + * + * For all subclasses, overload reset(), update(unsigned char), + * transform(), and finish() + */ +class Digest +{ +public: + + /** + * Different types of hash algorithms. + */ + typedef enum + { + HASH_NONE, + HASH_SHA1, + HASH_SHA224, + HASH_SHA256, + HASH_SHA384, + HASH_SHA512, + HASH_MD5 + } HashType; + + /** + * Constructor, with no type + */ + Digest() : hashType(HASH_NONE) + { reset(); } + + /** + * Destructor + */ + virtual ~Digest() + { reset(); } + + /** + * Return one of the enumerated hash types above + */ + virtual int getType() + { return hashType; } + + /** + * Append a single byte to the hash + */ + void append(unsigned char ch) + { update(ch); } + + /** + * Append a string to the hash + */ + virtual void append(const std::string &str) + { + for (unsigned int i=0 ; i &buf) + { //NOTE: function seems to be unused + for (unsigned int i=0 ; i finish() + { + std::vector ret; + return ret; + } + + + //######################## + //# Convenience methods + //######################## + + /** + * Convenience method. This is a simple way of getting a hash. + * Returns a byte buffer with the digest output. + * call with: std::vector digest = + * Digest::hash(Digest::HASH_XXX, buf, len); + */ + static std::vector hash(HashType typ, + unsigned char *buf, + int len); + /** + * Convenience method. This is a simple way of getting a hash. + * Returns a byte buffer with the digest output. + * call with: std::vector digest = + * Digest::hash(Digest::HASH_XXX, str); + */ + static std::vector hash(HashType typ, + const std::string &str); + + /** + * Convenience method. This is a simple way of getting a hash. + * Returns a string with the hexidecimal form of the digest output. + * call with: std::string digest = + * Digest::hash(Digest::HASH_XXX, buf, len); + */ + static std::string hashHex(HashType typ, + unsigned char *buf, + int len); + /** + * Convenience method. This is a simple way of getting a hash. + * Returns a string with the hexidecimal form of the digest output. + * call with: std::string digest = + * Digest::hash(Digest::HASH_XXX, str); + */ + static std::string hashHex(HashType typ, + const std::string &str); + +protected: + + /** + * Update the hash with a given byte + * Overload this in every subclass + */ + virtual void update(unsigned char /*ch*/) + {} + + /** + * Perform the particular block hashing algorithm for a + * particular type of hash. + * Overload this in every subclass + */ + virtual void transform() + {} + + + /** + * The enumerated type of the hash + */ + int hashType; + + /** + * Increment the count of bytes processed so far. Should be called + * in update() + */ + void incByteCount() + { + nrBytes++; + } + + /** + * Clear the byte / bit count information. Both for processing + * another message, also for security. Should be called in reset() + */ + void clearByteCount() + { + nrBytes = nrBits = 0; + } + + /** + * Calculates the bit count from the current byte count. Should be called + * in finish(), before any padding is added. This basically does a + * snapshot of the bitcount value before the padding. + */ + void getBitCount() + { + nrBits = (nrBytes << 3) & 0xFFFFFFFFFFFFFFFFLL; + } + + /** + * Common code for appending the 64-bit bitcount to the end of the + * message, after the padding. Should be called after padding, just + * before outputting the result. + */ + void appendBitCount() + { + update((unsigned char)((nrBits>>56) & 0xff)); + update((unsigned char)((nrBits>>48) & 0xff)); + update((unsigned char)((nrBits>>40) & 0xff)); + update((unsigned char)((nrBits>>32) & 0xff)); + update((unsigned char)((nrBits>>24) & 0xff)); + update((unsigned char)((nrBits>>16) & 0xff)); + update((unsigned char)((nrBits>> 8) & 0xff)); + update((unsigned char)((nrBits ) & 0xff)); + } + + /** + * Bit and byte counts + */ + uint64_t nrBytes; + uint64_t nrBits; +}; + + + + + +/** + * SHA-1, + * Section 6.1, SECURE HASH STANDARD + * Federal Information Processing Standards Publication 180-2 + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + */ +class Sha1 : public Digest +{ +public: + + /** + * Constructor + */ + Sha1() + { hashType = HASH_SHA1; reset(); } + + /** + * Destructor + */ + virtual ~Sha1() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + +private: + + uint32_t hashBuf[5]; + uint32_t inBuf[80]; + + int longNr; + int byteNr; + uint32_t inb[4]; + +}; + + + + + + +/** + * SHA-224, + * Section 6.1, SECURE HASH STANDARD + * Federal Information Processing Standards Publication 180-2 + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + */ +class Sha224 : public Digest +{ +public: + + /** + * Constructor + */ + Sha224() + { hashType = HASH_SHA224; reset(); } + + /** + * Destructor + */ + virtual ~Sha224() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + +private: + + uint32_t hashBuf[8]; + uint32_t inBuf[64]; + int longNr; + int byteNr; + uint32_t inb[4]; + +}; + + + +/** + * SHA-256, + * Section 6.1, SECURE HASH STANDARD + * Federal Information Processing Standards Publication 180-2 + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + */ +class Sha256 : public Digest +{ +public: + + /** + * Constructor + */ + Sha256() + { hashType = HASH_SHA256; reset(); } + + /** + * Destructor + */ + virtual ~Sha256() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + +private: + + uint32_t hashBuf[8]; + uint32_t inBuf[64]; + int longNr; + int byteNr; + uint32_t inb[4]; + +}; + + + +/** + * SHA-384, + * Section 6.1, SECURE HASH STANDARD + * Federal Information Processing Standards Publication 180-2 + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + */ +class Sha384 : public Digest +{ +public: + + /** + * Constructor + */ + Sha384() + { hashType = HASH_SHA384; reset(); } + + /** + * Destructor + */ + virtual ~Sha384() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + + + +private: + + uint64_t hashBuf[8]; + uint64_t inBuf[80]; + int longNr; + int byteNr; + uint64_t inb[8]; + +}; + + + + +/** + * SHA-512, + * Section 6.1, SECURE HASH STANDARD + * Federal Information Processing Standards Publication 180-2 + * http://csrc.nist.gov/publications/drafts/fips_180-3/draft_fips-180-3_June-08-2007.pdf + */ +class Sha512 : public Digest +{ +public: + + /** + * Constructor + */ + Sha512() + { hashType = HASH_SHA512; reset(); } + + /** + * Destructor + */ + virtual ~Sha512() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + +private: + + uint64_t hashBuf[8]; + uint64_t inBuf[80]; + int longNr; + int byteNr; + uint64_t inb[8]; + +}; + + + + + + + + + +/** + * IETF RFC 1321, MD5 Specification + * http://www.ietf.org/rfc/rfc1321.txt + */ +class Md5 : public Digest +{ +public: + + /** + * Constructor + */ + Md5() + { hashType = HASH_MD5; reset(); } + + /** + * Destructor + */ + virtual ~Md5() + { reset(); } + + /** + * Overloaded from Digest + */ + virtual void reset(); + + /** + * Overloaded from Digest + */ + virtual std::vector finish(); + +protected: + + /** + * Overloaded from Digest + */ + virtual void update(unsigned char val); + + /** + * Overloaded from Digest + */ + virtual void transform(); + +private: + + uint32_t hashBuf[4]; + uint32_t inBuf[16]; + + uint32_t inb[4]; // Buffer for input bytes as longs + int byteNr; // which byte in long + int longNr; // which long in 16-long buffer + +}; + + + + + + + + + +#endif /* __DIGEST_H__ */ + + diff --git a/src/dom/util/ziptool.cpp b/src/dom/util/ziptool.cpp new file mode 100644 index 000000000..9d9d5685c --- /dev/null +++ b/src/dom/util/ziptool.cpp @@ -0,0 +1,3025 @@ +/* + * This is intended to be a standalone, reduced capability + * implementation of Gzip and Zip functionality. Its + * targeted use case is for archiving and retrieving single files + * which use these encoding types. Being memory based and + * non-optimized, it is not useful in cases where very large + * archives are needed or where high performance is desired. + * However, it should hopefully work very well for smaller, + * one-at-a-time tasks. What you get in return is the ability + * to drop these files into your project and remove the dependencies + * on ZLib and Info-Zip. Enjoy. + * + * Authors: + * Bob Jamison + * + * Copyright (C) 2006-2007 Bob Jamison + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +#include +#include +#include + +#include + +#include "ziptool.h" + + + + + + +//######################################################################## +//# A D L E R 3 2 +//######################################################################## + +/** + * Constructor + */ +Adler32::Adler32() +{ + reset(); +} + +/** + * Destructor + */ +Adler32::~Adler32() +{ +} + +/** + * Reset Adler-32 checksum to initial value. + */ +void Adler32::reset() +{ + value = 1; +} + +// ADLER32_BASE is the largest prime number smaller than 65536 +#define ADLER32_BASE 65521 + +void Adler32::update(unsigned char b) +{ + unsigned long s1 = value & 0xffff; + unsigned long s2 = (value >> 16) & 0xffff; + s1 += b & 0xff; + s2 += s1; + value = ((s2 % ADLER32_BASE) << 16) | (s1 % ADLER32_BASE); +} + +void Adler32::update(char *str) +{ + if (str) + while (*str) + update((unsigned char)*str++); +} + + +/** + * Returns current checksum value. + */ +unsigned long Adler32::getValue() +{ + return value & 0xffffffffL; +} + + + +//######################################################################## +//# C R C 3 2 +//######################################################################## + +/** + * Constructor + */ +Crc32::Crc32() +{ + reset(); +} + +/** + * Destructor + */ +Crc32::~Crc32() +{ +} + +static bool crc_table_ready = false; +static unsigned long crc_table[256]; + +/** + * make the table for a fast CRC. + */ +static void makeCrcTable() +{ + if (crc_table_ready) + return; + for (int n = 0; n < 256; n++) + { + unsigned long c = n; + for (int k = 8; --k >= 0; ) + { + if ((c & 1) != 0) + c = 0xedb88320 ^ (c >> 1); + else + c >>= 1; + } + crc_table[n] = c; + } + crc_table_ready = true; +} + + +/** + * Reset CRC-32 checksum to initial value. + */ +void Crc32::reset() +{ + value = 0; + makeCrcTable(); +} + +void Crc32::update(unsigned char b) +{ + unsigned long c = ~value; + + c &= 0xffffffff; + c = crc_table[(c ^ b) & 0xff] ^ (c >> 8); + value = ~c; +} + + +void Crc32::update(char *str) +{ + if (str) + while (*str) + update((unsigned char)*str++); +} + +void Crc32::update(const std::vector &buf) +{ + std::vector::const_iterator iter; + for (iter=buf.begin() ; iter!=buf.end() ; ++iter) + { + unsigned char ch = *iter; + update(ch); + } +} + + +/** + * Returns current checksum value. + */ +unsigned long Crc32::getValue() +{ + return value & 0xffffffffL; +} + +//######################################################################## +//# I N F L A T E R +//######################################################################## + + +/** + * + */ +typedef struct +{ + int *count; // number of symbols of each length + int *symbol; // canonically ordered symbols +} Huffman; + +/** + * + */ +class Inflater +{ +public: + + Inflater(); + + virtual ~Inflater(); + + static const int MAXBITS = 15; // max bits in a code + static const int MAXLCODES = 286; // max number of literal/length codes + static const int MAXDCODES = 30; // max number of distance codes + static const int MAXCODES = 316; // max codes lengths to read + static const int FIXLCODES = 288; // number of fixed literal/length codes + + /** + * + */ + bool inflate(std::vector &destination, + std::vector &source); + +private: + + /** + * + */ + void error(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + /** + * + */ + void trace(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + /** + * + */ + void dump(); + + /** + * + */ + int buildHuffman(Huffman *h, int *length, int n); + + /** + * + */ + bool getBits(int need, int *oval); + + /** + * + */ + int doDecode(Huffman *h); + + /** + * + */ + bool doCodes(Huffman *lencode, Huffman *distcode); + + /** + * + */ + bool doStored(); + + /** + * + */ + bool doFixed(); + + /** + * + */ + bool doDynamic(); + + + std::vectordest; + + std::vectorsrc; + unsigned long srcPos; //current read position + int bitBuf; + int bitCnt; + +}; + + +/** + * + */ +Inflater::Inflater() : + dest(), + src(), + srcPos(0), + bitBuf(0), + bitCnt(0) +{ +} + +/** + * + */ +Inflater::~Inflater() +{ +} + +/** + * + */ +void Inflater::error(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "Inflater error:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +/** + * + */ +void Inflater::trace(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "Inflater:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + + +/** + * + */ +void Inflater::dump() +{ + for (unsigned int i=0 ; icount[len] = 0; + for (int symbol = 0; symbol < n; symbol++) + (h->count[length[symbol]])++; // assumes lengths are within bounds + if (h->count[0] == n) // no codes! + { + error("huffman tree will result in failed decode"); + return -1; + } + + // check for an over-subscribed or incomplete set of lengths + int left = 1; // number of possible codes left of current length + for (int len = 1; len <= MAXBITS; len++) + { + left <<= 1; // one more bit, double codes left + left -= h->count[len]; // deduct count from possible codes + if (left < 0) + { + error("huffman over subscribed"); + return -1; + } + } + + // generate offsets into symbol table for each length for sorting + int offs[MAXBITS+1]; //offsets in symbol table for each length + offs[1] = 0; + for (int len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + h->count[len]; + + /* + * put symbols in table sorted by length, by symbol order within each + * length + */ + for (int symbol = 0; symbol < n; symbol++) + if (length[symbol] != 0) + h->symbol[offs[length[symbol]]++] = symbol; + + // return zero for complete set, positive for incomplete set + return left; +} + + +/** + * + */ +bool Inflater::getBits(int requiredBits, int *oval) +{ + long val = bitBuf; + + //add more bytes if needed + while (bitCnt < requiredBits) + { + if (srcPos >= src.size()) + { + error("premature end of input"); + return false; + } + val |= ((long)(src[srcPos++])) << bitCnt; + bitCnt += 8; + } + + //update the buffer and return the data + bitBuf = (int)(val >> requiredBits); + bitCnt -= requiredBits; + *oval = (int)(val & ((1L << requiredBits) - 1)); + + return true; +} + + +/** + * + */ +int Inflater::doDecode(Huffman *h) +{ + int bitTmp = bitBuf; + int left = bitCnt; + int code = 0; + int first = 0; + int index = 0; + int len = 1; + int *next = h->count + 1; + while (true) + { + while (left--) + { + code |= bitTmp & 1; + bitTmp >>= 1; + int count = *next++; + if (code < first + count) + { /* if length len, return symbol */ + bitBuf = bitTmp; + bitCnt = (bitCnt - len) & 7; + return h->symbol[index + (code - first)]; + } + index += count; + first += count; + first <<= 1; + code <<= 1; + len++; + } + left = (MAXBITS+1) - len; + if (left == 0) + break; + if (srcPos >= src.size()) + { + error("premature end of input"); + dump(); + return -1; + } + bitTmp = src[srcPos++]; + if (left > 8) + left = 8; + } + + error("no end of block found"); + return -1; +} + +/** + * + */ +bool Inflater::doCodes(Huffman *lencode, Huffman *distcode) +{ + static const int lens[29] = { // Size base for length codes 257..285 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static const int lext[29] = { // Extra bits for length codes 257..285 + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static const int dists[30] = { // Offset base for distance codes 0..29 + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577}; + static const int dext[30] = { // Extra bits for distance codes 0..29 + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13}; + + //decode literals and length/distance pairs + while (true) + { + int symbol = doDecode(lencode); + if (symbol == 256) + break; + if (symbol < 0) + { + return false; + } + if (symbol < 256) //literal + { + dest.push_back(symbol); + } + else if (symbol > 256)//length + { + symbol -= 257; + if (symbol >= 29) + { + error("invalid fixed code"); + return false; + } + int ret; + if (!getBits(lext[symbol], &ret)) + return false; + int len = lens[symbol] + ret; + + symbol = doDecode(distcode);//distance + if (symbol < 0) + { + return false; + } + + if (!getBits(dext[symbol], &ret)) + return false; + unsigned int dist = dists[symbol] + ret; + if (dist > dest.size()) + { + error("distance too far back %d/%d", dist, dest.size()); + dump(); + //printf("pos:%d\n", srcPos); + return false; + } + + // copy length bytes from distance bytes back + //dest.push_back('{'); + while (len--) + { + dest.push_back(dest[dest.size() - dist]); + } + //dest.push_back('}'); + + } + } + + return true; +} + +/** + */ +bool Inflater::doStored() +{ + //trace("### stored ###"); + + // clear bits from current byte + bitBuf = 0; + bitCnt = 0; + + // length + if (srcPos + 4 > src.size()) + { + error("not enough input"); + return false; + } + + int len = src[srcPos++]; + len |= src[srcPos++] << 8; + //trace("### len:%d", len); + // check complement + if (src[srcPos++] != (~len & 0xff) || + src[srcPos++] != ((~len >> 8) & 0xff)) + { + error("twos complement for storage size do not match"); + return false; + } + + // copy data + if (srcPos + len > src.size()) + { + error("Not enough input for stored block"); + return false; + } + while (len--) + dest.push_back(src[srcPos++]); + + return true; +} + +/** + */ +bool Inflater::doFixed() +{ + //trace("### fixed ###"); + + static bool firstTime = true; + static int lencnt[MAXBITS+1], lensym[FIXLCODES]; + static int distcnt[MAXBITS+1], distsym[MAXDCODES]; + static Huffman lencode = {lencnt, lensym}; + static Huffman distcode = {distcnt, distsym}; + + if (firstTime) + { + firstTime = false; + + int lengths[FIXLCODES]; + + // literal/length table + int symbol = 0; + for ( ; symbol < 144; symbol++) + lengths[symbol] = 8; + for ( ; symbol < 256; symbol++) + lengths[symbol] = 9; + for ( ; symbol < 280; symbol++) + lengths[symbol] = 7; + for ( ; symbol < FIXLCODES; symbol++) + lengths[symbol] = 8; + buildHuffman(&lencode, lengths, FIXLCODES); + + // distance table + for (int symbol = 0; symbol < MAXDCODES; symbol++) + lengths[symbol] = 5; + buildHuffman(&distcode, lengths, MAXDCODES); + } + + // decode data until end-of-block code + bool ret = doCodes(&lencode, &distcode); + return ret; +} + +/** + */ +bool Inflater::doDynamic() +{ + //trace("### dynamic ###"); + int lengths[MAXCODES]; // descriptor code lengths + int lencnt[MAXBITS+1], lensym[MAXLCODES]; // lencode memory + int distcnt[MAXBITS+1], distsym[MAXDCODES]; // distcode memory + Huffman lencode = {lencnt, lensym}; // length code + Huffman distcode = {distcnt, distsym}; // distance code + static const int order[19] = // permutation of code length codes + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + // get number of lengths in each table, check lengths + int ret; + if (!getBits(5, &ret)) + return false; + int nlen = ret + 257; + if (!getBits(5, &ret)) + return false; + int ndist = ret + 1; + if (!getBits(4, &ret)) + return false; + int ncode = ret + 4; + if (nlen > MAXLCODES || ndist > MAXDCODES) + { + error("Bad codes"); + return false; + } + + // get code length code lengths + int index = 0; + for ( ; index < ncode; index++) + { + if (!getBits(3, &ret)) + return false; + lengths[order[index]] = ret; + } + for ( ; index < 19; index++) + lengths[order[index]] = 0; + + // build huffman table for code lengths codes + if (buildHuffman(&lencode, lengths, 19) != 0) + return false; + + // read length/literal and distance code length tables + index = 0; + while (index < nlen + ndist) + { + int symbol = doDecode(&lencode); + if (symbol < 16) // length in 0..15 + lengths[index++] = symbol; + else + { // repeat instruction + int len = 0; // assume repeating zeros + if (symbol == 16) + { // repeat last length 3..6 times + if (index == 0) + { + error("no last length"); + return false; + } + len = lengths[index - 1];// last length + if (!getBits(2, &ret)) + return false; + symbol = 3 + ret; + } + else if (symbol == 17) // repeat zero 3..10 times + { + if (!getBits(3, &ret)) + return false; + symbol = 3 + ret; + } + else // == 18, repeat zero 11..138 times + { + if (!getBits(7, &ret)) + return false; + symbol = 11 + ret; + } + if (index + symbol > nlen + ndist) + { + error("too many lengths"); + return false; + } + while (symbol--) // repeat last or zero symbol times + lengths[index++] = len; + } + } + + // build huffman table for literal/length codes + int err = buildHuffman(&lencode, lengths, nlen); + if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) + { + error("incomplete length codes"); + //return false; + } + // build huffman table for distance codes + err = buildHuffman(&distcode, lengths + nlen, ndist); + if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) + { + error("incomplete dist codes"); + return false; + } + + // decode data until end-of-block code + bool retn = doCodes(&lencode, &distcode); + return retn; +} + +/** + */ +bool Inflater::inflate(std::vector &destination, + std::vector &source) +{ + dest.clear(); + src = source; + srcPos = 0; + bitBuf = 0; + bitCnt = 0; + + while (true) + { + int last; // one if last block + if (!getBits(1, &last)) + return false; + int type; // block type 0..3 + if (!getBits(2, &type)) + return false; + switch (type) + { + case 0: + if (!doStored()) + return false; + break; + case 1: + if (!doFixed()) + return false; + break; + case 2: + if (!doDynamic()) + return false; + break; + default: + error("Unknown block type %d", type); + return false; + } + if (last) + break; + } + + destination = dest; + + return true; +} + + + + + + +//######################################################################## +//# D E F L A T E R +//######################################################################## + + +#define DEFLATER_BUF_SIZE 32768 +class Deflater +{ +public: + + /** + * + */ + Deflater(); + + /** + * + */ + virtual ~Deflater(); + + /** + * + */ + virtual void reset(); + + /** + * + */ + virtual bool update(int ch); + + /** + * + */ + virtual bool finish(); + + /** + * + */ + virtual std::vector &getCompressed(); + + /** + * + */ + bool deflate(std::vector &dest, + const std::vector &src); + + void encodeDistStatic(unsigned int len, unsigned int dist); + +private: + + //debug messages + void error(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + void trace(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + bool compressWindow(); + + bool compress(); + + std::vector compressed; + + std::vector uncompressed; + + std::vector window; + + unsigned int windowPos; + + //#### Output + unsigned int outputBitBuf; + unsigned int outputNrBits; + + void put(int ch); + + void putWord(int ch); + + void putFlush(); + + void putBits(unsigned int ch, unsigned int bitsWanted); + + void putBitsR(unsigned int ch, unsigned int bitsWanted); + + //#### Huffman Encode + void encodeLiteralStatic(unsigned int ch); + + unsigned char windowBuf[DEFLATER_BUF_SIZE]; + //assume 32-bit ints + unsigned int windowHashBuf[DEFLATER_BUF_SIZE]; +}; + + +//######################################################################## +//# A P I +//######################################################################## + + +/** + * + */ +Deflater::Deflater() +{ + reset(); +} + +/** + * + */ +Deflater::~Deflater() +{ + +} + +/** + * + */ +void Deflater::reset() +{ + compressed.clear(); + uncompressed.clear(); + window.clear(); + windowPos = 0; + outputBitBuf = 0; + outputNrBits = 0; + for (int k=0; k &Deflater::getCompressed() +{ + return compressed; +} + + +/** + * + */ +bool Deflater::deflate(std::vector &dest, + const std::vector &src) +{ + reset(); + uncompressed = src; + if (!compress()) + return false; + dest = compressed; + return true; +} + + + + + + + +//######################################################################## +//# W O R K I N G C O D E +//######################################################################## + + +//############################# +//# M E S S A G E S +//############################# + +/** + * Print error messages + */ +void Deflater::error(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "Deflater error:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +/** + * Print trace messages + */ +void Deflater::trace(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "Deflater:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + + + + +//############################# +//# O U T P U T +//############################# + +/** + * + */ +void Deflater::put(int ch) +{ + compressed.push_back(ch); + outputBitBuf = 0; + outputNrBits = 0; +} + +/** + * + */ +void Deflater::putWord(int ch) +{ + int lo = (ch ) & 0xff; + int hi = (ch>>8) & 0xff; + put(lo); + put(hi); +} + +/** + * + */ +void Deflater::putFlush() +{ + if (outputNrBits > 0) + { + put(outputBitBuf & 0xff); + } + outputBitBuf = 0; + outputNrBits = 0; +} + +/** + * + */ +void Deflater::putBits(unsigned int ch, unsigned int bitsWanted) +{ + //trace("n:%4u, %d\n", ch, bitsWanted); + + while (bitsWanted--) + { + //add bits to position 7. shift right + outputBitBuf = (outputBitBuf>>1) + (ch<<7 & 0x80); + ch >>= 1; + outputNrBits++; + if (outputNrBits >= 8) + { + unsigned char b = outputBitBuf & 0xff; + //printf("b:%02x\n", b); + put(b); + } + } +} + +static unsigned int bitReverse(unsigned int code, unsigned int nrBits) +{ + unsigned int outb = 0; + while (nrBits--) + { + outb = (outb << 1) | (code & 0x01); + code >>= 1; + } + return outb; +} + + +/** + * + */ +void Deflater::putBitsR(unsigned int ch, unsigned int bitsWanted) +{ + //trace("r:%4u, %d", ch, bitsWanted); + + unsigned int rcode = bitReverse(ch, bitsWanted); + + putBits(rcode, bitsWanted); + +} + + +//############################# +//# E N C O D E +//############################# + + + +void Deflater::encodeLiteralStatic(unsigned int ch) +{ + //trace("c: %d", ch); + + if (ch < 144) + { + putBitsR(ch + 0x0030 , 8); // 00110000 + } + else if (ch < 256) + { + putBitsR(ch - 144 + 0x0190 , 9); // 110010000 + } + else if (ch < 280) + { + putBitsR(ch - 256 + 0x0000 , 7); // 0000000 + } + else if (ch < 288) + { + putBitsR(ch - 280 + 0x00c0 , 8); // 11000000 + } + else //out of range + { + error("Literal out of range: %d", ch); + } + +} + + +typedef struct +{ + unsigned int base; + unsigned int range; + unsigned int bits; +} LenBase; + +LenBase lenBases[] = +{ + { 3, 1, 0 }, + { 4, 1, 0 }, + { 5, 1, 0 }, + { 6, 1, 0 }, + { 7, 1, 0 }, + { 8, 1, 0 }, + { 9, 1, 0 }, + { 10, 1, 0 }, + { 11, 2, 1 }, + { 13, 2, 1 }, + { 15, 2, 1 }, + { 17, 2, 1 }, + { 19, 4, 2 }, + { 23, 4, 2 }, + { 27, 4, 2 }, + { 31, 4, 2 }, + { 35, 8, 3 }, + { 43, 8, 3 }, + { 51, 8, 3 }, + { 59, 8, 3 }, + { 67, 16, 4 }, + { 83, 16, 4 }, + { 99, 16, 4 }, + { 115, 16, 4 }, + { 131, 32, 5 }, + { 163, 32, 5 }, + { 195, 32, 5 }, + { 227, 32, 5 }, + { 258, 1, 0 } +}; + +typedef struct +{ + unsigned int base; + unsigned int range; + unsigned int bits; +} DistBase; + +DistBase distBases[] = +{ + { 1, 1, 0 }, + { 2, 1, 0 }, + { 3, 1, 0 }, + { 4, 1, 0 }, + { 5, 2, 1 }, + { 7, 2, 1 }, + { 9, 4, 2 }, + { 13, 4, 2 }, + { 17, 8, 3 }, + { 25, 8, 3 }, + { 33, 16, 4 }, + { 49, 16, 4 }, + { 65, 32, 5 }, + { 97, 32, 5 }, + { 129, 64, 6 }, + { 193, 64, 6 }, + { 257, 128, 7 }, + { 385, 128, 7 }, + { 513, 256, 8 }, + { 769, 256, 8 }, + { 1025, 512, 9 }, + { 1537, 512, 9 }, + { 2049, 1024, 10 }, + { 3073, 1024, 10 }, + { 4097, 2048, 11 }, + { 6145, 2048, 11 }, + { 8193, 4096, 12 }, + { 12289, 4096, 12 }, + { 16385, 8192, 13 }, + { 24577, 8192, 13 } +}; + +void Deflater::encodeDistStatic(unsigned int len, unsigned int dist) +{ + + //## Output length + + if (len < 3 || len > 258) + { + error("Length out of range:%d", len); + return; + } + + bool found = false; + for (int i=0 ; i<30 ; i++) + { + unsigned int base = lenBases[i].base; + unsigned int range = lenBases[i].range; + if (base + range > len) + { + unsigned int lenCode = 257 + i; + unsigned int length = len - base; + //trace("--- %d %d %d %d", len, base, range, length); + encodeLiteralStatic(lenCode); + putBits(length, lenBases[i].bits); + found = true; + break; + } + } + if (!found) + { + error("Length not found in table:%d", len); + return; + } + + //## Output distance + + if (dist < 4 || dist > 32768) + { + error("Distance out of range:%d", dist); + return; + } + + found = false; + for (int i=0 ; i<30 ; i++) + { + unsigned int base = distBases[i].base; + unsigned int range = distBases[i].range; + if (base + range > dist) + { + unsigned int distCode = i; + unsigned int distance = dist - base; + //error("--- %d %d %d %d", dist, base, range, distance); + putBitsR(distCode, 5); + putBits(distance, distBases[i].bits); + found = true; + break; + } + } + if (!found) + { + error("Distance not found in table:%d", dist); + return; + } +} + + +//############################# +//# C O M P R E S S +//############################# + + +/** + * This method does the dirty work of dictionary + * compression. Basically it looks for redundant + * strings and has the current duplicate refer back + * to the previous one. + */ +bool Deflater::compressWindow() +{ + windowPos = 0; + unsigned int windowSize = window.size(); + //### Compress as much of the window as possible + + unsigned int hash = 0; + //Have each value be a long with the byte at this position, + //plus the 3 bytes after it in the window + for (int i=windowSize-1 ; i>=0 ; i--) + { + unsigned char ch = window[i]; + windowBuf[i] = ch; + hash = ((hash<<8) & 0xffffff00) | ch; + windowHashBuf[i] = hash; + } + + while (windowPos < windowSize - 3) + { + //### Find best match, if any + unsigned int bestMatchLen = 0; + unsigned int bestMatchDist = 0; + if (windowPos >= 4) + { + for (unsigned int lookBack=0 ; lookBack= windowPos -4 ) + lookAheadMax = windowPos - 4 - lookBack; + if (lookAheadMax > 258) + lookAheadMax = 258; + unsigned char *wp = &(windowBuf[windowPos+4]); + unsigned char *lb = &(windowBuf[lookBack+4]); + while (lookAhead bestMatchLen) + { + bestMatchLen = lookAhead; + bestMatchDist = windowPos - lookBack; + } + } + } + } + if (bestMatchLen > 3) + { + //Distance encode + //trace("### distance"); + /* + printf("### 1 '"); + for (int i=0 ; i < bestMatchLen ; i++) + fputc(window[windowPos+i], stdout); + printf("'\n### 2 '"); + for (int i=0 ; i < bestMatchLen ; i++) + fputc(window[windowPos-bestMatchDist+i], stdout); + printf("'\n"); + */ + encodeDistStatic(bestMatchLen, bestMatchDist); + windowPos += bestMatchLen; + } + else + { + //Literal encode + //trace("### literal"); + encodeLiteralStatic(windowBuf[windowPos]); + windowPos++; + } + } + + while (windowPos < windowSize) + encodeLiteralStatic(windowBuf[windowPos++]); + + encodeLiteralStatic(256); + return true; +} + + +/** + * + */ +bool Deflater::compress() +{ + //trace("compress"); + unsigned long total = 0L; + windowPos = 0; + std::vector::iterator iter; + for (iter = uncompressed.begin(); iter != uncompressed.end() ; ) + { + total += windowPos; + trace("total:%ld", total); + if (windowPos > window.size()) + windowPos = window.size(); + window.erase(window.begin() , window.begin()+windowPos); + while (window.size() < 32768 && iter != uncompressed.end()) + { + window.push_back(*iter); + ++iter; + } + if (window.size() >= 32768) + putBits(0x00, 1); //0 -- more blocks + else + putBits(0x01, 1); //1 -- last block + putBits(0x01, 2); //01 -- static trees + if (!compressWindow()) + return false; + } + putFlush(); + return true; +} + + + + + +//######################################################################## +//# G Z I P F I L E +//######################################################################## + +/** + * Constructor + */ +GzipFile::GzipFile() : + data(), + fileName(), + fileBuf(), + fileBufPos(0), + compressionMethod(0) +{ +} + +/** + * Destructor + */ +GzipFile::~GzipFile() +{ +} + +/** + * Print error messages + */ +void GzipFile::error(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "GzipFile error:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +/** + * Print trace messages + */ +void GzipFile::trace(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "GzipFile:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +/** + * + */ +void GzipFile::put(unsigned char ch) +{ + data.push_back(ch); +} + +/** + * + */ +void GzipFile::setData(const std::vector &str) +{ + data = str; +} + +/** + * + */ +void GzipFile::clearData() +{ + data.clear(); +} + +/** + * + */ +std::vector &GzipFile::getData() +{ + return data; +} + +/** + * + */ +std::string &GzipFile::getFileName() +{ + return fileName; +} + +/** + * + */ +void GzipFile::setFileName(const std::string &val) +{ + fileName = val; +} + + + +//##################################### +//# U T I L I T Y +//##################################### + +/** + * Loads a new file into an existing GzipFile + */ +bool GzipFile::loadFile(const std::string &fName) +{ + FILE *f = fopen(fName.c_str() , "rb"); + if (!f) + { + error("Cannot open file %s", fName.c_str()); + return false; + } + while (true) + { + int ch = fgetc(f); + if (ch < 0) + break; + data.push_back(ch); + } + fclose(f); + setFileName(fName); + return true; +} + + + +//##################################### +//# W R I T E +//##################################### + +/** + * + */ +bool GzipFile::putByte(unsigned char ch) +{ + fileBuf.push_back(ch); + return true; +} + + + +/** + * + */ +bool GzipFile::putLong(unsigned long val) +{ + fileBuf.push_back( (unsigned char)((val ) & 0xff)); + fileBuf.push_back( (unsigned char)((val>> 8) & 0xff)); + fileBuf.push_back( (unsigned char)((val>>16) & 0xff)); + fileBuf.push_back( (unsigned char)((val>>24) & 0xff)); + return true; +} + + + +/** + * + */ +bool GzipFile::write() +{ + fileBuf.clear(); + + putByte(0x1f); //magic + putByte(0x8b); //magic + putByte( 8); //compression method + putByte(0x08); //flags. say we have a crc and file name + + unsigned long ltime = (unsigned long) time(NULL); + putLong(ltime); + + //xfl + putByte(0); + //OS + putByte(0); + + //file name + for (unsigned int i=0 ; i compBuf; + Deflater deflater; + if (!deflater.deflate(compBuf, data)) + { + return false; + } + + std::vector::iterator iter; + for (iter=compBuf.begin() ; iter!=compBuf.end() ; ++iter) + { + unsigned char ch = *iter; + putByte(ch); + } + + Crc32 crcEngine; + crcEngine.update(data); + unsigned long crc = crcEngine.getValue(); + putLong(crc); + + putLong(data.size()); + + return true; +} + + +/** + * + */ +bool GzipFile::writeBuffer(std::vector &outBuf) +{ + if (!write()) + return false; + outBuf.clear(); + outBuf = fileBuf; + return true; +} + + +/** + * + */ +bool GzipFile::writeFile(const std::string &fileName) +{ + if (!write()) + return false; + FILE *f = fopen(fileName.c_str(), "wb"); + if (!f) + return false; + std::vector::iterator iter; + for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) + { + unsigned char ch = *iter; + fputc(ch, f); + } + fclose(f); + return true; +} + + +//##################################### +//# R E A D +//##################################### + +bool GzipFile::getByte(unsigned char *ch) +{ + if (fileBufPos >= fileBuf.size()) + { + error("unexpected end of data"); + return false; + } + *ch = fileBuf[fileBufPos++]; + return true; +} + +/** + * + */ +bool GzipFile::getLong(unsigned long *val) +{ + if (fileBuf.size() - fileBufPos < 4) + return false; + int ch1 = fileBuf[fileBufPos++]; + int ch2 = fileBuf[fileBufPos++]; + int ch3 = fileBuf[fileBufPos++]; + int ch4 = fileBuf[fileBufPos++]; + *val = ((ch4<<24) & 0xff000000L) | + ((ch3<<16) & 0x00ff0000L) | + ((ch2<< 8) & 0x0000ff00L) | + ((ch1 ) & 0x000000ffL); + return true; +} + +bool GzipFile::read() +{ + fileBufPos = 0; + + unsigned char ch; + + //magic cookie + if (!getByte(&ch)) + return false; + if (ch != 0x1f) + { + error("bad gzip header"); + return false; + } + if (!getByte(&ch)) + return false; + if (ch != 0x8b) + { + error("bad gzip header"); + return false; + } + + //## compression method + if (!getByte(&ch)) + return false; + compressionMethod = ch & 0xff; + + //## flags + if (!getByte(&ch)) + return false; + //bool ftext = ch & 0x01; + bool fhcrc = ch & 0x02; + bool fextra = ch & 0x04; + bool fname = ch & 0x08; + bool fcomment = ch & 0x10; + + //trace("cm:%d ftext:%d fhcrc:%d fextra:%d fname:%d fcomment:%d", + // cm, ftext, fhcrc, fextra, fname, fcomment); + + //## file time + unsigned long ltime; + if (!getLong(<ime)) + return false; + //time_t mtime = (time_t)ltime; + + //## XFL + if (!getByte(&ch)) + return false; + //int xfl = ch; + + //## OS + if (!getByte(&ch)) + return false; + //int os = ch; + + //std::string timestr = ctime(&mtime); + //trace("xfl:%d os:%d mtime:%s", xfl, os, timestr.c_str()); + + if (fextra) + { + if (!getByte(&ch)) + return false; + long xlen = ch; + if (!getByte(&ch)) + return false; + xlen = (xlen << 8) + ch; + for (long l=0 ; l compBuf; + while (fileBufPos < fileBuf.size() - 8) + { + if (!getByte(&ch)) + return false; + compBuf.push_back(ch); + } + //uncompress + data.clear(); + Inflater inflater; + if (!inflater.inflate(data, compBuf)) + { + return false; + } + + //Get the CRC and compare + Crc32 crcEngine; + crcEngine.update(data); + unsigned long calcCrc = crcEngine.getValue(); + unsigned long givenCrc; + if (!getLong(&givenCrc)) + return false; + if (givenCrc != calcCrc) + { + error("Specified crc, %ud, not what received: %ud", + givenCrc, calcCrc); + return false; + } + + //Get the file size and compare + unsigned long givenFileSize; + if (!getLong(&givenFileSize)) + return false; + if (givenFileSize != data.size()) + { + error("Specified data size, %ld, not what received: %ld", + givenFileSize, data.size()); + return false; + } + + return true; +} + + + +/** + * + */ +bool GzipFile::readBuffer(const std::vector &inbuf) +{ + fileBuf = inbuf; + if (!read()) + return false; + return true; +} + + +/** + * + */ +bool GzipFile::readFile(const std::string &fileName) +{ + fileBuf.clear(); + FILE *f = fopen(fileName.c_str(), "rb"); + if (!f) + return false; + while (true) + { + int ch = fgetc(f); + if (ch < 0) + break; + fileBuf.push_back(ch); + } + fclose(f); + if (!read()) + return false; + return true; +} + + + + + + + + +//######################################################################## +//# Z I P F I L E +//######################################################################## + +/** + * Constructor + */ +ZipEntry::ZipEntry() +{ + crc = 0L; + compressionMethod = 8; + position = 0; +} + +/** + * + */ +ZipEntry::ZipEntry(const std::string &fileNameArg, + const std::string &commentArg) +{ + crc = 0L; + compressionMethod = 8; + fileName = fileNameArg; + comment = commentArg; + position = 0; +} + +/** + * Destructor + */ +ZipEntry::~ZipEntry() +{ +} + + +/** + * + */ +std::string ZipEntry::getFileName() +{ + return fileName; +} + +/** + * + */ +void ZipEntry::setFileName(const std::string &val) +{ + fileName = val; +} + +/** + * + */ +std::string ZipEntry::getComment() +{ + return comment; +} + +/** + * + */ +void ZipEntry::setComment(const std::string &val) +{ + comment = val; +} + +/** + * + */ +unsigned long ZipEntry::getCompressedSize() +{ + return (unsigned long)compressedData.size(); +} + +/** + * + */ +int ZipEntry::getCompressionMethod() +{ + return compressionMethod; +} + +/** + * + */ +void ZipEntry::setCompressionMethod(int val) +{ + compressionMethod = val; +} + +/** + * + */ +std::vector &ZipEntry::getCompressedData() +{ + return compressedData; +} + +/** + * + */ +void ZipEntry::setCompressedData(const std::vector &val) +{ + compressedData = val; +} + +/** + * + */ +unsigned long ZipEntry::getUncompressedSize() +{ + return (unsigned long)uncompressedData.size(); +} + +/** + * + */ +std::vector &ZipEntry::getUncompressedData() +{ + return uncompressedData; +} + +/** + * + */ +void ZipEntry::setUncompressedData(const std::vector &val) +{ + uncompressedData = val; +} + +/** + * + */ +unsigned long ZipEntry::getCrc() +{ + return crc; +} + +/** + * + */ +void ZipEntry::setCrc(unsigned long val) +{ + crc = val; +} + +/** + * + */ +void ZipEntry::write(unsigned char ch) +{ + uncompressedData.push_back(ch); +} + +/** + * + */ +void ZipEntry::finish() +{ + Crc32 c32; + std::vector::iterator iter; + for (iter = uncompressedData.begin() ; + iter!= uncompressedData.end() ; ++iter) + { + unsigned char ch = *iter; + c32.update(ch); + } + crc = c32.getValue(); + switch (compressionMethod) + { + case 0: //none + { + for (iter = uncompressedData.begin() ; + iter!= uncompressedData.end() ; ++iter) + { + unsigned char ch = *iter; + compressedData.push_back(ch); + } + break; + } + case 8: //deflate + { + Deflater deflater; + if (!deflater.deflate(compressedData, uncompressedData)) + { + //some error + } + break; + } + default: + { + printf("error: unknown compression method %d\n", + compressionMethod); + } + } +} + + + + +/** + * + */ +bool ZipEntry::readFile(const std::string &fileNameArg, + const std::string &commentArg) +{ + crc = 0L; + uncompressedData.clear(); + fileName = fileNameArg; + comment = commentArg; + FILE *f = fopen(fileName.c_str(), "rb"); + if (!f) + { + return false; + } + while (true) + { + int ch = fgetc(f); + if (ch < 0) + break; + uncompressedData.push_back((unsigned char)ch); + } + fclose(f); + finish(); + return true; +} + + +/** + * + */ +void ZipEntry::setPosition(unsigned long val) +{ + position = val; +} + +/** + * + */ +unsigned long ZipEntry::getPosition() +{ + return position; +} + + + + + + + +/** + * Constructor + */ +ZipFile::ZipFile() : + entries(), + fileBuf(), + fileBufPos(0), + comment() +{ +} + +/** + * Destructor + */ +ZipFile::~ZipFile() +{ + std::vector::iterator iter; + for (iter=entries.begin() ; iter!=entries.end() ; ++iter) + { + ZipEntry *entry = *iter; + delete entry; + } + entries.clear(); +} + +/** + * + */ +void ZipFile::setComment(const std::string &val) +{ + comment = val; +} + +/** + * + */ +std::string ZipFile::getComment() +{ + return comment; +} + + +/** + * + */ +std::vector &ZipFile::getEntries() +{ + return entries; +} + + + +//##################################### +//# M E S S A G E S +//##################################### + +void ZipFile::error(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "ZipFile error:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +void ZipFile::trace(char const *fmt, ...) +{ + va_list args; + va_start(args, fmt); + fprintf(stdout, "ZipFile:"); + vfprintf(stdout, fmt, args); + fprintf(stdout, "\n"); + va_end(args); +} + +//##################################### +//# U T I L I T Y +//##################################### + +/** + * + */ +ZipEntry *ZipFile::addFile(const std::string &fileName, + const std::string &comment) +{ + ZipEntry *ze = new ZipEntry(); + if (!ze->readFile(fileName, comment)) + { + delete ze; + return NULL; + } + entries.push_back(ze); + return ze; +} + + +/** + * + */ +ZipEntry *ZipFile::newEntry(const std::string &fileName, + const std::string &comment) +{ + ZipEntry *ze = new ZipEntry(fileName, comment); + entries.push_back(ze); + return ze; +} + + +//##################################### +//# W R I T E +//##################################### + +/** + * + */ +bool ZipFile::putLong(unsigned long val) +{ + fileBuf.push_back( ((int)(val )) & 0xff); + fileBuf.push_back( ((int)(val>> 8)) & 0xff); + fileBuf.push_back( ((int)(val>>16)) & 0xff); + fileBuf.push_back( ((int)(val>>24)) & 0xff); + return true; +} + + +/** + * + */ +bool ZipFile::putInt(unsigned int val) +{ + fileBuf.push_back( (val ) & 0xff); + fileBuf.push_back( (val>> 8) & 0xff); + return true; +} + +/** + * + */ +bool ZipFile::putByte(unsigned char val) +{ + fileBuf.push_back(val); + return true; +} + +/** + * + */ +bool ZipFile::writeFileData() +{ + std::vector::iterator iter; + for (iter = entries.begin() ; iter != entries.end() ; ++iter) + { + ZipEntry *entry = *iter; + entry->setPosition(fileBuf.size()); + //##### HEADER + std::string fname = entry->getFileName(); + putLong(0x04034b50L); + putInt(20); //versionNeeded + putInt(0); //gpBitFlag + //putInt(0); //compression method + putInt(entry->getCompressionMethod()); //compression method + putInt(0); //mod time + putInt(0); //mod date + putLong(entry->getCrc()); //crc32 + putLong(entry->getCompressedSize()); + putLong(entry->getUncompressedSize()); + putInt(fname.size());//fileName length + putInt(8);//extra field length + //file name + for (unsigned int i=0 ; i &buf = entry->getCompressedData(); + std::vector::iterator iter; + for (iter = buf.begin() ; iter != buf.end() ; ++iter) + { + unsigned char ch = (unsigned char) *iter; + putByte(ch); + } + } + return true; +} + +/** + * + */ +bool ZipFile::writeCentralDirectory() +{ + unsigned long cdPosition = fileBuf.size(); + std::vector::iterator iter; + for (iter = entries.begin() ; iter != entries.end() ; ++iter) + { + ZipEntry *entry = *iter; + std::string fname = entry->getFileName(); + std::string ecomment = entry->getComment(); + putLong(0x02014b50L); //magic cookie + putInt(2386); //versionMadeBy + putInt(20); //versionNeeded + putInt(0); //gpBitFlag + putInt(entry->getCompressionMethod()); //compression method + putInt(0); //mod time + putInt(0); //mod date + putLong(entry->getCrc()); //crc32 + putLong(entry->getCompressedSize()); + putLong(entry->getUncompressedSize()); + putInt(fname.size());//fileName length + putInt(4);//extra field length + putInt(ecomment.size());//comment length + putInt(0); //disk number start + putInt(0); //internal attributes + putLong(0); //external attributes + putLong(entry->getPosition()); + + //file name + for (unsigned int i=0 ; i &outBuf) +{ + if (!write()) + return false; + outBuf.clear(); + outBuf = fileBuf; + return true; +} + + +/** + * + */ +bool ZipFile::writeFile(const std::string &fileName) +{ + if (!write()) + return false; + FILE *f = fopen(fileName.c_str(), "wb"); + if (!f) + return false; + std::vector::iterator iter; + for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) + { + unsigned char ch = *iter; + fputc(ch, f); + } + fclose(f); + return true; +} + +//##################################### +//# R E A D +//##################################### + +/** + * + */ +bool ZipFile::getLong(unsigned long *val) +{ + if (fileBuf.size() - fileBufPos < 4) + return false; + int ch1 = fileBuf[fileBufPos++]; + int ch2 = fileBuf[fileBufPos++]; + int ch3 = fileBuf[fileBufPos++]; + int ch4 = fileBuf[fileBufPos++]; + *val = ((ch4<<24) & 0xff000000L) | + ((ch3<<16) & 0x00ff0000L) | + ((ch2<< 8) & 0x0000ff00L) | + ((ch1 ) & 0x000000ffL); + return true; +} + +/** + * + */ +bool ZipFile::getInt(unsigned int *val) +{ + if (fileBuf.size() - fileBufPos < 2) + return false; + int ch1 = fileBuf[fileBufPos++]; + int ch2 = fileBuf[fileBufPos++]; + *val = ((ch2<< 8) & 0xff00) | + ((ch1 ) & 0x00ff); + return true; +} + + +/** + * + */ +bool ZipFile::getByte(unsigned char *val) +{ + if (fileBuf.size() <= fileBufPos) + return false; + *val = fileBuf[fileBufPos++]; + return true; +} + + +/** + * + */ +bool ZipFile::readFileData() +{ + //printf("#################################################\n"); + //printf("###D A T A\n"); + //printf("#################################################\n"); + while (true) + { + unsigned long magicCookie; + if (!getLong(&magicCookie)) + { + error("magic cookie not found"); + break; + } + trace("###Cookie:%lx", magicCookie); + if (magicCookie == 0x02014b50L) //central directory + break; + if (magicCookie != 0x04034b50L) + { + error("file header not found"); + return false; + } + unsigned int versionNeeded; + if (!getInt(&versionNeeded)) + { + error("bad version needed found"); + return false; + } + unsigned int gpBitFlag; + if (!getInt(&gpBitFlag)) + { + error("bad bit flag found"); + return false; + } + unsigned int compressionMethod; + if (!getInt(&compressionMethod)) + { + error("bad compressionMethod found"); + return false; + } + unsigned int modTime; + if (!getInt(&modTime)) + { + error("bad modTime found"); + return false; + } + unsigned int modDate; + if (!getInt(&modDate)) + { + error("bad modDate found"); + return false; + } + unsigned long crc32; + if (!getLong(&crc32)) + { + error("bad crc32 found"); + return false; + } + unsigned long compressedSize; + if (!getLong(&compressedSize)) + { + error("bad compressedSize found"); + return false; + } + unsigned long uncompressedSize; + if (!getLong(&uncompressedSize)) + { + error("bad uncompressedSize found"); + return false; + } + unsigned int fileNameLength; + if (!getInt(&fileNameLength)) + { + error("bad fileNameLength found"); + return false; + } + unsigned int extraFieldLength; + if (!getInt(&extraFieldLength)) + { + error("bad extraFieldLength found"); + return false; + } + std::string fileName; + for (unsigned int i=0 ; i compBuf; + if (gpBitFlag & 0x8)//bit 3 was set. means we dont know compressed size + { + unsigned char c1, c2, c3, c4; + c1 = c2 = c3 = c4 = 0; + while (true) + { + unsigned char ch; + if (!getByte(&ch)) + { + error("premature end of data"); + break; + } + compBuf.push_back(ch); + c1 = c2; c2 = c3; c3 = c4; c4 = ch; + if (c1 == 0x50 && c2 == 0x4b && c3 == 0x07 && c4 == 0x08) + { + trace("found end of compressed data"); + //remove the cookie + compBuf.erase(compBuf.end() -4, compBuf.end()); + break; + } + } + } + else + { + for (unsigned long bnr = 0 ; bnr < compressedSize ; bnr++) + { + unsigned char ch; + if (!getByte(&ch)) + { + error("premature end of data"); + break; + } + compBuf.push_back(ch); + } + } + + printf("### data: "); + for (int i=0 ; i<10 ; i++) + printf("%02x ", compBuf[i] & 0xff); + printf("\n"); + + if (gpBitFlag & 0x8)//only if bit 3 set + { + /* this cookie was read in the loop above + unsigned long dataDescriptorSignature ; + if (!getLong(&dataDescriptorSignature)) + break; + if (dataDescriptorSignature != 0x08074b50L) + { + error("bad dataDescriptorSignature found"); + return false; + } + */ + unsigned long crc32; + if (!getLong(&crc32)) + { + error("bad crc32 found"); + return false; + } + unsigned long compressedSize; + if (!getLong(&compressedSize)) + { + error("bad compressedSize found"); + return false; + } + unsigned long uncompressedSize; + if (!getLong(&uncompressedSize)) + { + error("bad uncompressedSize found"); + return false; + } + }//bit 3 was set + //break; + + std::vector uncompBuf; + switch (compressionMethod) + { + case 8: //deflate + { + Inflater inflater; + if (!inflater.inflate(uncompBuf, compBuf)) + { + return false; + } + break; + } + default: + { + error("Unimplemented compression method %d", compressionMethod); + return false; + } + } + + if (uncompressedSize != uncompBuf.size()) + { + error("Size mismatch. Expected %ld, received %ld", + uncompressedSize, uncompBuf.size()); + return false; + } + + Crc32 crcEngine; + crcEngine.update(uncompBuf); + unsigned long crc = crcEngine.getValue(); + if (crc != crc32) + { + error("Crc mismatch. Calculated %08ux, received %08ux", crc, crc32); + return false; + } + + ZipEntry *ze = new ZipEntry(fileName, comment); + ze->setCompressionMethod(compressionMethod); + ze->setCompressedData(compBuf); + ze->setUncompressedData(uncompBuf); + ze->setCrc(crc); + entries.push_back(ze); + + + } + return true; +} + + +/** + * + */ +bool ZipFile::readCentralDirectory() +{ + //printf("#################################################\n"); + //printf("###D I R E C T O R Y\n"); + //printf("#################################################\n"); + while (true) + { + //We start with a central directory cookie already + //Check at the bottom of the loop. + unsigned int version; + if (!getInt(&version)) + { + error("bad version found"); + return false; + } + unsigned int versionNeeded; + if (!getInt(&versionNeeded)) + { + error("bad version found"); + return false; + } + unsigned int gpBitFlag; + if (!getInt(&gpBitFlag)) + { + error("bad bit flag found"); + return false; + } + unsigned int compressionMethod; + if (!getInt(&compressionMethod)) + { + error("bad compressionMethod found"); + return false; + } + unsigned int modTime; + if (!getInt(&modTime)) + { + error("bad modTime found"); + return false; + } + unsigned int modDate; + if (!getInt(&modDate)) + { + error("bad modDate found"); + return false; + } + unsigned long crc32; + if (!getLong(&crc32)) + { + error("bad crc32 found"); + return false; + } + unsigned long compressedSize; + if (!getLong(&compressedSize)) + { + error("bad compressedSize found"); + return false; + } + unsigned long uncompressedSize; + if (!getLong(&uncompressedSize)) + { + error("bad uncompressedSize found"); + return false; + } + unsigned int fileNameLength; + if (!getInt(&fileNameLength)) + { + error("bad fileNameLength found"); + return false; + } + unsigned int extraFieldLength; + if (!getInt(&extraFieldLength)) + { + error("bad extraFieldLength found"); + return false; + } + unsigned int fileCommentLength; + if (!getInt(&fileCommentLength)) + { + error("bad fileCommentLength found"); + return false; + } + unsigned int diskNumberStart; + if (!getInt(&diskNumberStart)) + { + error("bad diskNumberStart found"); + return false; + } + unsigned int internalFileAttributes; + if (!getInt(&internalFileAttributes)) + { + error("bad internalFileAttributes found"); + return false; + } + unsigned long externalFileAttributes; + if (!getLong(&externalFileAttributes)) + { + error("bad externalFileAttributes found"); + return false; + } + unsigned long localHeaderOffset; + if (!getLong(&localHeaderOffset)) + { + error("bad localHeaderOffset found"); + return false; + } + std::string fileName; + for (unsigned int i=0 ; i &inbuf) +{ + fileBuf = inbuf; + if (!read()) + return false; + return true; +} + + +/** + * + */ +bool ZipFile::readFile(const std::string &fileName) +{ + fileBuf.clear(); + FILE *f = fopen(fileName.c_str(), "rb"); + if (!f) + return false; + while (true) + { + int ch = fgetc(f); + if (ch < 0) + break; + fileBuf.push_back(ch); + } + fclose(f); + if (!read()) + return false; + return true; +} + + + + + + + + + +//######################################################################## +//# E N D O F F I L E +//######################################################################## + + diff --git a/src/dom/util/ziptool.h b/src/dom/util/ziptool.h new file mode 100644 index 000000000..dbae8ac60 --- /dev/null +++ b/src/dom/util/ziptool.h @@ -0,0 +1,567 @@ +#ifndef SEEN_ZIPTOOL_H +#define SEEN_ZIPTOOL_H +/** + * This is intended to be a standalone, reduced capability + * implementation of Gzip and Zip functionality. Its + * targeted use case is for archiving and retrieving single files + * which use these encoding types. Being memory based and + * non-optimized, it is not useful in cases where very large + * archives are needed or where high performance is desired. + * However, it should hopefully work well for smaller, + * one-at-a-time tasks. What you get in return is the ability + * to drop these files into your project and remove the dependencies + * on ZLib and Info-Zip. Enjoy. + */ +/* + * Authors: + * Bob Jamison + * + * Copyright (C) 2006-2007 Bob Jamison + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +#include +#include + + +//######################################################################## +//# A D L E R 3 2 +//######################################################################## + +class Adler32 +{ +public: + + Adler32(); + + virtual ~Adler32(); + + void reset(); + + void update(unsigned char b); + + void update(char *str); + + unsigned long getValue(); + +private: + + unsigned long value; + +}; + + +//######################################################################## +//# C R C 3 2 +//######################################################################## + +class Crc32 +{ +public: + + Crc32(); + + virtual ~Crc32(); + + void reset(); + + void update(unsigned char b); + + void update(char *str); + + void update(const std::vector &buf); + + unsigned long getValue(); + +private: + + unsigned long value; + +}; + + + + + + +//######################################################################## +//# G Z I P S T R E A M S +//######################################################################## + +class GzipFile +{ +public: + + /** + * + */ + GzipFile(); + + /** + * + */ + virtual ~GzipFile(); + + /** + * + */ + virtual void put(unsigned char ch); + + /** + * + */ + virtual void setData(const std::vector &str); + + /** + * + */ + virtual void clearData(); + + /** + * + */ + virtual std::vector &getData(); + + /** + * + */ + virtual std::string &getFileName(); + + /** + * + */ + virtual void setFileName(const std::string &val); + + + //###################### + //# U T I L I T Y + //###################### + + /** + * + */ + virtual bool readFile(const std::string &fName); + + //###################### + //# W R I T E + //###################### + + /** + * + */ + virtual bool write(); + + /** + * + */ + virtual bool writeBuffer(std::vector &outbuf); + + /** + * + */ + virtual bool writeFile(const std::string &fileName); + + + //###################### + //# R E A D + //###################### + + + /** + * + */ + virtual bool read(); + + /** + * + */ + virtual bool readBuffer(const std::vector &inbuf); + + /** + * + */ + virtual bool loadFile(const std::string &fileName); + + + +private: + + std::vector data; + std::string fileName; + + //debug messages + void error(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + void trace(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + std::vector fileBuf; + unsigned long fileBufPos; + + bool getByte(unsigned char *ch); + bool getLong(unsigned long *val); + + bool putByte(unsigned char ch); + bool putLong(unsigned long val); + + int compressionMethod; +}; + + + + +//######################################################################## +//# Z I P F I L E +//######################################################################## + + +/** + * + */ +class ZipEntry +{ +public: + + /** + * + */ + ZipEntry(); + + /** + * + */ + ZipEntry(const std::string &fileName, + const std::string &comment); + + /** + * + */ + virtual ~ZipEntry(); + + /** + * + */ + virtual std::string getFileName(); + + /** + * + */ + virtual void setFileName(const std::string &val); + + /** + * + */ + virtual std::string getComment(); + + /** + * + */ + virtual void setComment(const std::string &val); + + /** + * + */ + virtual unsigned long getCompressedSize(); + + /** + * + */ + virtual int getCompressionMethod(); + + /** + * + */ + virtual void setCompressionMethod(int val); + + /** + * + */ + virtual std::vector &getCompressedData(); + + /** + * + */ + virtual void setCompressedData(const std::vector &val); + + /** + * + */ + virtual unsigned long getUncompressedSize(); + + /** + * + */ + virtual std::vector &getUncompressedData(); + + /** + * + */ + virtual void setUncompressedData(const std::vector &val); + + /** + * + */ + virtual void write(unsigned char ch); + + /** + * + */ + virtual void finish(); + + /** + * + */ + virtual unsigned long getCrc(); + + /** + * + */ + virtual void setCrc(unsigned long crc); + + /** + * + */ + virtual bool readFile(const std::string &fileNameArg, + const std::string &commentArg); + + /** + * + */ + virtual void setPosition(unsigned long val); + + /** + * + */ + virtual unsigned long getPosition(); + +private: + + unsigned long crc; + + std::string fileName; + std::string comment; + + int compressionMethod; + + std::vector compressedData; + std::vector uncompressedData; + + unsigned long position; +}; + + + + + + + + + +/** + * This class sits over the zlib and gzip code to + * implement a PKWare or Info-Zip .zip file reader and + * writer + */ +class ZipFile +{ +public: + + /** + * + */ + ZipFile(); + + /** + * + */ + virtual ~ZipFile(); + + //###################### + //# V A R I A B L E S + //###################### + + /** + * + */ + virtual void setComment(const std::string &val); + + /** + * + */ + virtual std::string getComment(); + + /** + * Return the list of entries currently in this file + */ + std::vector &getEntries(); + + + //###################### + //# U T I L I T Y + //###################### + + /** + * + */ + virtual ZipEntry *addFile(const std::string &fileNameArg, + const std::string &commentArg); + + /** + * + */ + virtual ZipEntry *newEntry(const std::string &fileNameArg, + const std::string &commentArg); + + //###################### + //# W R I T E + //###################### + + /** + * + */ + virtual bool write(); + + /** + * + */ + virtual bool writeBuffer(std::vector &outbuf); + + /** + * + */ + virtual bool writeFile(const std::string &fileName); + + + //###################### + //# R E A D + //###################### + + + /** + * + */ + virtual bool read(); + + /** + * + */ + virtual bool readBuffer(const std::vector &inbuf); + + /** + * + */ + virtual bool readFile(const std::string &fileName); + + +private: + + //debug messages + void error(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + void trace(char const *fmt, ...) + #ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) + #endif + ; + + //# Private writing methods + + /** + * + */ + bool putLong(unsigned long val); + + /** + * + */ + bool putInt(unsigned int val); + + + /** + * + */ + bool putByte(unsigned char val); + + /** + * + */ + bool writeFileData(); + + /** + * + */ + bool writeCentralDirectory(); + + + //# Private reading methods + + /** + * + */ + bool getLong(unsigned long *val); + + /** + * + */ + bool getInt(unsigned int *val); + + /** + * + */ + bool getByte(unsigned char *val); + + /** + * + */ + bool readFileData(); + + /** + * + */ + bool readCentralDirectory(); + + + std::vector entries; + + std::vector fileBuf; + unsigned long fileBufPos; + + std::string comment; +}; + + + + + + +#endif // SEEN_ZIPTOOL_H + + +//######################################################################## +//# E N D O F F I L E +//######################################################################## + -- cgit v1.2.3 From e330f37cfa5949bb505bb846a467f10c2c711d8f Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Sat, 9 Feb 2013 10:30:08 +0100 Subject: Add function to add document font-family entries to store. Remove font-family to interator map as we can now have duplicate font-family names in store. (bzr r12111) --- src/libnrtype/font-lister.cpp | 149 +++++++++++++++++++++++++++++++++++++++++- src/libnrtype/font-lister.h | 40 +++++------- 2 files changed, 165 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/libnrtype/font-lister.cpp b/src/libnrtype/font-lister.cpp index 6df576866..9949be208 100644 --- a/src/libnrtype/font-lister.cpp +++ b/src/libnrtype/font-lister.cpp @@ -14,6 +14,11 @@ #include "font-lister.h" #include "FontFactory.h" +#include "sp-object.h" +#include "sp-root.h" +#include "document.h" +#include "xml/repr.h" + namespace Inkscape { FontLister::FontLister () @@ -53,11 +58,153 @@ namespace Inkscape (*treeModelIter)[FontList.styles] = styles; (*treeModelIter)[FontList.onSystem] = true; - font_list_store_iter_map.insert(std::make_pair(familyName, Gtk::TreePath(treeModelIter))); } } } + // Example of how to use "foreach_iter" + // bool + // FontLister::print_document_font( const Gtk::TreeModel::iterator &iter ) { + // Gtk::TreeModel::Row row = *iter; + // if( !row[FontList.onSystem] ) { + // std::cout << " Not on system: " << row[FontList.font] << std::endl; + // return false; + // } + // return true; + // } + // font_list_store->foreach_iter( sigc::mem_fun(*this, &FontLister::print_document_font )); + + void + FontLister::update_font_list( SPDocument* document ) { + + SPObject *r = document->getRoot(); + if( !r ) { + return; + } + + /* Clear all old document font-family entries */ + Gtk::TreeModel::iterator iter = font_list_store->get_iter( "0" ); + while( iter != font_list_store->children().end() ) { + Gtk::TreeModel::Row row = *iter; + if( !row[FontList.onSystem] ) { + // std::cout << " Not on system: " << row[FontList.font] << std::endl; + iter = font_list_store->erase( iter ); + } else { + // std::cout << " First on system: " << row[FontList.font] << std::endl; + break; + } + } + + /* Create default styles for use when font-family is unknown on system. */ + static GList *default_styles = NULL; + if( default_styles == NULL ) { + default_styles = g_list_append( default_styles, g_strdup("Normal") ); + default_styles = g_list_append( default_styles, g_strdup("Italic") ); + default_styles = g_list_append( default_styles, g_strdup("Bold") ); + default_styles = g_list_append( default_styles, g_strdup("Bold Italic") ); + default_styles = g_list_append( default_styles, g_strdup("Loopy") ); + } + + /* Get "font-family"s used in document. */ + std::list fontfamilies; + update_font_list_recursive( r, &fontfamilies ); + + fontfamilies.sort(); + fontfamilies.unique(); + fontfamilies.reverse(); + + /* Insert separator */ + if( !fontfamilies.empty() ) { + Gtk::TreeModel::iterator treeModelIter = font_list_store->prepend(); + (*treeModelIter)[FontList.font] = "separatoR"; + (*treeModelIter)[FontList.onSystem] = false; + } + + /* Insert font-family's in document. */ + std::list::iterator i; + for( i = fontfamilies.begin(); i != fontfamilies.end(); ++i) { + + GList *styles = default_styles; + + /* See if font-family (or first in fallback list) is on system. If so, get styles. */ + std::vector tokens = Glib::Regex::split_simple(",", *i ); + if( !tokens[0].empty() ) { + + Gtk::TreeModel::iterator iter2 = font_list_store->get_iter( "0" ); + while( iter2 != font_list_store->children().end() ) { + Gtk::TreeModel::Row row = *iter2; + if( row[FontList.onSystem] && tokens[0].compare( row[FontList.font] ) == 0 ) { + styles = row[FontList.styles]; + break; + } + ++iter2; + } + } + + Gtk::TreeModel::iterator treeModelIter = font_list_store->prepend(); + (*treeModelIter)[FontList.font] = reinterpret_cast(g_strdup((*i).c_str())); + (*treeModelIter)[FontList.styles] = styles; + (*treeModelIter)[FontList.onSystem] = false; + } + } + + void + FontLister::update_font_list_recursive( SPObject *r, std::list *l ) { + + const gchar *style = r->getRepr()->attribute("style"); + if( style != NULL ) { + + std::vector tokens = Glib::Regex::split_simple(";", style ); + for( size_t i=0; i < tokens.size(); ++i ) { + + Glib::ustring token = tokens[i]; + size_t found = token.find("font-family:"); + + if( found != Glib::ustring::npos ) { + + // Remove "font-family:" + token.erase(found,12); + + // Remove any leading single or double quote + if( token[0] == '\'' || token[0] == '"' ) { + token.erase(0,1); + } + + // Remove any trailing single or double quote + if( token[token.length()-1] == '\'' || token[token.length()-1] == '"' ) { + token.erase(token.length()-1); + } + + l->push_back( token ); + } + } + } + + for (SPObject *child = r->firstChild(); child; child = child->getNext()) { + update_font_list_recursive( child, l ); + } + } + + Gtk::TreePath + FontLister::get_row_for_font (Glib::ustring family) + { + Gtk::TreePath path; + + Gtk::TreeModel::iterator iter = font_list_store->get_iter( "0" ); + while( iter != font_list_store->children().end() ) { + + Gtk::TreeModel::Row row = *iter; + + if( family.compare( row[FontList.font] ) == 0 ) { + return font_list_store->get_path( iter ); + } + + ++iter; + } + + throw FAMILY_NOT_FOUND; + } + FontLister::~FontLister () { }; diff --git a/src/libnrtype/font-lister.h b/src/libnrtype/font-lister.h index 7a7db5615..d4c48dd52 100644 --- a/src/libnrtype/font-lister.h +++ b/src/libnrtype/font-lister.h @@ -7,9 +7,11 @@ * Authors: * Chris Lahey * Lauris Kaplinski + * Tavmjong Bah * * Copyright (C) 1999-2001 Ximian, Inc. * Copyright (C) 2002 Lauris Kaplinski + * Copyright (C) 2013 Tavmjong Bah * * Released under GNU GPL, read the file 'COPYING' for more information */ @@ -21,6 +23,9 @@ #include #include "nr-type-primitives.h" +class SPObject; +class SPDocument; + namespace Inkscape { /** @@ -66,22 +71,7 @@ namespace Inkscape } }; - /* Case-insensitive < compare for standard strings */ - class StringLessThan - { - public: - bool operator () (std::string str1, std::string str2) const - { - std::string s1=str1; // Can't transform the originals! - std::string s2=str2; - std::transform(s1.begin(), s1.end(), s1.begin(), (int(*)(int)) toupper); - std::transform(s2.begin(), s2.end(), s2.begin(), (int(*)(int)) toupper); - return s1 IterMapType; /** Returns the ListStore with the font names * @@ -92,6 +82,17 @@ namespace Inkscape const Glib::RefPtr get_font_list () const; + /** Updates font list to include fonts in document + * + */ + void + update_font_list ( SPDocument* document); + + private: + void + update_font_list_recursive( SPObject *r, std::list *l ); + + public: static Inkscape::FontLister* get_instance () { @@ -100,12 +101,7 @@ namespace Inkscape } Gtk::TreePath - get_row_for_font (Glib::ustring family) - { - IterMapType::iterator iter = font_list_store_iter_map.find (family); - if (iter == font_list_store_iter_map.end ()) throw FAMILY_NOT_FOUND; - return (*iter).second; - } + get_row_for_font (Glib::ustring family); const NRNameList get_name_list () const @@ -113,7 +109,6 @@ namespace Inkscape return families; } - private: FontLister (); @@ -121,7 +116,6 @@ namespace Inkscape NRNameList families; Glib::RefPtr font_list_store; - IterMapType font_list_store_iter_map; }; } -- cgit v1.2.3 From 83ae846627474ee5aad75c1f4816a3faa7240a47 Mon Sep 17 00:00:00 2001 From: Tavmjong Bah Date: Sat, 9 Feb 2013 13:52:04 +0100 Subject: Use update_font_list() in font-lister.cpp. Remove equivalent code in text-toolbar.cpp. Change separator "tag" from "separatoR" to "#" in attempt to speed up start up. (bzr r12112) --- src/libnrtype/font-lister.cpp | 2 +- src/widgets/text-toolbar.cpp | 100 +++--------------------------------------- 2 files changed, 7 insertions(+), 95 deletions(-) (limited to 'src') diff --git a/src/libnrtype/font-lister.cpp b/src/libnrtype/font-lister.cpp index 9949be208..1e51d8803 100644 --- a/src/libnrtype/font-lister.cpp +++ b/src/libnrtype/font-lister.cpp @@ -116,7 +116,7 @@ namespace Inkscape /* Insert separator */ if( !fontfamilies.empty() ) { Gtk::TreeModel::iterator treeModelIter = font_list_store->prepend(); - (*treeModelIter)[FontList.font] = "separatoR"; + (*treeModelIter)[FontList.font] = "#"; (*treeModelIter)[FontList.onSystem] = false; } diff --git a/src/widgets/text-toolbar.cpp b/src/widgets/text-toolbar.cpp index f19ee7cee..5ba2065b9 100644 --- a/src/widgets/text-toolbar.cpp +++ b/src/widgets/text-toolbar.cpp @@ -133,9 +133,6 @@ static void sp_print_fontstyle( SPStyle *query ) { } #endif -void sp_text_toolbox_get_font_list_in_doc (SPObject *r, std::list *l); -void sp_text_toolbox_update_font_list( GtkListStore* model ); - // Format family drop-down menu. static void cell_data_func(GtkCellLayout * /*cell_layout*/, GtkCellRenderer *cell, @@ -224,7 +221,7 @@ static gboolean separator_func(GtkTreeModel *model, { gchar* text = 0; gtk_tree_model_get(model, iter, 0, &text, -1 ); // Column 0 - return (text && strcmp(text,"separatoR") == 0); + return (text && strcmp(text,"#") == 0); } /* @@ -1250,7 +1247,8 @@ static void sp_text_toolbox_selection_changed(Inkscape::Selection */*selection*/ Ink_ComboBoxEntry_Action* fontFamilyAction = INK_COMBOBOXENTRY_ACTION( g_object_get_data( tbl, "TextFontFamilyAction" ) ); if( fontFamilyAction->combobox != NULL ) { - sp_text_toolbox_update_font_list( GTK_LIST_STORE(ink_comboboxentry_action_get_model(fontFamilyAction)) ); + Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + fontlister->update_font_list( sp_desktop_document( SP_ACTIVE_DESKTOP )); } @@ -1587,93 +1585,6 @@ sp_text_toolbox_get_font_list_in_doc_recursive (SPObject *r, std::list *l) { - - sp_text_toolbox_get_font_list_in_doc_recursive (r, l); - - l->sort(); - l->unique(); - l->reverse(); - - // for(std::list::iterator i = l->begin(); i != l->end(); ++i) { - // std::cout << " font_family in doc: " << *i << std::endl; - // } -} - -/* Update font-family list with "font-family" attributes used in a document. */ -void -sp_text_toolbox_update_font_list( GtkListStore* model ) { - - /* Create default styles for use when font-family is unknown on system. */ - static GList *default_styles = NULL; - if( default_styles == NULL ) { - default_styles = g_list_append( default_styles, g_strdup("Normal") ); - default_styles = g_list_append( default_styles, g_strdup("Italic") ); - default_styles = g_list_append( default_styles, g_strdup("Bold") ); - default_styles = g_list_append( default_styles, g_strdup("Bold Italic") ); - } - - /* Get "font-family" attributes used in document */ - std::list fontfamilies; - sp_text_toolbox_get_font_list_in_doc( (sp_desktop_document(SP_ACTIVE_DESKTOP))->getRoot(), &fontfamilies ); - - /* Delete all old doc font-family entries */ - GtkTreeIter iter; - gboolean valid; - for( valid = gtk_tree_model_get_iter_first( GTK_TREE_MODEL(model), &iter ); valid; ) { - gchar *family = 0; - gboolean onSystem = true; - gtk_tree_model_get( GTK_TREE_MODEL(model), &iter, 0, &family, 2, &onSystem, -1 ); - //std::cout << "List: " << family << ": " << (onSystem ? "Yes" : "No") << std::endl; - if( !onSystem ) { - valid = gtk_list_store_remove( model, &iter ); - } else { - valid = gtk_tree_model_iter_next( GTK_TREE_MODEL(model), &iter ); - } - } - - /* Insert separator */ - if( !fontfamilies.empty() ) { - gtk_list_store_insert( model, &iter, 0 ); // iter points to new row - gtk_list_store_set( model, &iter, 0, "separatoR", -1 ); - } - - - /* Insert doc font-family entries, list is already reverse sorted with duplicates removed. */ - std::list::iterator i; - for(i=fontfamilies.begin(); i != fontfamilies.end(); ++i) { - - GList *styles = default_styles; - gtk_list_store_insert( model, &iter, 0 ); // iter points to new row - - /* See if font-family (or first in fallback list) is on system. If so, get styles. */ - std::vector tokens = Glib::Regex::split_simple(",", *i ); - if( !tokens[0].empty() ) { - - GtkTreeIter iter2; - gboolean valid2; - for( valid2 = gtk_tree_model_get_iter_first( GTK_TREE_MODEL(model), &iter2 ); - valid2; - valid2 = gtk_tree_model_iter_next( GTK_TREE_MODEL(model), &iter2 ) ) { - - gchar* family = 0; - gboolean onSystem = true; - gtk_tree_model_get( GTK_TREE_MODEL(model), &iter2, 0, &family, 2, &onSystem, -1 ); - if( onSystem && tokens[0].compare( family ) == 0 ) { - gtk_tree_model_get( GTK_TREE_MODEL(model), &iter2, 1, &styles, -1 ); - break; - } - } - - } - - gtk_list_store_set( model, &iter, 0, (*i).c_str(), 1, styles, 2, false, -1 ); - } -} // Define all the "widgets" in the toolbar. void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObject* holder) @@ -1689,9 +1600,10 @@ void sp_text_toolbox_prep(SPDesktop *desktop, GtkActionGroup* mainActions, GObje /* Font family */ { // Font list - Glib::RefPtr store = Inkscape::FontLister::get_instance()->get_font_list(); + Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + fontlister->update_font_list( sp_desktop_document( SP_ACTIVE_DESKTOP )); + Glib::RefPtr store = fontlister->get_font_list(); GtkListStore* model = store->gobj(); - sp_text_toolbox_update_font_list( model ); Ink_ComboBoxEntry_Action* act = ink_comboboxentry_action_new( "TextFontFamilyAction", -- cgit v1.2.3