diff options
Diffstat (limited to 'src/analysis')
| -rwxr-xr-x | src/analysis/Makefile.am | 3 | ||||
| -rw-r--r-- | src/analysis/binary-int.h | 12 | ||||
| -rw-r--r-- | src/analysis/binary.c | 444 | ||||
| -rw-r--r-- | src/analysis/binary.h | 32 | ||||
| -rwxr-xr-x | src/analysis/db/Makefile.am | 22 | ||||
| -rw-r--r-- | src/analysis/db/bookmark.c | 69 | ||||
| -rw-r--r-- | src/analysis/db/bookmark.h | 41 | ||||
| -rw-r--r-- | src/analysis/db/cdb.c | 602 | ||||
| -rw-r--r-- | src/analysis/db/cdb.h | 62 | ||||
| -rw-r--r-- | src/analysis/db/client.c | 291 | ||||
| -rw-r--r-- | src/analysis/db/client.h | 61 | ||||
| -rw-r--r-- | src/analysis/db/collection.c | 26 | ||||
| -rw-r--r-- | src/analysis/db/collection.h | 30 | ||||
| -rw-r--r-- | src/analysis/db/core.c | 205 | ||||
| -rw-r--r-- | src/analysis/db/core.h | 70 | ||||
| -rw-r--r-- | src/analysis/db/protocol.h | 71 | ||||
| -rw-r--r-- | src/analysis/db/server.c | 426 | ||||
| -rw-r--r-- | src/analysis/db/server.h | 61 | 
18 files changed, 2521 insertions, 7 deletions
| diff --git a/src/analysis/Makefile.am b/src/analysis/Makefile.am index 6409943..79aa9d1 100755 --- a/src/analysis/Makefile.am +++ b/src/analysis/Makefile.am @@ -14,6 +14,7 @@ libanalysis_la_SOURCES =				\  libanalysis_la_LIBADD =					\  	binaries/libanalysisbinaries.la		\  	blocks/libanalysisblocks.la			\ +	db/libanalysisdb.la					\  	decomp/libanalysisdecomp.la			\  	disass/libanalysisdisass.la			\  	types/libanalysistypes.la @@ -27,4 +28,4 @@ AM_CPPFLAGS =  AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) -SUBDIRS = binaries blocks decomp disass types +SUBDIRS = binaries blocks db decomp disass types diff --git a/src/analysis/binary-int.h b/src/analysis/binary-int.h index f813aa8..788371a 100644 --- a/src/analysis/binary-int.h +++ b/src/analysis/binary-int.h @@ -28,6 +28,7 @@  #include "binary.h" +#include "db/client.h"  #include "../format/format.h" @@ -44,11 +45,22 @@ struct _GLoadedBinary  {      GObject parent;                         /* A laisser en premier        */ +    char *username;                         /* Identifiant de l'utilisateur*/ +    bool username_changed;                  /* Mémorise les changements    */ +    char *remote_host;                      /* Nom du serveur distant      */ +    unsigned short remote_port;             /* Port du serveur distant     */ +    bool use_remote_server;                 /* Indique une utilisation     */ + +    GDbClient *local;                       /* Enregistrements locaux      */ +    GDbClient *remote;                      /* Enregistrements distants    */ +    DBStorage storages[DBF_COUNT];          /* Lieux d'enregistrement      */ +      save_binary_fc save;                    /* Sauvegarde au format XML    */      get_binary_filename_fc get_filename;    /* Obtention d'une description */      off_t bin_length;                       /* Taille des données brutes   */      bin_t *bin_data;                        /* Données binaires brutes     */ +    GChecksum *checksum;                    /* Calcul de l'empreinte       */      GExeFormat *format;                     /* Format du binaire           */      GArchProcessor *proc;                   /* Architecture du binaire     */ diff --git a/src/analysis/binary.c b/src/analysis/binary.c index 05c4e99..31bd18b 100644 --- a/src/analysis/binary.c +++ b/src/analysis/binary.c @@ -39,6 +39,7 @@  #include "decomp/decompiler.h"  #include "disass/disassembler.h"  #include "../common/extstr.h" +#include "../common/cpp.h" @@ -69,6 +70,16 @@ static void ack_completed_disassembly(GDelayedDisassembly *, GLoadedBinary *); +/* ------------------------- INFORMATIONS D'ENREGISTREMENTS ------------------------- */ + + +/* Charge en mémoire les formes d'enregistrement du XML. */ +static bool g_loaded_binary_load_storage(GLoadedBinary *, xmlXPathContextPtr, const char *); + +/* Ecrit les formes d'enregistrement du binaire dans du XML. */ +static bool g_loaded_binary_save_storage(const GLoadedBinary *, xmlDocPtr, xmlXPathContextPtr, const char *); + + @@ -122,6 +133,16 @@ static void g_loaded_binary_class_init(GLoadedBinaryClass *klass)  static void g_loaded_binary_init(GLoadedBinary *binary)  { +    binary->username = strdup("default"); + +    binary->remote_host = strdup("localhost"); +    binary->remote_port = 9999; +    binary->use_remote_server = false; + +    binary->storages[DBF_COMMENTS] = DBS_ALL_LOCAL; +    binary->storages[DBF_SEGMENTS_DISPLAY] = DBS_ALL_LOCAL; +    binary->storages[DBF_BOOKMARKS] = DBS_ALL_LOCAL; +      binary->text_display[BDT_ASM][0] = true;      binary->text_display[BDT_ASM][1] = true;      binary->text_display[BDT_GRAPH][0] = false; @@ -146,14 +167,14 @@ static void g_loaded_binary_init(GLoadedBinary *binary)  static void g_loaded_binary_dispose(GLoadedBinary *binary)  { +    if (binary->checksum != NULL) +        g_checksum_free(binary->checksum); +      if (binary->format != NULL)          g_object_unref(G_OBJECT(binary->format));      if (binary->proc != NULL)          g_object_unref(G_OBJECT(binary->proc)); -    if (binary->bin_data != NULL) -        free(binary->bin_data); -      /* TODO... */      G_OBJECT_CLASS(g_loaded_binary_parent_class)->dispose(G_OBJECT(binary)); @@ -175,7 +196,12 @@ static void g_loaded_binary_dispose(GLoadedBinary *binary)  static void g_loaded_binary_finalize(GLoadedBinary *binary)  { -    /* TODO */ +    free(binary->username); + +    if (binary->bin_data != NULL) +        free(binary->bin_data); + +    /* TODO... */      G_OBJECT_CLASS(g_loaded_binary_parent_class)->finalize(G_OBJECT(binary)); @@ -198,22 +224,33 @@ static void g_loaded_binary_finalize(GLoadedBinary *binary)  GLoadedBinary *g_loaded_binary_new_from_xml(xmlXPathContextPtr context, const char *path)  {      GLoadedBinary *result;                  /* Adresse à retourner         */ -    char *type;                             /* Tupe de binaire à charger   */ +    char *type;                             /* Type de binaire à charger   */ +    bool status;                            /* Etat de la connexion à la BD*/      result = NULL;      type = get_node_prop_value(context, path, "type");      if (strcmp(type, "file") == 0) -        result = g_loaded_binary_new_from_xml(context, path); +        result = g_file_binary_new_from_xml(context, path);      free(type);      if (result == NULL)          return NULL; +    if (!g_loaded_binary_load_storage(result, context, path)) +        goto glbnfx_error; + +    /*      if (!g_loaded_binary_load_parts_from_xml(result, context, path))          goto glbnfx_error; +    */ + +    result->local = g_db_client_new("localhost", 1337); +    status = g_db_client_start(result->local); + +    printf("DB status :: %d\n", status);      return result; @@ -247,6 +284,8 @@ bool g_loaded_binary_save(const GLoadedBinary *binary, xmlDocPtr xdoc, xmlXPathC      result = binary->save(binary, xdoc, context, path); +    result = g_loaded_binary_save_storage(binary, xdoc, context, path); +      /* Parties à désassembler */      result = g_loaded_binary_save_parts(binary, xdoc, context, path); @@ -475,6 +514,368 @@ static bool g_loaded_binary_save_parts(const GLoadedBinary *binary, xmlDocPtr xd  } + +/* ---------------------------------------------------------------------------------- */ +/*                           INFORMATIONS D'ENREGISTREMENTS                           */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary  = élément binaire à traiter.                         * +*                context = contexte pour les recherches XPath.                * +*                path    = chemin d'accès au noeud XML à lire.                * +*                                                                             * +*  Description : Charge en mémoire les formes d'enregistrement du XML.        * +*                                                                             * +*  Retour      : true si l'opération a bien tourné, false sinon.              * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static bool g_loaded_binary_load_storage(GLoadedBinary *binary, xmlXPathContextPtr context, const char *path) +{ +    bool result;                            /* Bilan à faire remonter      */ +    char *storage_path;                     /* Partie "Enregistrement"     */ +    char *access;                           /* Chemin d'accès à un élément */ +    char *value;                            /* Valeur lue à partie du XML  */ +    unsigned short port;                    /* Port de communication       */ +    bool use;                               /* Usage d'un serveur distant  */ +    DBFeatures i;                           /* Boucle de parcours          */ + +    result = true; + +    storage_path = strdup(path); +    storage_path = stradd(storage_path, "/Storage"); + +    /* Nom d'utilisateur */ + +    access = strdup(storage_path); +    access = stradd(access, "/Username"); + +    value = get_node_text_value(context, access); + +    if (value != NULL) +    { +        g_loaded_binary_set_username(binary, value); +        free(value); +    } + +    free(access); + +    /* Serveur distant */ + +    access = strdup(storage_path); +    access = stradd(access, "/RemoteServer"); + +    value = get_node_prop_value(context, access, "port"); +    if (value == NULL) goto glbls_features; + +    port = atoi(value); + +    free(value); + +    value = get_node_prop_value(context, access, "use"); +    if (value == NULL) goto glbls_features; + +    use = (strcmp(value, "true") == 0); + +    free(value); + +    value = get_node_prop_value(context, access, "host"); +    if (value == NULL) goto glbls_features; + +    g_loaded_binary_set_remote_server(binary, value, port, use); + +    free(value); + + glbls_features: + +    free(access); + +    /* Fonctionnalités */ + +    for (i = 0; i < DBF_COUNT; i++) +    { +        access = strdup(storage_path); +        access = stradd(access, "/Features/"); + +        switch (i) +        { +            case DBF_COMMENTS: +                access = stradd(access, "Comments"); +                break; +            case DBF_SEGMENTS_DISPLAY: +                access = stradd(access, "Segments"); +                break; +            case DBF_BOOKMARKS: +                access = stradd(access, "Bookmarks"); +                break; +            case DBF_COUNT: +                /* Pour GCC */ +                break; +        } + +        value = get_node_text_value(context, access); + +        if (value != NULL) +        { +            if (atoi(value) <= DBS_MAX) +                g_loaded_binary_set_storage(binary, i, atoi(value)); + +        } + +        free(access); + +    } + +    free(storage_path); + +    return result; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary  = élément binaire à traiter.                         * +*                xdoc    = structure XML en cours d'édition.                  * +*                context = contexte à utiliser pour les recherches.           * +*                path    = chemin d'accès réservé au binaire.                 * +*                                                                             * +*  Description : Ecrit les formes d'enregistrement du binaire dans du XML.    * +*                                                                             * +*  Retour      : true si l'opération a bien tourné, false sinon.              * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static bool g_loaded_binary_save_storage(const GLoadedBinary *binary, xmlDocPtr xdoc, xmlXPathContextPtr context, const char *path) +{ +    bool result;                            /* Bilan à faire remonter      */ +    char *storage_path;                     /* Partie "Enregistrement"     */ +    char *access;                           /* Chemin d'accès à un élément */ +    char port_str[sizeof(STR(USHRT_MAX)) + 1]; /* Version chaînée          */ +    DBFeatures i;                           /* Boucle de parcours          */ + +    result = true; + +    storage_path = strdup(path); +    storage_path = stradd(storage_path, "/Storage"); + +    /* Nom d'utilisateur */ + +    access = strdup(storage_path); +    access = stradd(access, "/Username"); + +    result &= add_content_to_node(xdoc, context, access, binary->username); + +    free(access); + +    /* Serveur distant */ + +    access = strdup(storage_path); +    access = stradd(access, "/RemoteServer"); + +    result &= add_string_attribute_to_node(xdoc, context, access, "host", binary->remote_host); + +    sprintf(port_str, "%hu", binary->remote_port); +    result &= add_string_attribute_to_node(xdoc, context, access, "port", port_str); + +    result &= add_string_attribute_to_node(xdoc, context, access, "use", +                                           binary->use_remote_server ? "true" : "false"); + +    free(access); + +    /* Fonctionnalités */ + +    for (i = 0; i < DBF_COUNT; i++) +    { +        access = strdup(storage_path); +        access = stradd(access, "/Features/"); + +        switch (i) +        { +            case DBF_COMMENTS: +                access = stradd(access, "Comments"); +                break; +            case DBF_SEGMENTS_DISPLAY: +                access = stradd(access, "Segments"); +                break; +            case DBF_BOOKMARKS: +                access = stradd(access, "Bookmarks"); +                break; +            case DBF_COUNT: +                /* Pour GCC */ +                break; +        } + +        result &= add_uint_content_to_node(xdoc, context, access, binary->storages[i]); + +        free(access); + +    } + +    free(storage_path); + +    return result; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = élément binaire à consulter.                        * +*                                                                             * +*  Description : Identifie l'utilisateur analysant le binaire courant.        * +*                                                                             * +*  Retour      : Nom de l'utilisateur manipulant le binaire.                  * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +const char *g_loaded_binary_get_username(const GLoadedBinary *binary) +{ +    return binary->username; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary   = élément binaire à consulter.                      * +*                username = nom de l'utilisateur manipulant le binaire.       * +*                                                                             * +*  Description : Définit l'utilisateur analysant le binaire courant.          * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void g_loaded_binary_set_username(GLoadedBinary *binary, const char *username) +{ +    bool changed;                           /* Note les changements        */ + +    changed = (strcmp(binary->username, username) != 0); + +    free(binary->username); +    binary->username = strdup(username); + +    binary->username_changed = changed; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = élément binaire à consulter.                        * +*                host   = nom du serveur distant à contacter. [OUT]           * +*                port   = port de communication avec le serveur distant. [OUT]* +*                                                                             * +*  Description : Identifie le serveur distant associé au binaire courant.     * +*                                                                             * +*  Retour      : Statut de l'utilisation du serveur distant.                  * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool g_loaded_binary_get_remote_server(const GLoadedBinary *binary, const char **host, unsigned short *port) +{ +    *host = binary->remote_host; +    *port = binary->remote_port; + +    return binary->use_remote_server; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = élément binaire à consulter.                        * +*                host   = nom du serveur distant à contacter.                 * +*                port   = port de communication avec le serveur distant.      * +*                use    = statut de l'utilisation du serveur distant.         * +*                                                                             * +*  Description : Définit le serveur distant associé au binaire courant.       * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void g_loaded_binary_set_remote_server(GLoadedBinary *binary, const char *host, unsigned short port, bool use) +{ +    free(binary->remote_host); +    binary->remote_host = strdup(host); + +    binary->remote_port = port; + +    binary->use_remote_server = use; + +    if (use) +        /* TODO : reload conn ! */; +    else +        /* TODO : stop conn ! */; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary  = élément binaire à consulter.                       * +*                feature = fonctionnalité visée par la requête.               * +*                                                                             * +*  Description : Indique la forme d'enregistrement d'une fonctionnalité.      * +*                                                                             * +*  Retour      : Type d'enregistrement sélectionné.                           * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +DBStorage g_loaded_binary_get_storage(const GLoadedBinary *binary, DBFeatures feature) +{ +    return binary->storages[feature]; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary  = élément binaire à consulter.                       * +*                feature = fonctionnalité visée par la requête.               * +*                storage = type d'enregistrement sélectionné.                 * +*                                                                             * +*  Description : Définit la forme d'enregistrement d'une fonctionnalité.      * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void g_loaded_binary_set_storage(GLoadedBinary *binary, DBFeatures feature, DBStorage storage) +{ +    binary->storages[feature] = storage; + +} + + + + + + + + + +  /******************************************************************************  *                                                                             *  *  Paramètres  : binary = élément binaire à consulter.                        * @@ -541,6 +942,18 @@ void g_loaded_binary_analyse(GLoadedBinary *binary)      GBinPart **parts;                       /* Parties d'élément binaire   */      size_t parts_count;                     /* Nombre de ces parties       */ +    /* Détermination de l'identifiant */ + +    binary->checksum = g_checksum_new(G_CHECKSUM_SHA256); +    g_checksum_update(binary->checksum, binary->bin_data, binary->bin_length); + +    /* Contacts avec les serveurs */ + + + + + +      if (binary->parts_count[BPM_ROUTINES] > 0)          binary->model = BPM_ROUTINES; @@ -597,6 +1010,25 @@ const char *g_loaded_binary_get_filename(const GLoadedBinary *binary, bool full)  /******************************************************************************  *                                                                             *  *  Paramètres  : binary = élément binaire à consulter.                        * +*                                                                             * +*  Description : Fournit une empreinte unique (SHA256) pour le binaire.       * +*                                                                             * +*  Retour      : Chaîne représentant l'empreinte du binaire.                  * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +const gchar *g_loaded_binary_get_cheksum(const GLoadedBinary *binary) +{ +    return g_checksum_get_string(binary->checksum); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = élément binaire à consulter.                        *  *                length = taille en octets des données chargées. [OUT]        *  *                                                                             *  *  Description : Fournit les détails du contenu binaire chargé en mémoire.    * diff --git a/src/analysis/binary.h b/src/analysis/binary.h index 073c546..d7bc3e2 100644 --- a/src/analysis/binary.h +++ b/src/analysis/binary.h @@ -29,6 +29,7 @@  #include <stdbool.h> +#include "db/protocol.h"  #include "../arch/processor.h"  #include "../common/xml.h"  #include "../format/executable.h" @@ -81,6 +82,34 @@ GLoadedBinary *g_loaded_binary_new_from_xml(xmlXPathContextPtr, const char *);  /* Ecrit une sauvegarde du binaire dans un fichier XML. */  bool g_loaded_binary_save(const GLoadedBinary *, xmlDocPtr, xmlXPathContextPtr, const char *); + + +/* ------------------------- INFORMATIONS D'ENREGISTREMENTS ------------------------- */ + + +/* Identifie l'utilisateur analysant le binaire courant. */ +const char *g_loaded_binary_get_username(const GLoadedBinary *); + +/* Définit l'utilisateur analysant le binaire courant. */ +void g_loaded_binary_set_username(GLoadedBinary *, const char *); + +/* Identifie le serveur distant associé au binaire courant. */ +bool g_loaded_binary_get_remote_server(const GLoadedBinary *, const char **, unsigned short *); + +/* Définit le serveur distant associé au binaire courant. */ +void g_loaded_binary_set_remote_server(GLoadedBinary *, const char *, unsigned short, bool); + +/* Indique la forme d'enregistrement d'une fonctionnalité. */ +DBStorage g_loaded_binary_get_storage(const GLoadedBinary *, DBFeatures); + +/* Définit la forme d'enregistrement d'une fonctionnalité. */ +void g_loaded_binary_set_storage(GLoadedBinary *, DBFeatures, DBStorage); + + + + + +  /* Définit les parties de binaire à analyser. */  void g_loaded_binary_set_parts(GLoadedBinary *, BinaryPartModel, GBinPart **, size_t); @@ -93,6 +122,9 @@ void g_loaded_binary_analyse(GLoadedBinary *);  /* Fournit le fichier correspondant à l'élément binaire. */  const char *g_loaded_binary_get_filename(const GLoadedBinary *, bool); +/* Fournit une empreinte unique (SHA256) pour le binaire. */ +const gchar *g_loaded_binary_get_cheksum(const GLoadedBinary *); +  /* Fournit les détails du contenu binaire chargé en mémoire. */  bin_t *g_loaded_binary_get_data(const GLoadedBinary *, off_t *); diff --git a/src/analysis/db/Makefile.am b/src/analysis/db/Makefile.am new file mode 100755 index 0000000..ef98a24 --- /dev/null +++ b/src/analysis/db/Makefile.am @@ -0,0 +1,22 @@ + +noinst_LTLIBRARIES  = libanalysisdb.la + +libanalysisdb_la_SOURCES =				\ +	bookmark.h bookmark.c				\ +	cdb.h cdb.c							\ +	client.h client.c					\ +	collection.h collection.c			\ +	core.h core.c						\ +	protocol.h							\ +	server.h server.c + +libanalysisdb_la_LIBADD =	 + +libanalysisdb_la_LDFLAGS =  + + +AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) + +AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) + +SUBDIRS =  diff --git a/src/analysis/db/bookmark.c b/src/analysis/db/bookmark.c new file mode 100644 index 0000000..6327338 --- /dev/null +++ b/src/analysis/db/bookmark.c @@ -0,0 +1,69 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * bookmark.h - prototypes pour la gestion des signets au sein d'un binaire + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "bookmark.h" + + +#include <malloc.h> + + + + + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : db = accès à la base de données.                             * +*                                                                             * +*  Description : Crée la table des signets dans une base de données.          * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool create_bookmark_db_table(sqlite3 *db) +{ +    char *sql;                              /* Requête à exécuter          */ +    int ret;                                /* Bilan de la création        */ +    char *msg;                              /* Message d'erreur            */ + +    sql = "CREATE TABLE Bookmarks ("            \ +             "id INT PRIMARY KEY NOT NULL, "    \ +             "user TEXT NOT NULL, "             \ +             "created INT NOT NULL, "           \ +             "address INT NOT NULL, "           \ +             "comment TEXT"                     \ +          ");"; + +    ret = sqlite3_exec(db, sql, NULL, NULL, &msg); +    if (ret != SQLITE_OK) +    { +        fprintf(stderr, "sqlite3_exec(): %s\n", msg); +        sqlite3_free(msg); +    } + +    return (ret == SQLITE_OK); + +} diff --git a/src/analysis/db/bookmark.h b/src/analysis/db/bookmark.h new file mode 100644 index 0000000..f5a8b37 --- /dev/null +++ b/src/analysis/db/bookmark.h @@ -0,0 +1,41 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * bookmark.h - prototypes pour la gestion des signets au sein d'un binaire + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_BOOKMARK_H +#define _ANALYSIS_DB_BOOKMARK_H + + + +#include <sqlite3.h> +#include <stdbool.h> + + + +/* Crée la table des signets dans une base de données. */ +bool create_bookmark_db_table(sqlite3 *); + + + + + +#endif  /* _ANALYSIS_DB_BOOKMARK_H */ diff --git a/src/analysis/db/cdb.c b/src/analysis/db/cdb.c new file mode 100644 index 0000000..67d4916 --- /dev/null +++ b/src/analysis/db/cdb.c @@ -0,0 +1,602 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * cdb.h - prototypes pour la manipulation des archives au format CDB + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "cdb.h" + + +#include <archive.h> +#include <archive_entry.h> +#include <errno.h> +#include <fcntl.h> +#include <malloc.h> +#include <stdio.h> +#include <sqlite3.h> +#include <string.h> +#include <unistd.h> +#include <sys/stat.h> + + +#include <config.h> + + +#include "bookmark.h" +#include "protocol.h" +#include "../../common/cpp.h" +#include "../../common/extstr.h" +#include "../../common/io.h" +#include "../../common/xdg.h" +#include "../../common/xml.h" + + + +/* Fixe le tampon pour la lecture des fichiers à inclure */ +#define ARCHIVE_RBUF_SIZE 2048 + + +/* Description d'une archive d'éléments utilisateur (instance) */ +struct _GCdbArchive +{ +    GObject parent;                         /* A laisser en premier        */ + +    char hash[65];                          /* Empreinte SHA256            */ + + +    char *filename;                         /* Chemin d'accès à l'archive  */ + +    char *xml_desc;                         /* Fichier de description      */ +    char *sql_db;                           /* Base de données SQLite      */ + +    xmlDocPtr xdoc;                         /* Document XML à créer        */ +    xmlXPathContextPtr context;             /* Contexte pour les recherches*/ + +    sqlite3 *db;                            /* Base de données à manipuler */ + +}; + +/* Description d'une archive d'éléments utilisateur (classe) */ +struct _GCdbArchiveClass +{ +    GObjectClass parent;                    /* A laisser en premier        */ + +}; + + +/* Initialise la classe des archives d'éléments utilisateur. */ +static void g_cdb_archive_class_init(GCdbArchiveClass *); + +/* Initialise une archive d'éléments utilisateur. */ +static void g_cdb_archive_init(GCdbArchive *); + +/* Supprime toutes les références externes. */ +static void g_cdb_archive_dispose(GCdbArchive *); + +/* Procède à la libération totale de la mémoire. */ +static void g_cdb_archive_finalize(GCdbArchive *); + +/* Ouvre une archive avec tous les éléments à conserver. */ +static bool g_cdb_archive_read(GCdbArchive *); + + + + + +/* Crée la description XML correspondant à l'archive. */ +static bool g_cdb_archive_create_xml_desc(GCdbArchive *, const core_db_info *); + + + +/* ------------------------- ACCES A LA BASE DE DONNEES SQL ------------------------- */ + +/* Crée la base de données correspondant à l'archive. */ +static bool g_cdb_archive_create_db(const GCdbArchive *, const core_db_info *); + + + + +/* Indique le type défini pour une une archive d'éléments utilisateur. */ +G_DEFINE_TYPE(GCdbArchive, g_cdb_archive, G_TYPE_OBJECT); + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : klass = classe à initialiser.                                * +*                                                                             * +*  Description : Initialise la classe des archives d'éléments utilisateur.    * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_cdb_archive_class_init(GCdbArchiveClass *klass) +{ +    GObjectClass *object;                   /* Autre version de la classe  */ + +    object = G_OBJECT_CLASS(klass); + +    object->dispose = (GObjectFinalizeFunc/* ! */)g_cdb_archive_dispose; +    object->finalize = (GObjectFinalizeFunc)g_cdb_archive_finalize; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = instance à initialiser.                            * +*                                                                             * +*  Description : Initialise une archive d'éléments utilisateur.               * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_cdb_archive_init(GCdbArchive *archive) +{ + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = instance d'objet GLib à traiter.                   * +*                                                                             * +*  Description : Supprime toutes les références externes.                     * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_cdb_archive_dispose(GCdbArchive *archive) +{ +    G_OBJECT_CLASS(g_cdb_archive_parent_class)->dispose(G_OBJECT(archive)); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = instance d'objet GLib à traiter.                   * +*                                                                             * +*  Description : Procède à la libération totale de la mémoire.                * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_cdb_archive_finalize(GCdbArchive *archive) +{ +    //void close_xml_file(xmlDocPtr, xmlXPathContextPtr); + + + +    G_OBJECT_CLASS(g_cdb_archive_parent_class)->finalize(G_OBJECT(archive)); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : local  = indique si l'enregistrement est local ou non.       * +*                client = flux ouvert en lecture pour les informations utiles.* +*                info   = informations de base associées à la requête.        * +*                                                                             * +*  Description : Définit ou ouvre une archive d'éléments utilisateur.         * +*                                                                             * +*  Retour      : Structure mise en plae ou NULL en cas d'échec.               * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +GCdbArchive *g_cdb_archive_new(bool local, GDbClient *client, const core_db_info *info) +{ +    GCdbArchive *result;                    /* Adresse à retourner         */ +    char *suffix;                           /* Fin du nom de fichier       */ +    struct stat finfo;                      /* Information sur l'archive   */ +    int ret;                                /* Retour d'un appel           */ + +    result = g_object_new(G_TYPE_CDB_ARCHIVE, NULL); + + + +    strcpy(result->hash, info->hash); + + + + +    /* Chemin de l'archive */ + +    suffix = strdup("chrysalide" G_DIR_SEPARATOR_S); +    suffix = stradd(suffix, local ? "local" : "server"); +    suffix = stradd(suffix, G_DIR_SEPARATOR_S); +    suffix = stradd(suffix, result->hash); +    suffix = stradd(suffix, ".tar.xz"); + +    result->filename = get_xdg_config_dir(suffix); + +    free(suffix); + +    if (!mkpath(result->filename)) +        goto gcan_error; + +    /* Chemin des enregistrements temporaires */ + +    result->xml_desc = strdup(g_get_tmp_dir()); + +    if (result->xml_desc[strlen(result->xml_desc) - 1] != G_DIR_SEPARATOR) +        result->xml_desc = stradd(result->xml_desc, G_DIR_SEPARATOR_S); + +    result->xml_desc = stradd(result->xml_desc, result->hash); +    result->xml_desc = stradd(result->xml_desc, "_desc.xml"); + +    result->sql_db = strdup(g_get_tmp_dir()); + +    if (result->sql_db[strlen(result->sql_db) - 1] != G_DIR_SEPARATOR) +        result->sql_db = stradd(result->sql_db, G_DIR_SEPARATOR_S); + +    result->sql_db = stradd(result->sql_db, result->hash); +    result->sql_db = stradd(result->sql_db, "_db.sql"); + +    /* Création de l'archive si elle n'existe pas */ + +    ret = stat(result->filename, &finfo); + +    if (ret != 0) +    { +        /* Le soucis ne vient pas de l'absence du fichier... */ +        if (errno != ENOENT) goto gcan_error; + +        g_cdb_archive_create_xml_desc(result, info); +        g_cdb_archive_create_db(result, info); + +        if (!g_cdb_archive_write(result)) +            goto gcan_error; + +    } +    else if (!S_ISREG(finfo.st_mode)) +        goto gcan_error; + +    /* Ouverture de l'archive */ + +    if (!g_cdb_archive_read(result) && 0) +        goto gcan_error; + +    return result; + + gcan_error: + +    g_object_unref(G_OBJECT(result)); + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = information quant à l'archive à interpréter.       * +*                                                                             * +*  Description : Ouvre une archive avec tous les éléments à conserver.        * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static bool g_cdb_archive_read(GCdbArchive *archive) +{ +    bool result;                            /* Conclusion à retourner      */ +    struct archive *in;                     /* Archive à consulter         */ +    int ret;                                /* Bilan d'un appel            */ +    int flags;                              /* Propriétés à extraire       */ +    struct archive *out;                    /* Extracteur générique        */ +    struct archive_entry *entry;            /* Elément de l'archive        */ +    const char *path;                       /* Désignation d'un fichier    */ + +    result = false; + +    in = archive_read_new(); +    archive_read_support_filter_all(in); +    archive_read_support_format_all(in); + +    ret = archive_read_open_filename(in, archive->filename, 10240 /* ?! */); +    if (ret != ARCHIVE_OK) goto gcar_exit; + +    /* Propriétés à restaurer */ +    flags = ARCHIVE_EXTRACT_TIME; +    flags |= ARCHIVE_EXTRACT_PERM; +    flags |= ARCHIVE_EXTRACT_ACL; +    flags |= ARCHIVE_EXTRACT_FFLAGS; + +    out = archive_write_disk_new(); +    archive_write_disk_set_options(out, flags); +    archive_write_disk_set_standard_lookup(out); + +    for (ret = archive_read_next_header(in, &entry); +         ret == ARCHIVE_OK; +         ret = archive_read_next_header(in, &entry)) +    { +        bool dump_arch_data(struct archive_entry *ent, struct archive *input, struct archive *output) +        { +            const void *buff;               /* Tampon de copie             */ +            size_t size;                    /* Quantité copiée             */ +            __LA_INT64_T offset;            /* Position de lecture         */ + +            ret = archive_write_header(output, entry); +            if (ret != ARCHIVE_OK) return false; + +            for (ret = archive_read_data_block(input, &buff, &size, &offset); +                 ret == ARCHIVE_OK; +                 ret = archive_read_data_block(input, &buff, &size, &offset)) +            { +                ret = archive_write_data_block(output, buff, size, offset); +                if (ret != ARCHIVE_OK) +                    return false; +            } + +            if (ret != ARCHIVE_EOF) +                return false; + +            ret = archive_write_finish_entry(output); + +            return (ret == ARCHIVE_OK); + +        } + +        path = archive_entry_pathname(entry); + +        if (strcmp(path, "desc.xml") == 0) +        { +            archive_entry_set_pathname(entry, archive->xml_desc); + +            if (!dump_arch_data(entry, in, out)) +                goto gcar_exit; + +            if (!open_xml_file(archive->xml_desc, &archive->xdoc, &archive->context)) +                goto gcar_exit; + +        } +        else if (strcmp(path, "sql.db") == 0) +        { +            archive_entry_set_pathname(entry, archive->sql_db); + +            if (!dump_arch_data(entry, in, out)) +                goto gcar_exit; + +            ret = sqlite3_open(archive->sql_db, &archive->db); +            if (ret != SQLITE_OK) +                goto gcar_exit; + +        } + +    } + +    archive_read_close(in); +    archive_read_free(in); + +    archive_write_close(out); +    archive_write_free(out); + +    result = true; + + gcar_exit: + +    return result; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = information quant à l'archive à créer.             * +*                                                                             * +*  Description : Enregistre une archive avec tous les éléments à conserver.   * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool g_cdb_archive_write(const GCdbArchive *archive) +{ +    bool result;                            /* Conclusion à retourner      */ +    struct archive *out;                    /* Archive à constituer        */ +    int ret;                                /* Bilan d'un appel            */ + +    result = false; + +    out = archive_write_new(); +    archive_write_add_filter_xz(out); +    archive_write_set_format_gnutar(out); + +    ret = archive_write_open_filename(out, archive->filename); +    if (ret != ARCHIVE_OK) goto gcaw_exit; + +    bool add_file_to_archive(struct archive *out, const char *src, const char *path) +    { +        struct stat info;                   /* Informations d'origine      */ +        struct archive_entry *entry;        /* Elément de l'archive        */ +        int fd;                             /* Flux ouvert en lecture      */ +        char buffer[ARCHIVE_RBUF_SIZE];     /* Tampon pour les transferts  */ +        ssize_t len;                        /* Quantité de données lues    */ + +        ret = stat(src, &info); +        if (ret != 0) return false; + +        entry = archive_entry_new(); + +        archive_entry_copy_stat(entry, &info); +        archive_entry_set_pathname(entry, path); + +        ret = archive_write_header(out, entry); +        if (ret != 0) goto afta_error; + +        fd = open(src, O_RDONLY); +        if (fd == -1) goto afta_error; + +        for (len = safe_read(fd, buffer, ARCHIVE_RBUF_SIZE); +             len > 0; +             len = safe_read(fd, buffer, ARCHIVE_RBUF_SIZE)) +        { +            if (archive_write_data(out, buffer, len) != len) +                goto afta_error; +        } + +        close(fd); + +        archive_entry_free(entry); + +        return true; + + afta_error: + +        archive_entry_free(entry); + +        return false; + +    } + +    result = add_file_to_archive(out, archive->xml_desc, "desc.xml"); +    result &= add_file_to_archive(out, archive->sql_db, "sql.db"); + + gcaw_exit: + +    archive_write_free(out); + +    return result; + +} + + + + + + + + + +/* --------------------- OPERATIONS DE LECTURE D'UN FICHIER XML --------------------- */ +/* --------------------- OPERATIONS DE LECTURE D'UN FICHIER XML --------------------- */ + + + + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = archive à constituer.                              * +*                info    = informations de base associées à la requête.       * +*                                                                             * +*  Description : Crée la description XML correspondant à l'archive.           * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static bool g_cdb_archive_create_xml_desc(GCdbArchive *archive, const core_db_info *info) +{ +    bool result;                            /* Bilan à retourner           */ +    char tmp[sizeof(STR(ULLONG_MAX))];      /* Stockage temporaire        */ + +    result = create_new_xml_file(&archive->xdoc, &archive->context); +    if (!result) return false; + +    result &= add_content_to_node(archive->xdoc, archive->context, +                                  "/ChrysalideBinary/Version", PACKAGE_VERSION); + +    result &= add_content_to_node(archive->xdoc, archive->context, +                                  "/ChrysalideBinary/Hash", archive->hash); + +    result &= add_content_to_node(archive->xdoc, archive->context, +                                  "/ChrysalideBinary/Creation/Author", "**me**"); + +    snprintf(tmp, sizeof(tmp), "%" PRIu64, (uint64_t)10ull); + +    result &= add_content_to_node(archive->xdoc, archive->context, +                                  "/ChrysalideBinary/Creation/Date", tmp); + +    save_xml_file(archive->xdoc, archive->xml_desc); + +    return result; + +} + + + + + + +/* ---------------------------------------------------------------------------------- */ +/*                           ACCES A LA BASE DE DONNEES SQL                           */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : archive = archive à constituer.                              * +*                info    = informations de base associées à la requête.       * +*                                                                             * +*  Description : Crée la base de données correspondant à l'archive.           * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static bool g_cdb_archive_create_db(const GCdbArchive *archive, const core_db_info *info) +{ +    bool result;                            /* Bilan à retourner           */ +    sqlite3 *db;                            /* Base de données à constituer*/ +    int ret;                                /* Bilan de la création        */ + +    ret = sqlite3_open(archive->sql_db, &db); + +    if (ret != SQLITE_OK) +    { +        fprintf(stderr, "sqlite3_open(): %s\n", sqlite3_errmsg(db)); +        return false; +    } + + + +    result = create_bookmark_db_table(db); + + + +    sqlite3_close(db); + +    return result; + +} diff --git a/src/analysis/db/cdb.h b/src/analysis/db/cdb.h new file mode 100644 index 0000000..46d0f11 --- /dev/null +++ b/src/analysis/db/cdb.h @@ -0,0 +1,62 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * cdb.h - prototypes pour la manipulation des archives au format CDB + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_CDB_H +#define _ANALYSIS_DB_CDB_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "client.h" +#include "core.h" + + + +#define G_TYPE_CDB_ARCHIVE               g_cdb_archive_get_type() +#define G_CDB_ARCHIVE(obj)               (G_TYPE_CHECK_INSTANCE_CAST((obj), g_cdb_archive_get_type(), GCdbArchive)) +#define G_IS_CDB_ARCHIVE(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj), g_cdb_archive_get_type())) +#define G_CDB_ARCHIVE_GET_IFACE(inst)    (G_TYPE_INSTANCE_GET_INTERFACE((inst), g_cdb_archive_get_type(), GCdbArchiveIface)) +#define G_CDB_ARCHIVE_GET_CLASS(obj)     (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_CDB_ARCHIVE, GCdbArchiveClass)) + + +/* Description d'une archive d'éléments utilisateur (instance) */ +typedef struct _GCdbArchive GCdbArchive; + +/* Description d'une archive d'éléments utilisateur (classe) */ +typedef struct _GCdbArchiveClass GCdbArchiveClass; + + +/* Indique le type défini pour une une archive d'éléments utilisateur. */ +GType g_cdb_archive_get_type(void); + +/* Prépare un client pour une connexion à une BD. */ +GCdbArchive *g_cdb_archive_new(bool, GDbClient *, const core_db_info *); + +/* Enregistre une archive avec tous les éléments à conserver. */ +bool g_cdb_archive_write(const GCdbArchive *); + + + +#endif  /* _ANALYSIS_DB_CDB_H */ diff --git a/src/analysis/db/client.c b/src/analysis/db/client.c new file mode 100644 index 0000000..64a4c31 --- /dev/null +++ b/src/analysis/db/client.c @@ -0,0 +1,291 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * client.c - connexion à un serveur Chrysalide + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "client.h" + + +#include <netdb.h> +#include <poll.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/socket.h> + + +#include "protocol.h" + + + +/* Description de client à l'écoute (instance) */ +struct _GDbClient +{ +    GObject parent;                         /* A laisser en premier        */ + +    int fd; +    struct sockaddr_in addr;                /* Adresse d'écoute            */ + +    GThread *update;                        /* Procédure de traitement     */ + +}; + +/* Description de client à l'écoute (classe) */ +struct _GDbClientClass +{ +    GObjectClass parent;                    /* A laisser en premier        */ + +}; + + +/* Initialise la classe des descriptions de fichier binaire. */ +static void g_db_client_class_init(GDbClientClass *); + +/* Initialise une description de fichier binaire. */ +static void g_db_client_init(GDbClient *); + +/* Procède à la libération totale de la mémoire. */ +static void g_db_client_finalize(GDbClient *); + +/* Assure l'accueil des nouvelles mises à jour. */ +static void *g_db_client_update(GDbClient *); + + + +/* Indique le type défini pour une description de client à l'écoute. */ +G_DEFINE_TYPE(GDbClient, g_db_client, G_TYPE_OBJECT); + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : klass = classe à initialiser.                                * +*                                                                             * +*  Description : Initialise la classe des descriptions de fichier binaire.    * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_client_class_init(GDbClientClass *klass) +{ +    GObjectClass *object;                   /* Autre version de la classe  */ + +    object = G_OBJECT_CLASS(klass); + +    object->finalize = (GObjectFinalizeFunc)g_db_client_finalize; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : client = instance à initialiser.                             * +*                                                                             * +*  Description : Initialise une description de fichier binaire.               * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_client_init(GDbClient *client) +{ +    client->fd = -1; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = instance d'objet GLib à traiter.                    * +*                                                                             * +*  Description : Procède à la libération totale de la mémoire.                * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_client_finalize(GDbClient *binary) +{ +    //free(binary->filename); + +    G_OBJECT_CLASS(g_db_client_parent_class)->finalize(G_OBJECT(binary)); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : host = hôte à représenter pour le service.                   * +*                port = port de connexion pour les clients.                   * +*                                                                             * +*  Description : Prépare un client pour une connexion à une BD.               * +*                                                                             * +*  Retour      : Structure mise en plae ou NULL en cas d'échec.               * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +GDbClient *g_db_client_new(const char *host, short port) +{ +    GDbClient *result;                      /* Adresse à retourner         */ +    struct hostent *hp;                     /* Informations sur l'hôte     */ + +    result = g_object_new(G_TYPE_DB_CLIENT, NULL); + +    hp = gethostbyname(host); +    if (hp == NULL) goto gdsn_error; + +    result->addr.sin_family = hp->h_addrtype; +    memcpy(&result->addr.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr)); + +    result->addr.sin_port = htons(port); + +    return result; + + gdsn_error: + +    g_object_unref(G_OBJECT(result)); + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : client = client pour les accès distants à manipuler.         * +*                                                                             * +*  Description : Assure l'accueil des nouvelles mises à jour.                 * +*                                                                             * +*  Retour      : NULL.                                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void *g_db_client_update(GDbClient *client) +{ +    struct pollfd fds;                      /* Surveillance des flux       */ +    int ret;                                /* Bilan d'un appel            */ + +    fds.fd = client->fd; +    fds.events = POLLIN | POLLPRI; + +    while (1) +    { +        ret = poll(&fds, 1, -1); +        if (ret != 1) continue; + +        printf("fds.revents :: %x\n", fds.revents); + +        /* Le canal est fermé, une sortie doit être demandée... */ +        if (fds.revents & POLLNVAL) +            break; + +        if (fds.revents & (POLLIN | POLLPRI)) +        { + +            /* TODO */ +            pause(); + + +        } + +    } + +    g_db_client_stop(client); + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : client = client pour les accès distants à manipuler.         * +*                                                                             * +*  Description : Démarre la connexion à la base de données.                   * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool g_db_client_start(GDbClient *client) +{ +    int ret;                                /* Bilan d'un appel            */ + +    client->fd = socket(AF_INET, SOCK_STREAM, 0); +    if (client->fd == -1) +    { +        perror("socket"); +        return false; +    } + +    ret = connect(client->fd, (struct sockaddr *)&client->addr, sizeof(struct sockaddr_in)); +    if (ret == -1) +    { +        perror("connect"); +        close(client->fd); +        client->fd = -1; +        return false; +    } + +    //client->update = g_thread_new("cdb_listener", (GThreadFunc)g_db_client_update, client); + +    send(client->fd, "A", 1, 0); + +    return true; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : client = client pour les accès distants à manipuler.         * +*                                                                             * +*  Description : Arrête la connexion à la base de données.                    * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void g_db_client_stop(GDbClient *client) +{ +    if (client->fd != -1) +        return; + +    close(client->fd); +    client->fd = -1; + +    g_thread_join(client->update); + +} diff --git a/src/analysis/db/client.h b/src/analysis/db/client.h new file mode 100644 index 0000000..58faa23 --- /dev/null +++ b/src/analysis/db/client.h @@ -0,0 +1,61 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * client.h - prototypes pour la connexion à un serveur Chrysalide + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_CLIENT_H +#define _ANALYSIS_DB_CLIENT_H + + +#include <glib-object.h> +#include <stdbool.h> + + + +#define G_TYPE_DB_CLIENT               g_db_client_get_type() +#define G_DB_CLIENT(obj)               (G_TYPE_CHECK_INSTANCE_CAST((obj), g_db_client_get_type(), GDbClient)) +#define G_IS_DB_CLIENT(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj), g_db_client_get_type())) +#define G_DB_CLIENT_GET_IFACE(inst)    (G_TYPE_INSTANCE_GET_INTERFACE((inst), g_db_client_get_type(), GDbClientIface)) +#define G_DB_CLIENT_GET_CLASS(obj)     (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_DB_CLIENT, GDbClientClass)) + + +/* Description de client à l'écoute (instance) */ +typedef struct _GDbClient GDbClient; + +/* Description de client à l'écoute (classe) */ +typedef struct _GDbClientClass GDbClientClass; + + +/* Indique le type défini pour une description de client à l'écoute. */ +GType g_db_client_get_type(void); + +/* Prépare un client pour une connexion à une BD. */ +GDbClient *g_db_client_new(const char *, short); + +/* Démarre la connexion à la base de données. */ +bool g_db_client_start(GDbClient *); + +/* Arrête la connexion à la base de données. */ +void g_db_client_stop(GDbClient *); + + + +#endif  /* _ANALYSIS_DB_CLIENT_H */ diff --git a/src/analysis/db/collection.c b/src/analysis/db/collection.c new file mode 100644 index 0000000..a310365 --- /dev/null +++ b/src/analysis/db/collection.c @@ -0,0 +1,26 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * collection.c - gestion d'éléments ajoutés par collection + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "collection.h" + + diff --git a/src/analysis/db/collection.h b/src/analysis/db/collection.h new file mode 100644 index 0000000..32d1609 --- /dev/null +++ b/src/analysis/db/collection.h @@ -0,0 +1,30 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * collection.h - prototypes pour la gestion d'éléments ajoutés par collection + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_COLLECTION_H +#define _ANALYSIS_DB_COLLECTION_H + + + + +#endif  /* _ANALYSIS_DB_COLLECTION_H */ diff --git a/src/analysis/db/core.c b/src/analysis/db/core.c new file mode 100644 index 0000000..8b06ac0 --- /dev/null +++ b/src/analysis/db/core.c @@ -0,0 +1,205 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * core.c - prototypes pour les informations de base pour tout élément ajouté + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "core.h" + + +#include <endian.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + + +#include "../../common/io.h" + + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : -                                                            * +*                                                                             * +*  Description : Détermine une fois pour toute la désignation de l'usager.    * +*                                                                             * +*  Retour      : Nom statique déterminé.                                      * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +const char *get_local_author_name(void) +{ +    static char result[MAX_DB_AUTHOR_LEN];  /* Désignation à retourner     */ +    char *chrysalide_user;                  /* Eventuel nom spécifique     */ +    char *logname;                          /* Nom depuis l'environnement  */ +    char hostname[HOST_NAME_MAX];           /* Nom de la machine courante  */ +    int ret;                                /* Bilan d'un appel            */ + +    if (result[0] == '\0') +    { +        chrysalide_user = getenv("CHRYSALIDE_USER"); + +        if (chrysalide_user != NULL) +        { +            strncpy(result, chrysalide_user, MAX_DB_AUTHOR_LEN - 1); +            result[MAX_DB_AUTHOR_LEN - 1] = '\0'; +        } +        else +        { +            logname = getenv("LOGNAME"); +            if (logname == NULL) +                logname = ""; + +            ret = gethostname(hostname, HOST_NAME_MAX); +            if (ret != 0) +                hostname[0] = '\0'; + +            if (logname != NULL && hostname[0] != '\0') +                snprintf(result, MAX_DB_AUTHOR_LEN, "%s@%s", logname, hostname); + +            else if (logname != NULL && hostname[0] == '\0') +                snprintf(result, MAX_DB_AUTHOR_LEN, "%s", logname); + +            else if (logname == NULL && hostname[0] != '\0') +                snprintf(result, MAX_DB_AUTHOR_LEN, "@%s", hostname); + +            else +                snprintf(result, MAX_DB_AUTHOR_LEN, "anonymous"); + +        } + +    } + +    return result; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : info = informations à constituer. [OUT]                      * +*                type = type de l'élément à mettre en place.                  * +*                user = provenance des informations ou NULL si machine.       * +*                                                                             * +*  Description : Initialise le coeur des informations d'un élément ajouté.    * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void init_core_db_info(core_db_info *info, uint64_t type, const char *user) +{ +    info->type = type; + +    strncpy(info->user, user, MAX_DB_AUTHOR_LEN - 1); +    info->user[MAX_DB_AUTHOR_LEN - 1] = '\0'; + +    info->created = time(NULL); +    info->modified = info->created; + +    info->saved = 0; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : info = informations à constituer. [OUT]                      * +*                type = type de l'élément, lu en avance de phase.             * +*                fd   = flux ouvert en lecture pour l'importation.            * +*                                                                             * +*  Description : Importe le coeur des informations d'un élément ajouté.       * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool load_core_db_info(core_db_info *info, uint64_t type, int fd) +{ +    ssize_t got;                            /* Quantité de données reçues  */ +    uint64_t val64;                         /* Valeur sur 64 bits          */ + +    info->type = type; + +    got = safe_recv(fd, info->user, MAX_DB_AUTHOR_LEN, MSG_WAITALL); +    if (got != MAX_DB_AUTHOR_LEN) return false; + +    info->user[MAX_DB_AUTHOR_LEN - 1] = '\0'; + +    got = safe_recv(fd, &val64, sizeof(uint64_t), MSG_WAITALL); +    if (got != sizeof(uint64_t)) return false; + +    info->created = be64toh(val64); + +    got = safe_recv(fd, &val64, sizeof(uint64_t), MSG_WAITALL); +    if (got != sizeof(uint64_t)) return false; + +    info->modified = be64toh(val64); + +    info->saved = info->modified; + +    return true; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : info = informations à sauvegarer.                            * +*                fd   = flux ouvert en écriture pour l'exportation.           * +*                                                                             * +*  Description : Exporte le coeur des informations d'un élément ajouté.       * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool store_core_db_info(core_db_info *info, int fd) +{ +    ssize_t got;                            /* Quantité de données reçues  */ + +    got = safe_send(fd, (uint64_t []) { htobe64(info->type) }, sizeof(uint64_t), MSG_WAITALL); +    if (got != sizeof(uint64_t)) return false; + +    got = safe_send(fd, info->user, MAX_DB_AUTHOR_LEN, MSG_WAITALL); +    if (got != MAX_DB_AUTHOR_LEN) return false; + +    got = safe_send(fd, (uint64_t []) { htobe64(info->created) }, sizeof(uint64_t), MSG_WAITALL); +    if (got != sizeof(uint64_t)) return false; + +    got = safe_send(fd, (uint64_t []) { htobe64(info->modified) }, sizeof(uint64_t), MSG_WAITALL); +    if (got != sizeof(uint64_t)) return false; + +    info->saved = time(NULL); + +    return true; + +} diff --git a/src/analysis/db/core.h b/src/analysis/db/core.h new file mode 100644 index 0000000..d3f4e3d --- /dev/null +++ b/src/analysis/db/core.h @@ -0,0 +1,70 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * core.h - prototypes pour les informations de base pour tout élément ajouté + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_CORE_H +#define _ANALYSIS_DB_CORE_H + + +#include <inttypes.h> +#include <stdbool.h> + + + +/** + * Taille maximale pour un nom d'auteur. + * On considère comme exemple large '"Nom Prénom" xxx@yyy.tld' + */ +#define MAX_DB_AUTHOR_LEN 128 + + +/* Informations de base pour tout élément ajouté */ +typedef struct _core_db_info +{ +    uint64_t type;                          /* Type de l'élément           */ +    char hash[65];                          /* Empreinte SHA256            */ + +    char user[MAX_DB_AUTHOR_LEN];           /* Auteur humain ou NULL       */ + +    uint64_t created;                       /* Date de création            */ +    uint64_t modified;                      /* Date de modification        */ + +    uint64_t saved;                         /* Statut de l'élément         */ + +} core_db_info; + + +/* Détermine une fois pour toute la désignation de l'usager. */ +const char *get_local_author_name(void); + +/* Initialise le coeur des informations d'un élément ajouté. */ +void init_core_db_info(core_db_info *, uint64_t, const char *); + +/* Importe le coeur des informations d'un élément ajouté. */ +bool load_core_db_info(core_db_info *, uint64_t, int); + +/* Exporte le coeur des informations d'un élément ajouté. */ +bool store_core_db_info(core_db_info *, int); + + + +#endif  /* _ANALYSIS_DB_CORE_H */ diff --git a/src/analysis/db/protocol.h b/src/analysis/db/protocol.h new file mode 100644 index 0000000..9614abc --- /dev/null +++ b/src/analysis/db/protocol.h @@ -0,0 +1,71 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * protocol.h - prototypes pour la description du protocole impactant les BD Chrysalide + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_PROTOCOL_H +#define _ANALYSIS_DB_PROTOCOL_H + + + +/** + * Nombre maximal de connexions à un serveur. + * cf. listen(). + */ +#define CDB_SEVER_BACKLOG 100 + +/** + * Délai maximal de réaction pour les coupures de flux (en ms). + */ +#define CDB_CONN_TIMEOUT 1000 + + + + + +/* Fonctionnalités offertes */ +typedef enum _DBFeatures +{ +    DBF_COMMENTS,                           /* Commentaires ajoutés        */ +    DBF_SEGMENTS_DISPLAY,                   /* Choix d'affichage           */ +    DBF_BOOKMARKS,                          /* Signets dans le code        */ + +    DBF_COUNT + +} DBFeatures; + +/* Comportement vis à vis des éléments */ +typedef enum _DBStorage +{ +    DBS_ALL_LOCAL           = 0x01,         /* Enregistrements locaux      */ +    DBS_ALL_REMOTE          = 0x02,         /* Enregistrements distants    */ +    DBS_LOCAL_AND_REMOTE    = 0x03,         /* Enreg. locaux + infos dists.*/ + +    DBS_MAX = 3 + +} DBStorage; + + + + + + +#endif  /* _ANALYSIS_DB_PROTOCOL_H */ diff --git a/src/analysis/db/server.c b/src/analysis/db/server.c new file mode 100644 index 0000000..b636d02 --- /dev/null +++ b/src/analysis/db/server.c @@ -0,0 +1,426 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * server.c - mise en place d'un fournisseur d'éléments ajoutés + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "server.h" + + +#include <malloc.h> +#include <netdb.h> +#include <poll.h> +#include <string.h> +#include <unistd.h> +#include <sys/socket.h> + + +#include "protocol.h" + + + +/* Informations relatives à un client */ +typedef struct _cdb_client +{ +    GDbServer *server;                      /* Accès facile en mémoire     */ + +    int fd;                                 /* Canal de communication      */ +    struct sockaddr_in peer;                /* Adresse distante            */ + +    GThread *thread;                        /* Procédure de traitement     */ + +} cdb_client; + +/* Description de serveur à l'écoute (instance) */ +struct _GDbServer +{ +    GObject parent;                         /* A laisser en premier        */ + +    int fd; +    struct sockaddr_in addr;                /* Adresse d'écoute            */ + +    GThread *listener;                      /* Procédure de traitement     */ + +    cdb_client **clients;                   /* Connexions en place         */ +    size_t count;                           /* Quantité de clients         */ +    GMutex mutex;                           /* Verrou pour l'accès         */ + +}; + +/* Description de serveur à l'écoute (classe) */ +struct _GDbServerClass +{ +    GObjectClass parent;                    /* A laisser en premier        */ + +}; + + +/* Initialise la classe des descriptions de fichier binaire. */ +static void g_db_server_class_init(GDbServerClass *); + +/* Initialise une description de fichier binaire. */ +static void g_db_server_init(GDbServer *); + +/* Procède à la libération totale de la mémoire. */ +static void g_db_server_finalize(GDbServer *); + +/* Assure l'accueil des nouveaux clients. */ +static void *g_db_server_listener(GDbServer *); + +/* Assure le traitement des requêtes de clients. */ +static void *g_db_server_process(cdb_client **); + + + +/* Indique le type défini pour une description de serveur à l'écoute. */ +G_DEFINE_TYPE(GDbServer, g_db_server, G_TYPE_OBJECT); + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : klass = classe à initialiser.                                * +*                                                                             * +*  Description : Initialise la classe des descriptions de fichier binaire.    * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_server_class_init(GDbServerClass *klass) +{ +    GObjectClass *object;                   /* Autre version de la classe  */ + +    object = G_OBJECT_CLASS(klass); + +    object->finalize = (GObjectFinalizeFunc)g_db_server_finalize; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : server = instance à initialiser.                             * +*                                                                             * +*  Description : Initialise une description de fichier binaire.               * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_server_init(GDbServer *server) +{ +    server->fd = -1; + +    g_mutex_init(&server->mutex); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : binary = instance d'objet GLib à traiter.                    * +*                                                                             * +*  Description : Procède à la libération totale de la mémoire.                * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void g_db_server_finalize(GDbServer *binary) +{ +    //free(binary->filename); + +    G_OBJECT_CLASS(g_db_server_parent_class)->finalize(G_OBJECT(binary)); + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : host = hôte à représenter pour le service.                   * +*                port = port de connexion pour les clients.                   * +*                                                                             * +*  Description : Prépare un serveur de BD pour les clients.                   * +*                                                                             * +*  Retour      : Structure mise en plae ou NULL en cas d'échec.               * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +GDbServer *g_db_server_new(const char *host, short port) +{ +    GDbServer *result;                      /* Adresse à retourner         */ +    struct hostent *hp;                     /* Informations sur l'hôte     */ + +    result = g_object_new(G_TYPE_DB_SERVER, NULL); + +    hp = gethostbyname(host); +    if (hp == NULL) goto gdsn_error; + +    result->addr.sin_family = hp->h_addrtype; +    memcpy(&result->addr.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr)); + +    result->addr.sin_port = htons(port); + +    return result; + + gdsn_error: + +    g_object_unref(G_OBJECT(result)); + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : server = serveur pour les accès distants à manipuler.        * +*                                                                             * +*  Description : Assure l'accueil des nouveaux clients.                       * +*                                                                             * +*  Retour      : NULL.                                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void *g_db_server_listener(GDbServer *server) +{ +    struct pollfd fds;                      /* Surveillance des flux       */ +    int ret;                                /* Bilan d'un appel            */ +    struct sockaddr_in peer;                /* Adresse cliente             */ +    int fd;                                 /* Canal établi vers un client */ +    cdb_client *client;                     /* Mémorisation pour poursuite */ + +    fds.fd = server->fd; +    fds.events = POLLIN | POLLPRI; + +    while (1) +    { +        ret = poll(&fds, 1, -1); +        if (ret != 1) continue; + +        /* Le canal est fermé, une sortie doit être demandée... */ +        if (fds.revents & POLLNVAL) +            break; + +        if (fds.revents & (POLLIN | POLLPRI)) +        { +            fd = accept(server->fd, &peer, (socklen_t []) { sizeof(struct sockaddr_in) }); +            if (fd == -1) continue; + +            g_mutex_lock(&server->mutex); + +            client = (cdb_client *)calloc(1, sizeof(cdb_client)); + +            g_object_ref(G_OBJECT(server)); +            client->server = server; + +            client->fd = fd; +            client->peer = peer; + +            server->clients = (cdb_client **)realloc(server->clients, +                                                     ++server->count * sizeof(cdb_client *)); +            server->clients[server->count - 1] = client; + +            client->thread = g_thread_new("cdb_process", (GThreadFunc)g_db_server_process, +                                          &server->clients[server->count - 1]); + +            g_mutex_unlock(&server->mutex); + +        } + +    } + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : client = informations sur une connexion établie à utiliser.  * +*                                                                             * +*  Description : Assure le traitement des requêtes de clients.                * +*                                                                             * +*  Retour      : NULL.                                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +static void *g_db_server_process(cdb_client **client) +{ +    struct pollfd fds;                      /* Surveillance des flux       */ +    int ret;                                /* Bilan d'un appel            */ +    GDbServer *server;                      /* Accès facile en mémoire     */ +    size_t index;                           /* Indice courant du client    */ +    size_t remaining;                       /* Quantité à déplacer         */ + +    fds.fd = (*client)->fd; +    fds.events = POLLIN | POLLPRI; + +    while (1) +    { +        ret = poll(&fds, 1, -1); +        if (ret != 1) continue; + +        printf("fds.revents :: %x\n", fds.revents); + +        /* Le canal est fermé, une sortie doit être demandée... */ +        if (fds.revents & POLLNVAL) +            break; + +        if (fds.revents & (POLLIN | POLLPRI)) +        { + +            /* TODO */ +            pause(); + + +        } + +    } + +    /* Retrait de la liste avant la terminaison */ + +    server = (*client)->server; + +    g_mutex_lock(&server->mutex); + +    index = (client - server->clients); +    remaining = server->count - index - 1; + +    if (remaining > 0) +        memmove(&server->clients[index], &server->clients[index + 1], +                remaining * sizeof(cdb_client *)); + +    g_object_unref(G_OBJECT(server)); + +    free(*client); + +    g_mutex_unlock(&server->mutex); + +    return NULL; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : server = serveur pour les accès distants à manipuler.        * +*                                                                             * +*  Description : Démarre le serveur de base de données.                       * +*                                                                             * +*  Retour      : Bilan de l'opération.                                        * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +bool g_db_server_start(GDbServer *server) +{ +    int ret;                                /* Bilan d'un appel            */ + +    server->fd = socket(AF_INET, SOCK_STREAM, 0); +    if (server->fd == -1) +    { +        perror("socket"); +        return false; +    } + +    ret = setsockopt(server->fd, SOL_SOCKET, SO_REUSEADDR, (int []) { 1 }, sizeof(int)); +    if (ret == -1) +    { +        perror("setsockopt"); +        close(server->fd); +        server->fd = -1; +        return false; +    } + +    ret = bind(server->fd, (struct sockaddr *)&server->addr, sizeof(struct sockaddr_in)); +    if (ret == -1) +    { +        perror("bind"); +        close(server->fd); +        server->fd = -1; +        return false; +    } + +    ret = listen(server->fd, CDB_SEVER_BACKLOG); +    if (ret == -1) +    { +        perror("listen"); +        close(server->fd); +        server->fd = -1; +        return false; +    } + +    server->listener = g_thread_new("cdb_listener", (GThreadFunc)g_db_server_listener, server); + +    return true; + +} + + +/****************************************************************************** +*                                                                             * +*  Paramètres  : server = serveur pour les accès distants à manipuler.        * +*                                                                             * +*  Description : Arrête le serveur de base de données.                        * +*                                                                             * +*  Retour      : -                                                            * +*                                                                             * +*  Remarques   : -                                                            * +*                                                                             * +******************************************************************************/ + +void g_db_server_stop(GDbServer *server) +{ +    size_t i;                               /* Boucle de parcours          */ +    GThread *thread;                        /* Procédure de traitement     */ + +    if (server->fd != -1) +        return; + +    close(server->fd); +    server->fd = -1; + +    g_thread_join(server->listener); + +    for (i = 0; i < server->count; i++) +    { +        /* Sauvegarde de la référene, qui peut disparaître */ +        thread = server->clients[i]->thread; + +        close(server->clients[i]->fd); +        g_thread_join(thread); + +    } + +} diff --git a/src/analysis/db/server.h b/src/analysis/db/server.h new file mode 100644 index 0000000..e470a8f --- /dev/null +++ b/src/analysis/db/server.h @@ -0,0 +1,61 @@ + +/* OpenIDA - Outil d'analyse de fichiers binaires + * server.h - prototypes pour la mise en place d'un fournisseur d'éléments ajoutés + * + * Copyright (C) 2014 Cyrille Bagard + * + *  This file is part of OpenIDA. + * + *  OpenIDA is free software; you can redistribute it and/or modify + *  it under the terms of the GNU General Public License as published by + *  the Free Software Foundation; either version 3 of the License, or + *  (at your option) any later version. + * + *  OpenIDA 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 Foobar.  If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_SERVER_H +#define _ANALYSIS_DB_SERVER_H + + +#include <glib-object.h> +#include <stdbool.h> + + + +#define G_TYPE_DB_SERVER               g_db_server_get_type() +#define G_DB_SERVER(obj)               (G_TYPE_CHECK_INSTANCE_CAST((obj), g_db_server_get_type(), GDbServer)) +#define G_IS_DB_SERVER(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj), g_db_server_get_type())) +#define G_DB_SERVER_GET_IFACE(inst)    (G_TYPE_INSTANCE_GET_INTERFACE((inst), g_db_server_get_type(), GDbServerIface)) +#define G_DB_SERVER_GET_CLASS(obj)     (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_DB_SERVER, GDbServerClass)) + + +/* Description de serveur à l'écoute (instance) */ +typedef struct _GDbServer GDbServer; + +/* Description de serveur à l'écoute (classe) */ +typedef struct _GDbServerClass GDbServerClass; + + +/* Indique le type défini pour une description de serveur à l'écoute. */ +GType g_db_server_get_type(void); + +/* Prépare un serveur de BD pour les clients. */ +GDbServer *g_db_server_new(const char *, short); + +/* Démarre le serveur de base de données. */ +bool g_db_server_start(GDbServer *); + +/* Arrête le serveur de base de données. */ +void g_db_server_stop(GDbServer *); + + + +#endif  /* _ANALYSIS_DB_SERVER_H */ | 
