summaryrefslogtreecommitdiff
path: root/src/common/io.c
blob: e5ea4374e26bf4ba50b312a173e2b319e9280614 (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

/* Chrysalide - Outil d'analyse de fichiers binaires
 * io.c - entrées sorties fiables
 *
 * Copyright (C) 2014-2019 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 "io.h"


#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <malloc.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>


#include "../core/logs.h"
#include "../core/params.h"



/******************************************************************************
*                                                                             *
*  Paramètres  : fd    = flux ouvert en lecture.                              *
*                buf   = données à recevoir.                                  *
*                count = quantité de ces données.                             *
*                                                                             *
*  Description : Lit des données depuis un flux local.                        *
*                                                                             *
*  Retour      : true si toutes les données ont été lues, false sinon.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool safe_read(int fd, void *buf, size_t count)
{
    uint8_t *iter;                          /* Données en attente          */
    size_t remaining;                       /* Quantité restante           */
    ssize_t got;                            /* Données envoyées            */

    iter = (uint8_t *)buf;
    remaining = count;

    while (remaining > 0)
    {
        got = read(fd, iter, remaining);

        if (got == -1)
        {
            if (errno == EINTR) continue;
            else
            {
                perror("read");
                break;
            }
        }

        if (got == 0)
            break;

        iter += got;
        remaining -= got;

    }

    return (remaining == 0);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : fd  = flux ouvert en lecture.                                *
*                buf = données à recevoir.                                    *
*                max = quantité maximale de ces données.                      *
*                                                                             *
*  Description : Lit des données depuis un flux local.                        *
*                                                                             *
*  Retour      : Nombre d'octets lus, au pire 0 en cas d'erreur.              *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

ssize_t safe_read_partial(int fd, void *buf, size_t max)
{
    ssize_t result;                         /* Quantité lue à remonter     */
    uint8_t *iter;                          /* Données en attente          */
    size_t remaining;                       /* Quantité restante           */
    ssize_t got;                            /* Données envoyées            */

    result = 0;

    iter = (uint8_t *)buf;
    remaining = max;

    while (remaining > 0)
    {
        got = read(fd, iter, remaining);

        if (got == -1)
        {
            if (errno == EINTR) continue;
            else
            {
                perror("read");
                break;
            }
        }

        if (got == 0)
            break;

        result += got;

        iter += got;
        remaining -= got;

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : fd    = flux ouvert en écriture.                             *
*                buf   = données à émettre.                                   *
*                count = quantité de ces données.                             *
*                                                                             *
*  Description : Ecrit des données dans un flux local.                        *
*                                                                             *
*  Retour      : true si toutes les données ont été écrites, false sinon.     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool safe_write(int fd, const void *buf, size_t count)
{
    uint8_t *iter;                          /* Données en attente          */
    size_t remaining;                       /* Quantité restante           */
    ssize_t sent;                           /* Données envoyées            */

    iter = (uint8_t *)buf;
    remaining = count;

    while (remaining > 0)
    {
        sent = write(fd, iter, remaining);

        if (sent == -1)
        {
            if (errno == EINTR) continue;
            else
            {
                perror("write");
                break;
            }
        }

        if (sent == 0)
            break;

        iter += sent;
        remaining -= sent;

    }

    return (remaining == 0);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : sockfd = flux ouvert en lecture.                             *
*                buf    = données à recevoir.                                 *
*                len    = quantité de ces données.                            *
*                flags  = options de réception.                               *
*                                                                             *
*  Description : Réceptionne des données depuis un flux réseau.               *
*                                                                             *
*  Retour      : true si toutes les données ont été reçues, false sinon.      *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool safe_recv(int sockfd, void *buf, size_t len, int flags)
{
    uint8_t *iter;                          /* Données en attente          */
    size_t remaining;                       /* Quantité restante           */
    ssize_t got;                            /* Données envoyées            */

    iter = buf;
    remaining = len;

    while (remaining > 0)
    {
        got = recv(sockfd, iter, remaining, MSG_NOSIGNAL | flags);
        if (got == -1)
        {
            if (errno == EINTR) continue;
            else
            {
                perror("recv");
                break;
            }
        }

        iter += got;
        remaining -= got;

    }

    return (remaining == 0);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : sockfd = flux ouvert en écriture.                            *
*                buf    = données à émettre.                                  *
*                len    = quantité de ces données.                            *
*                flags  = options d'envoi.                                    *
*                                                                             *
*  Description : Envoie des données au travers un flux réseau.                *
*                                                                             *
*  Retour      : true si toutes les données ont été émises, false sinon.      *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool safe_send(int sockfd, const void *buf, size_t len, int flags)
{
    uint8_t *iter;                          /* Données en attente          */
    size_t remaining;                       /* Quantité restante           */
    ssize_t sent;                           /* Données envoyées            */

    iter = (uint8_t *)buf;
    remaining = len;

    while (remaining > 0)
    {
        sent = send(sockfd, iter, remaining, MSG_NOSIGNAL | flags);
        if (sent == -1)
        {
            if (errno == EINTR) continue;
            else
            {
                perror("send");
                break;
            }
        }

        iter += sent;
        remaining -= sent;

    }

    return (remaining == 0);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : path = chemin d'accès à valider.                             *
*                                                                             *
*  Description : S'assure qu'un chemin donné existe dans le système.          *
*                                                                             *
*  Retour      : 0 si le chemin est actuellement présent, -1 sinon.           *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

int ensure_path_exists(const char *path)
{
    int result;                             /* Bilan de l'assurance        */
    char *copy;                             /* Chemin libérable            */
    char *tmp;                              /* Chemin altérable            */

    copy = strdup(path);
    tmp = dirname(copy);

    result = access(tmp, W_OK | X_OK);

    if (result != 0)
    {
        result = ensure_path_exists(tmp);

        if (result == 0)
            result = mkdir(tmp, 0700);

    }

    free(copy);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : prefix   = préfixe du nom du fichier temporaire à créer.     *
*                suffix   = éventuel suffixe à coller au nom de fichier.      *
*                filename = chemin d'accès complet au nouveau fichier. [OUT]  *
*                                                                             *
*  Description : Met en place un fichier temporaire.                          *
*                                                                             *
*  Retour      : Flux ouvert en lecture et écriture, ou -1 en cas d'erreur.   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

int make_tmp_file(const char *prefix, const char *suffix, char **filename)
{
    int result;                             /* Flux ou code à retourner    */
    const char *tmpdir;                     /* Répertoire d'accueil        */
    bool status;                            /* Bilan d'un consultation     */
    size_t slen;                            /* Taille du suffixe           */

    status = g_generic_config_get_value(get_main_configuration(), MPK_TMPDIR, &tmpdir);
    if (!status) return -1;

    slen = strlen(suffix);

    if (slen > 0)
        asprintf(filename, "%s" G_DIR_SEPARATOR_S "%s-%d.XXXXXX.%s", tmpdir, prefix, getpid(), suffix);
    else
        asprintf(filename, "%s" G_DIR_SEPARATOR_S "%s-%d.XXXXXX", tmpdir, prefix, getpid());

    result = ensure_path_exists(*filename);

    if (result == 0)
    {
        if (slen > 0)
            result = mkstemps(*filename, strlen(suffix) + 1);
        else
            result = mkstemp(*filename);

        if (result == -1) perror("mkstemp");

    }

    if (result == -1)
    {
        free(*filename);
        *filename = NULL;
    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : dest = fichier de destination de la copie.                   *
*                src  = fichier source à copier.                              *
*                                                                             *
*  Description : Copie un fichier.                                            *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool copy_file(const char *dest, const char *src)
{
    bool result;                            /* Bilan à retourner           */
    int fd;                                 /* Descripteur du fichier      */
    struct stat info;                       /* Informations sur le fichier */
    int ret;                                /* Bilan d'un appel            */
    void *data;                             /* Quantité de données traitées*/
    bool status;                            /* Bilan de la lecture         */

    result = false;

    /* Côté source */

    fd = open(src, O_RDONLY);
    if (fd == -1)
    {
        LOG_ERROR_N("open");
        goto exit;
    }

    ret = fstat(fd, &info);
    if (ret == -1)
    {
        LOG_ERROR_N("fstat");
        goto done;
    }

    data = malloc(info.st_size);

    status = safe_read(fd, data, info.st_size);
    if (!status) goto clean;

    close(fd);

    /* Côté destination */

    fd = open(dest, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    if (fd == -1)
    {
        LOG_ERROR_N("open");
        free(data);
        goto exit;
    }

    status = safe_write(fd, data, info.st_size);
    if (!status) goto clean;

    result = true;

 clean:

    free(data);

 done:

    close(fd);

 exit:

    return result;

}