/* Chrysalide - Outil d'analyse de fichiers binaires
 * cdb.h - prototypes pour la manipulation des archives au format CDB
 *
 * Copyright (C) 2014-2017 Cyrille Bagard
 *
 *  This file is part of Chrysalide.
 *
 *  Chrysalide 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.
 *
 *  Chrysalide 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 Chrysalide.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "cdb.h"


#include <assert.h>
#include <errno.h>
#include <malloc.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>


#include <i18n.h>
#include <config.h>


#include "collection.h"
#include "protocol.h"
#include "../../common/compression.h"
#include "../../common/cpp.h"
#include "../../common/extstr.h"
#include "../../common/pathname.h"
#include "../../common/xml.h"
#include "../../core/collections.h"
#include "../../core/logs.h"
#include "../../core/params.h"



/* Informations relatives à un client */
typedef struct _cdb_client
{
    SSL *ssl_fd;                            /* Canal de communication      */
    rle_string user;                        /* Utilisateur à l'autre bout  */

    uint64_t last_time;                     /* Date de dernier envoi       */

} cdb_client;


/* Description d'une archive d'éléments utilisateur (instance) */
struct _GCdbArchive
{
    GObject parent;                         /* A laisser en premier        */

    rle_string hash;                        /* Empreinte cryptographique   */

    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 */

    GList *collections;                     /* Ensemble de modifications   */

    cdb_client *clients;                    /* Connexions en place         */
    size_t count;                           /* Quantité de clients         */
    GMutex clients_access;                  /* Verrou pour l'accès         */

    GThread *process;                       /* Procédure de traitement     */
    GMutex id_access;                       /* Accès à l'identifiant       */
    GCond id_cond;                          /* Condition d'attente         */
    pthread_t process_id;                   /* Identifiant de la procédure */

};

/* 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 *);



/* -------------------------- MANIPULATION DES PARTIES XML -------------------------- */


/* Crée la description XML correspondant à l'archive. */
static bool g_cdb_archive_create_xml_desc(GCdbArchive *, const rle_string *);

/* Vérifie la conformité d'une description XML avec le serveur. */
static bool g_cdb_archive_check_xml_version(const GCdbArchive *);



/* ------------------------- 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 *);



/////////////////////////:


/* Crée et remplit les collections à partir de leurs bases. */
static bool g_cdb_archive_load_collections(GCdbArchive *);

/* Réagit à une modification au sein d'une collection donnée. */
static void on_collection_changed(GDbCollection *, DBAction, GDbItem *, GCdbArchive *);

/* Assure le traitement des requêtes de clients. */
static void *g_cdb_archive_process(GCdbArchive *);

/* Dissocie un utilisateur de l'archive. */
static void g_cdb_archive_remove_client(GCdbArchive *, size_t);





/* 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)
{
    archive->collections = create_collections_list();

    g_mutex_init(&archive->clients_access);

    g_mutex_init(&archive->id_access);
    g_cond_init(&archive->id_cond);

}


/******************************************************************************
*                                                                             *
*  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_cond_clear(&archive->id_cond);
    g_mutex_clear(&archive->id_access);

    g_mutex_clear(&archive->clients_access);

    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)
{
    int ret;                                /* Bilan d'un appel            */

    if (archive->db != NULL)
    {
        ret = sqlite3_close(archive->db);
        assert(ret == SQLITE_OK);
    }

    if (archive->xdoc != NULL)
        close_xml_file(archive->xdoc, archive->context);

    if (archive->xml_desc != NULL)
    {
        ret = unlink(archive->xml_desc);
        if (ret != 0) perror("unlink");

        free(archive->xml_desc);

    }

    if (archive->sql_db != NULL)
    {
        ret = unlink(archive->sql_db);
        if (ret != 0) perror("unlink");

        free(archive->sql_db);

    }

    free(archive->filename);

    exit_rle_string(&archive->hash);

    G_OBJECT_CLASS(g_cdb_archive_parent_class)->finalize(G_OBJECT(archive));

}


/******************************************************************************
*                                                                             *
*  Paramètres  : basedir = répertoire de stockage des enregistrements.        *
*                hash    = empreinte du binaire à représenter.                *
*                user    = désignation d'un éventuel nouveau créateur.        *
*                error   = indication éventuelle en cas d'échec. [OUT]        *
*                                                                             *
*  Description : Définit ou ouvre une archive d'éléments utilisateur.         *
*                                                                             *
*  Retour      : Structure mise en plae ou NULL en cas d'échec.               *
*                                                                             *
*  Remarques   : Les chaînes sont assurées d'être non vides ; la procédure    *
*                assume un transfert de propriété.                            *
*                                                                             *
******************************************************************************/

GCdbArchive *g_cdb_archive_new(const char *basedir, const rle_string *hash, const rle_string *user, DBError *error)
{
    GCdbArchive *result;                    /* Adresse à retourner         */
    const char *tmpdir;                     /* Répertoire d'accueil        */
    bool status;                            /* Bilan d'un consultation     */
    int ret;                                /* Retour d'un appel           */
    struct stat finfo;                      /* Information sur l'archive   */

    result = g_object_new(G_TYPE_CDB_ARCHIVE, NULL);

    dup_into_rle_string(&result->hash, get_rle_string(hash));

    /* Chemin de l'archive */

    result->filename = strdup(basedir);
    result->filename = stradd(result->filename, G_DIR_SEPARATOR_S);
    result->filename = stradd(result->filename, hash->data);
    result->filename = stradd(result->filename, ".cdb.tar.xz");

    if (!mkpath(result->filename))
        goto gcan_error;

    /* Chemin des enregistrements temporaires */

    status = g_generic_config_get_value(get_main_configuration(), MPK_TMPDIR, &tmpdir);
    if (!status) goto gcan_no_tmp;

    ret = asprintf(&result->xml_desc, "%s" G_DIR_SEPARATOR_S "%s_desc.xml", tmpdir, result->hash.data);
    if (ret == -1) goto gcan_no_tmp;

    ret = ensure_path_exists(result->xml_desc);
    if (ret == -1) goto gcan_no_tmp;

    ret = asprintf(&result->sql_db, "%s" G_DIR_SEPARATOR_S "%s_db.sql", tmpdir, result->hash.data);
    if (ret == -1) goto gcan_no_tmp;

    /* 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, user);
        g_cdb_archive_create_db(result);

        *error = g_cdb_archive_write(result);

        if (*error != DBE_NONE)
            goto gcan_error;

    }
    else if (!S_ISREG(finfo.st_mode))
        goto gcan_error;

    /* Ouverture de l'archive */

    if (!g_cdb_archive_read(result))
        goto gcan_error;

    if (!g_cdb_archive_check_xml_version(result))
    {
        *error = DBE_XML_VERSION_ERROR;
        goto gcan_error;
    }

    /* Chargement des éléments sauvegardés */

    if (!g_cdb_archive_load_collections(result))
    {
        *error = DBE_DB_LOADING_ERROR;
        goto gcan_error;
    }

    return result;

 gcan_no_tmp:

 gcan_error:

    g_object_unref(G_OBJECT(result));

    return NULL;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = informations 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            */
    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_bad_archive;

    for (ret = archive_read_next_header(in, &entry);
         ret == ARCHIVE_OK;
         ret = archive_read_next_header(in, &entry))
    {
        path = archive_entry_pathname(entry);

        if (strcmp(path, "desc.xml") == 0)
        {
            if (!dump_archive_entry_into_file(in, entry, archive->xml_desc))
                goto gcar_exit;

            if (!open_xml_file(archive->xml_desc, &archive->xdoc, &archive->context))
                goto gcar_exit;

        }
        else if (strcmp(path, "sql.db") == 0)
        {
            if (!dump_archive_entry_into_file(in, entry, archive->sql_db))
                goto gcar_exit;

            ret = sqlite3_open(archive->sql_db, &archive->db);
            if (ret != SQLITE_OK)
                goto gcar_exit;

        }

    }

    if (ret != ARCHIVE_EOF)
        goto gcar_exit;

    result = true;

 gcar_exit:

 gcar_bad_archive:

    archive_read_close(in);
    archive_read_free(in);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = informations quant à l'archive à créer.            *
*                                                                             *
*  Description : Enregistre une archive avec tous les éléments à conserver.   *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

DBError g_cdb_archive_write(const GCdbArchive *archive)
{
    DBError result;                         /* Conclusion à retourner      */
    struct archive *out;                    /* Archive à constituer        */
    int ret;                                /* Bilan d'un appel            */
    CPError status;                         /* Bilan d'une compression     */

    result = DBE_ARCHIVE_ERROR;

    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_bad_archive;

    status = add_file_into_archive(out, archive->xml_desc, "desc.xml");

    switch (status)
    {
        case CPE_NO_ERROR:
            result = DBE_NONE;
            break;

        case CPE_SYSTEM_ERROR:
            result = DBE_SYS_ERROR;
            break;

        case CPE_ARCHIVE_ERROR:
            result = DBE_ARCHIVE_ERROR;
            break;

    }

    if (result == DBE_NONE)
    {
        status = add_file_into_archive(out, archive->sql_db, "sql.db");

        switch (status)
        {
            case CPE_NO_ERROR:
                result = DBE_NONE;
                break;

            case CPE_SYSTEM_ERROR:
                result = DBE_SYS_ERROR;
                break;

            case CPE_ARCHIVE_ERROR:
                result = DBE_ARCHIVE_ERROR;
                break;

        }

    }

 gcaw_bad_archive:

    archive_write_close(out);
    archive_write_free(out);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = informations quant à l'archive à consulter.        *
*                hash    = empreinte extérieure à comparer.                   *
*                                                                             *
*  Description : Détermine si une empreinte correspond à celle d'une archive. *
*                                                                             *
*  Retour      : Résultat de la comparaison : -1, 0 ou 1.                     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

int g_cdb_archive_compare_hash(const GCdbArchive *archive, const rle_string *hash)
{
    return cmp_rle_string(&archive->hash, hash);

}



/* ---------------------------------------------------------------------------------- */
/*                            MANIPULATION DES PARTIES XML                            */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive à constituer.                              *
*                user    = désignation d'un éventuel nouveau créateur.        *
*                                                                             *
*  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 rle_string *user)
{
    bool result;                            /* Bilan à retourner           */
    timestamp_t timestamp;                  /* Date de création            */
    char tmp[sizeof(XSTR(UINT64_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/Protocol", XSTR(CDB_PROTOCOL_VERSION));

    result &= add_content_to_node(archive->xdoc, archive->context,
                                  "/ChrysalideBinary/Hash", archive->hash.data);

    result &= add_content_to_node(archive->xdoc, archive->context,
                                  "/ChrysalideBinary/Creation/Author", user->data);

    init_timestamp(&timestamp);
    snprintf(tmp, sizeof(tmp), "%" PRIu64, timestamp);

    result &= add_content_to_node(archive->xdoc, archive->context,
                                  "/ChrysalideBinary/Creation/Date", tmp);

    save_xml_file(archive->xdoc, archive->xml_desc);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive à consulter.                               *
*                                                                             *
*  Description : Vérifie la conformité d'une description XML avec le serveur. *
*                                                                             *
*  Retour      : Bilan de la vérification.                                    *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool g_cdb_archive_check_xml_version(const GCdbArchive *archive)
{
    bool result;                            /* Bilan à retourner           */
    char *version;                          /* Version protocolaire        */
    unsigned long int used;                 /* Version utilisée            */

    result = NULL;

    version = get_node_text_value(archive->context, "/ChrysalideBinary/Protocol");
    if (version == NULL) return false;

    used = strtoul(version, NULL, 16);

    result = (used == CDB_PROTOCOL_VERSION);

    free(version);

    return result;

}


/* ---------------------------------------------------------------------------------- */
/*                           ACCES A LA BASE DE DONNEES SQL                           */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive à constituer.                              *
*                                                                             *
*  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)
{
    bool result;                            /* Bilan à retourner           */
    sqlite3 *db;                            /* Base de données à constituer*/
    int ret;                                /* Bilan de la création        */
    GList *iter;                            /* Boucle de parcours          */
    GDbCollection *collec;                  /* Collection visée manipulée  */

    ret = sqlite3_open(archive->sql_db, &db);

    if (ret != SQLITE_OK)
    {
        fprintf(stderr, "sqlite3_open(): %s\n", sqlite3_errmsg(db));
        return false;
    }

    result = true;

    for (iter = g_list_first(archive->collections);
         iter != NULL && result;
         iter = g_list_next(iter))
    {
        collec = G_DB_COLLECTION(iter->data);
        result = g_db_collection_create_db_table(collec, db);
    }

    sqlite3_close(db);

    return result;

}












/* ---------------------------------------------------------------------------------- */
/*                           ACCES A LA BASE DE DONNEES SQL                           */
/*                           ACCES A LA BASE DE DONNEES SQL                           */
/* ---------------------------------------------------------------------------------- */






/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive dont les collections sont à initialiser.   *
*                                                                             *
*  Description : Crée et remplit les collections à partir de leurs bases.     *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool g_cdb_archive_load_collections(GCdbArchive *archive)
{
    GList *iter;                            /* Boucle de parcours          */
    GDbCollection *collec;                  /* Collection visée manipulée  */

    for (iter = g_list_first(archive->collections);
         iter != NULL;
         iter = g_list_next(iter))
    {
        collec = G_DB_COLLECTION(iter->data);
        g_signal_connect(collec, "content-changed", G_CALLBACK(on_collection_changed), archive);

        if (!g_db_collection_load_all_items(collec, archive->db))
            return false;

    }

    return true;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : collec  = collection dont le contenu a évolué.               *
*                action  = type d'évolution rencontrée.                       *
*                item    = élément ajouté, modifié ou supprimé.               *
*                archive = centralisation de tous les savoirs.                *
*                                                                             *
*  Description : Réagit à une modification au sein d'une collection donnée.   *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void on_collection_changed(GDbCollection *collec, DBAction action, GDbItem *item, GCdbArchive *archive)
{
    packed_buffer pbuf;                     /* Tampon d'émission           */
    size_t i;                               /* Boucle de parcours          */
    bool status;                            /* Bilan d'un envoi de retour  */

    init_packed_buffer(&pbuf);

    status = g_db_collection_pack(collec, &pbuf, action, item);

    g_mutex_lock(&archive->clients_access);

    for (i = 0; i < archive->count && status; i++)
    {
        status = ssl_send_packed_buffer(&pbuf, archive->clients[i].ssl_fd);

        if (!status)
            LOG_ERROR(LMT_ERROR, _("Failed to send some DB update"));

    }

    g_mutex_unlock(&archive->clients_access);

    exit_packed_buffer(&pbuf);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = centralisation de tous les savoirs.                *
*                                                                             *
*  Description : Assure le traitement des requêtes de clients.                *
*                                                                             *
*  Retour      : NULL.                                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void *g_cdb_archive_process(GCdbArchive *archive)
{
    struct pollfd *fds;                     /* Surveillance des flux       */
    nfds_t nfds;                            /* Quantité de ces flux        */
    nfds_t i;                               /* Boucle de parcours          */
    int ret;                                /* Bilan d'un appel            */
    packed_buffer in_pbuf;                  /* Tampon de réception         */
    uint32_t tmp32;                         /* Valeur sur 32 bits          */
    bool status;                            /* Bilan de lecture initiale   */
    uint32_t command;                       /* Commande de la requête      */
    DBError error;                          /* Bilan d'une opération       */
    packed_buffer out_pbuf;                 /* Tampon d'émission           */
    GDbCollection *collec;                  /* Collection visée au final   */
    char *msg;                              /* Erreur à faire remonter     */

    void interrupt_poll_with_sigusr1(int sig) { };

    signal(SIGUSR1, interrupt_poll_with_sigusr1);

    g_mutex_lock(&archive->id_access);
    archive->process_id = pthread_self();
    g_cond_signal(&archive->id_cond);
    g_mutex_unlock(&archive->id_access);

    fds = NULL;

    while (1)
    {
        /* Reconstitution d'une liste à jour */

        g_mutex_lock(&archive->clients_access);

        nfds = archive->count;
        fds = realloc(fds, nfds * sizeof(struct pollfd));

        for (i = 0; i < nfds; i++)
        {
            fds[i].fd = SSL_get_fd(archive->clients[i].ssl_fd);
            fds[i].events = POLLIN | POLLPRI;
        }

        g_mutex_unlock(&archive->clients_access);

        if (nfds == 0)
            goto gcap_no_more_clients;

        /* Lancement d'une phase de surveillance */

        ret = poll(fds, nfds, -1);
        if (ret == -1)
        {
            if (errno == EINTR) continue;

            perror("poll");
            break;

        }

        /* Traitement des requêtes reçues */

        for (i = 0; i < nfds; i++)
        {
            /* Le canal est fermé, une sortie doit être demandée... */
            if (fds[i].revents & POLLNVAL)
                goto gcap_closed_exchange;

            /* Données présentes en entrée */
            if (fds[i].revents & (POLLIN | POLLPRI))
            {
                init_packed_buffer(&in_pbuf);

                status = ssl_recv_packed_buffer(&in_pbuf, archive->clients[i].ssl_fd);
                if (!status) goto gcap_bad_exchange;

                status = extract_packed_buffer(&in_pbuf, &tmp32, sizeof(uint32_t), true);
                if (!status) goto gcap_bad_exchange;

                command = tmp32;

                switch (command)
                {
                    case DBC_SAVE:

                        error = g_cdb_archive_write(archive);

                        init_packed_buffer(&out_pbuf);

                        status = extend_packed_buffer(&out_pbuf, (uint32_t []) { DBC_SAVE },
                                                      sizeof(uint32_t), true);
                        if (!status) goto gcap_bad_reply;

                        status = extend_packed_buffer(&out_pbuf, (uint32_t []) { error }, sizeof(uint32_t), true);
                        if (!status) goto gcap_bad_reply;

                        status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].ssl_fd);
                        if (!status) goto gcap_bad_reply;

                        exit_packed_buffer(&out_pbuf);

                        break;

                    case DBC_COLLECTION:

                        status = extract_packed_buffer(&in_pbuf, &tmp32, sizeof(uint32_t), true);
                        if (!status) goto gcap_bad_exchange;

                        collec = find_collection_in_list(archive->collections, tmp32);
                        if (collec == NULL) goto gcap_bad_exchange;

                        status = g_db_collection_unpack(collec, &in_pbuf, archive->db);
                        if (!status) goto gcap_bad_exchange;

                        break;

                    case DBC_GET_ALL_ITEMS:

                        init_packed_buffer(&out_pbuf);

                        status = extend_packed_buffer(&out_pbuf, (uint32_t []) { DBC_SET_ALL_ITEMS },
                                                      sizeof(uint32_t), true);
                        if (!status) goto gcap_bad_reply;

                        status = pack_all_collection_updates(archive->collections, &out_pbuf);
                        if (!status) goto gcap_bad_reply;

                        status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].ssl_fd);
                        if (!status) goto gcap_bad_reply;

                        exit_packed_buffer(&out_pbuf);

                        break;

                    case DBC_SET_ALL_ITEMS:
                        asprintf(&msg, _("This command is not available on this side: 0x%08x"), command);
                        LOG_ERROR(LMT_ERROR, msg);
                        free(msg);
                        goto gcap_bad_exchange;
                        break;

                    case DBC_SET_LAST_ACTIVE:

                        status = update_activity_in_collections(archive->collections, &in_pbuf, archive->db);
                        if (!status) goto gcap_bad_exchange;

                        break;

                    default:
                        asprintf(&msg, _("Bad protocol command: 0x%08x"), command);
                        LOG_ERROR(LMT_ERROR, msg);
                        free(msg);
                        goto gcap_bad_exchange;
                        break;

                }

                exit_packed_buffer(&in_pbuf);

                continue;

 gcap_bad_reply:

                exit_packed_buffer(&out_pbuf);

 gcap_bad_exchange:

                LOG_ERROR(LMT_ERROR, _("Bad exchange"));

                exit_packed_buffer(&in_pbuf);

 gcap_closed_exchange:

                g_cdb_archive_remove_client(archive, i);

            }

        }

    }

    /* On disparaît des écrans... */

 gcap_no_more_clients:

    archive->process = NULL;

    g_mutex_lock(&archive->id_access);
    archive->process_id = 0;
    g_cond_signal(&archive->id_cond);
    g_mutex_unlock(&archive->id_access);

    if (fds != NULL)
        free(fds);

    return NULL;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive à connecter avec un utilisateur.           *
*                fd      = canal de communication réseau ouvert.              *
*                user    = désignation de l'utilisateur associé.              *
*                                                                             *
*  Description : Associe un nouvel utilisateur à l'archive.                   *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void g_cdb_archive_add_client(GCdbArchive *archive, SSL *fd, const rle_string *user)
{
    volatile pthread_t *process_id;         /* Identifiant de la procédure */

    /**
     * La situation est un peu compliquée lors de l'accueil d'un nouveau client :
     *
     *    - soit on envoie tous les éléments à prendre en compte, mais on doit
     *      bloquer la base de données jusqu'à l'intégration pleine et entière
     *      du client, afin que ce dernier ne loupe pas l'envoi d'un nouvel
     *      élément entre temps.
     *
     *    - soit on intègre le client et celui ci demande des mises à jour
     *      collection par collection ; c'est également à lui qui revient le rejet
     *      des éléments envoyés en solitaires avant la réception de la base
     *      complète.
     *
     * On fait le choix du second scenario ici, du fait de la difficulté
     * de maîtriser facilement la reconstitution d'une liste de clients dans
     * g_cdb_archive_process() depuis un autre flot d'exécution.
     */

    /* Ajout dans la liste officielle */

    g_mutex_lock(&archive->clients_access);

    archive->clients = realloc(archive->clients, ++archive->count * sizeof(cdb_client));

    archive->clients[archive->count - 1].ssl_fd = fd;
    dup_into_rle_string(&archive->clients[archive->count - 1].user, get_rle_string(user));

    /* Démarrage ou redémarrage du processus d'écoute */

    if (archive->process == NULL)
    {
        archive->process = g_thread_new("cdb_process", (GThreadFunc)g_cdb_archive_process, archive);

        /* On attend que le processus parallèle soit prêt */

        process_id = &archive->process_id;

        g_mutex_lock(&archive->id_access);
        while (process_id == 0)
            g_cond_wait(&archive->id_cond, &archive->id_access);
        g_mutex_unlock(&archive->id_access);

    }
    else
        pthread_kill(archive->process_id, SIGUSR1);

    g_mutex_unlock(&archive->clients_access);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : archive = archive à connecter avec un utilisateur.           *
*                index   = indice de l'utilisateur concerné.                  *
*                                                                             *
*  Description : Dissocie un utilisateur de l'archive.                        *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_cdb_archive_remove_client(GCdbArchive *archive, size_t index)
{
    cdb_client *client;                     /* Client à traiter            */

    client = &archive->clients[index];

    g_mutex_lock(&archive->clients_access);

    SSL_free(client->ssl_fd);
    exit_rle_string(&client->user);

    if ((index + 1) < archive->count)
        memmove(&archive->clients[index], &archive->clients[index + 1],
                (archive->count - index - 1) * sizeof(cdb_client));

    archive->clients = realloc(archive->clients, --archive->count * sizeof(cdb_client));

    g_mutex_unlock(&archive->clients_access);

}