summaryrefslogtreecommitdiff
path: root/src/analysis/db/server.c
blob: 3d75b716ca70654547dfd07a960db4c504c911fb (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

/* Chrysalide - 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 Chrysalide.
 *
 *  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"
#include "../../gui/panels/log.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;                                 /* Canal de communication      */
    char *hostname;                         /* Désignation humaine         */
    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  : server = 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 *server)
{
    free(server->hostname);

    G_OBJECT_CLASS(g_db_server_parent_class)->finalize(G_OBJECT(server));

}


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

    result->hostname = strdup(host);

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

    log_variadic_message(LMT_PROCESS, _("Server started and listening at %s:%hu"),
                         server->hostname, ntohs(server->addr.sin_port));

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

    }

}