summaryrefslogtreecommitdiff
path: root/src/analysis/db/cdb.c
blob: 78f2aa8ca6a1759d43f33b732cc4c0203ead41fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

/* 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 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 <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 <config.h>


#include "collection.h"
#include "protocol.h"
#include "../../common/cpp.h"
#include "../../common/extstr.h"
#include "../../common/io.h"
#include "../../common/pathname.h"
#include "../../common/xml.h"
#include "../../core/collections.h"



/* Fixe le tampon pour la lecture des fichiers à inclure */
#define ARCHIVE_RBUF_SIZE 2048





/* Informations relatives à un client */
typedef struct _cdb_client
{
    int 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 *);






/* 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)
{
    //void close_xml_file(xmlDocPtr, xmlXPathContextPtr);

    free(archive->filename);


    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         */
    struct stat finfo;                      /* Information sur l'archive   */
    int ret;                                /* Retour d'un appel           */

    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, ".tar.xz");

    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.data);
    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.data);
    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, 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_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            */
    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 = 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            */

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

    DBError add_file_to_archive(struct archive *out, const char *src, const char *path)
    {
        DBError status;                     /* Bilan à renvoyer            */
        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    */

        status = DBE_ARCHIVE_ERROR;

        ret = stat(src, &info);
        if (ret != 0) return DBE_SYS_ERROR;

        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)
        {
            status = DBE_SYS_ERROR;
            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 DBE_NONE;

 afta_error:

        archive_entry_free(entry);

        return status;

    }

    result = add_file_to_archive(out, archive->xml_desc, "desc.xml");

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

 gcaw_exit:

    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 = send_packed_buffer(&pbuf, archive->clients[i].fd);

    g_mutex_unlock(&archive->clients_access);

    exit_packed_buffer(&pbuf);

    if (!status)
        goto occ_error;


    printf("CHANGED for %d clients !!\n", (int)archive->count);



 occ_error:

    /* TODO : close() */
    ;

}


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

    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 = (struct pollfd *)realloc(fds, nfds * sizeof(struct pollfd));

        for (i = 0; i < nfds; i++)
        {
            fds[i].fd = archive->clients[i].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_bad_exchange;

            /* Données présentes en entrée */
            if (fds[i].revents & (POLLIN | POLLPRI))
            {
                status = recv_packed_buffer(&in_pbuf, fds[i].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 = send_packed_buffer(&out_pbuf, fds[i].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;

                        printf("## CDB ## Got something for collection %p...\n", collec);

                        //GDbCollection *find_collection_in_list(GList *, uint32_t);

                        //static GGenConfig *find_collection_in_list(GList *list, uint32_t id)

                        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:
                        printf("bad command :: 0x%08x\n", command);
                        goto gcap_bad_exchange;
                        break;

                }

                exit_packed_buffer(&in_pbuf);

                continue;

 gcap_bad_reply:

                exit_packed_buffer(&out_pbuf);

 gcap_bad_exchange:

                printf("Bad exchange...\n");

                exit_packed_buffer(&in_pbuf);

                /* TODO : close conn */

                ;


            }

        }

    }

    /* 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      : Indication d'une éventuelle erreur lors de l'opération.      *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

DBError g_cdb_archive_add_client(GCdbArchive *archive, int fd, const rle_string *user)
{

    GList *iter;                            /* Boucle de parcours          */
    GDbCollection *collec;                  /* Collection visée manipulée  */
    volatile pthread_t *process_id;         /* Identifiant de la procédure */

    packed_buffer out_pbuf;                 /* Tampon d'émission           */
    bool status;                            /* Bilan d'un envoi de retour  */



    printf("Add '%s' for archive...\n", user->data);


    g_mutex_lock(&archive->clients_access);

    /* Ajout dans la liste officielle */

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

    archive->clients[archive->count - 1].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);

    /* Envoi des mises à jour au nouveau client... */

    init_packed_buffer(&out_pbuf);

    status = true;


    /* TODO : lock ? */

    for (iter = g_list_first(archive->collections);
         iter != NULL && status;
         iter = g_list_next(iter))
    {
        collec = G_DB_COLLECTION(iter->data);

        status = g_db_collection_pack_all_updates(collec, &out_pbuf);

    }

    if (status)
        status = send_packed_buffer(&out_pbuf, fd);

    exit_packed_buffer(&out_pbuf);



    return DBE_NONE;    ////

}