summaryrefslogtreecommitdiff
path: root/cleopatre/application/libspid/src/system.c
blob: 8ea1836ba5e018458025b8d9c5c6ef5f69009b2a (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
/* SPC300 bundle {{{
 *
 * Copyright (C) 2009 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    application/libspid/src/system.c
 * \brief   system functions
 * \ingroup libspid
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <syslog.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#ifndef __UTESTS__
#include <mtd/mtd-user.h>
#endif
#include "libspid.h"

typedef int file_lock_t;

/**
 * Lock a file.
 * \param  filename  the name of the file.
 * \param  create  whether to create the file if it doesn't exist.
 * \param  lock  the lock.
 * \return  LIBSPID_SUCCESS, on success.
 *          LIBSPID_ERROR_NOT_FOUND, if the specified file doesn't exist and
 *              the create parameter was set to false.
 *          LIBSPID_ERROR_PARAM, on bad input parameters.
 *          LIBSPID_ERROR_SYSTEM, on error.
 */
static libspid_error_t
libspid_system_file_lock (const char *filename, libspid_boolean_t create, file_lock_t *lock)
{
    if ((NULL == filename) || (NULL == lock))
    {
        return LIBSPID_ERROR_PARAM;
    }

    mode_t mode = S_IRUSR | S_IWUSR;

    int flags = O_RDWR;
    if (create == LIBSPID_TRUE)
    {
        flags |= O_CREAT;
    }

    int fd = open (filename, flags, mode); /* if O_CREAT is not specified in
                                              flags,then mode is ignored. */
    if (fd == -1)
    {
        /* Save errno. */
        int save_errno = errno;

        syslog (LOG_ERR, "open(): %m");

        if (save_errno == ENOENT)
        {
            assert (!create);
            return LIBSPID_ERROR_NOT_FOUND;
        }
        else
        {
            return LIBSPID_ERROR_SYSTEM;
        }
    }

    /* flock() is used instead of lockf() or fcntl() because with those two,
     * the lock is removed whenever the process closes a file descriptor to
     * the locked file, even if it's not the fd used when locking.
     * So here, calling libspid_config_read_line() or
     * libspid_config_write_line() while holding a lock would release the lock.
     * Which is not what is expected.
     * By using flock(), the lock is not released when closing the fd in
     * libspid_config_read_line() or libspid_config_write_line(). */
    if (flock (fd, LOCK_EX) == -1)
    {
        syslog (LOG_ERR, "flock(lock): %m");

        if (close (fd) == -1)
        {
            syslog (LOG_ERR, "close(): %m");
        }
        return LIBSPID_ERROR_SYSTEM;
    }

    *lock = fd;

    return LIBSPID_SUCCESS;
}

/**
 * Unlock a file.
 * \param  lock  the lock obtained when locking the file.
 * \return  LIBSPID_SUCCES, on success.
 *          LIBSPID_ERROR_PARAM, on bad input parameters.
 *          LIBSPID_ERROR_SYSTEM, on error.
 */
static int
libspid_system_file_unlock (const file_lock_t *lock)
{
    if (NULL == lock)
    {
        return LIBSPID_ERROR_PARAM;
    }

    int fd = *lock;

    if (flock (fd, LOCK_UN) == -1)
    {
        syslog (LOG_ERR, "flock(unlock): %m");

        return LIBSPID_ERROR_SYSTEM;
    }

    if (close (fd) == -1)
    {
        syslog (LOG_ERR, "close(): %m");

        return LIBSPID_ERROR_SYSTEM;
    }

    return LIBSPID_SUCCESS;
}

/**
 * Give the current Linux OS version inside a provided buffer.
 *
 * \param buffer buffer where to put the result
 * \param buffer_len length of buffer where to put the result
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NO_SPACE: no enough space in buffer
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */


libspid_error_t
libspid_system_get_kernel_version (char *buffer, int buffer_len)
{
    FILE *fp;
    char line_buffer[LIBSPID_CONFIG_LINE_MAX_LEN];
    unsigned int len = 0;
    unsigned int total = 0;

    if (buffer == NULL || buffer_len <= 0)
        return LIBSPID_ERROR_PARAM;

    /* initialize buffer  - important for strcat to work properly */
    memset (buffer, 0x0, buffer_len);

    fp = fopen (LIBSPID_SYSTEM_VERSION_PATH, "r");
    if (fp != NULL)
    {
        while (fgets(line_buffer, LIBSPID_CONFIG_LINE_MAX_LEN - 1, fp))
        {
            /* check for buffer overload */
            len = strlen (line_buffer);
            total += len;
            if (total > buffer_len)
                return LIBSPID_ERROR_NO_SPACE;

            strcat (buffer, line_buffer);
        }

        fclose (fp);
    }
    else
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    return LIBSPID_SUCCESS;
}

/**
 * Give the current PLC driver version inside a provided buffer.
 *
 * \param buffer buffer where to put the result
 * \param buffer_len length of buffer where to put the result
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NO_SPACE: no enough space in buffer
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_get_plc_version (char *buffer, const int buffer_len)
{
    return LIBSPID_SUCCESS;
}

/**
 * Give the current AV stack version inside a provided buffer.
 *
 * \param buffer buffer where to put the result
 * \param buffer_len length of buffer where to put the result
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NO_SPACE: no enough space in buffer
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_get_av_version (char *buffer, const int buffer_len)
{
    return LIBSPID_SUCCESS;
}

/**
 * Give the time spent since the system has started.<BR>
 * Results are in 'seconds'.
 *
 * \param total_s total time in seconds since system start
 * \param idle_s total time of processor idle state since system
 * start
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_get_uptime (unsigned int *total_s, unsigned int *idle_s)
{
    FILE *fp;
    char buf[LIBSPID_CONFIG_LINE_MAX_LEN];
    int res;
    unsigned int uptotal = 0;
    unsigned int upidle = 0;
    unsigned int dummy1, dummy2; /* we use dummy vars to take decimal parts */

    if (total_s == NULL || idle_s == NULL)
        return LIBSPID_ERROR_PARAM;
    /*
       /proc/uptime    <--- we will read uptime info from this file
       This file contains information detailing how long the system
       has been on since its last restart. The output of /proc/uptime is quite minimal:

       350735.47 234388.90

       The first number is the total number of seconds the system has been up.
       The second number is how much of that time the machine has spent idle, in seconds.
     */
    fp = fopen (LIBSPID_SYSTEM_UPTIME_PATH, "r");
    if (fp != NULL)
    {
        if (fgets (buf, LIBSPID_CONFIG_LINE_MAX_LEN - 1, fp) != NULL)
        {
            /* we cannot scanf %lf, we do not have double or float type on our ARM */
            res = sscanf (buf, "%d.%d %d.%d", &uptotal, &dummy1, &upidle, &dummy2);
            /* check if all 4 values were read */
            if (res != 4)
            {
                fclose (fp);
                return LIBSPID_ERROR_SYSTEM;
            }
        }

        fclose (fp);
    }

    *total_s = uptotal;
    *idle_s = upidle;

    return LIBSPID_SUCCESS;
}

/**
 * Get the current memory status of the system. All results are
 * put into the same provided buffer.
 *
 * \param buffer buffer where the result is put
 * \param buffer_len size of provided buffer
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 * \return LIBSPID_ERROR_NO_SPACE: not enough space in buffer
 */
libspid_error_t
libspid_system_get_meminfo (char *buffer, int buffer_len)
{
    FILE *fp;
    char line_buffer[LIBSPID_CONFIG_LINE_MAX_LEN];
    unsigned int len = 0;
    unsigned int total = 0;

    if (buffer == NULL || buffer_len <= 0)
        return LIBSPID_ERROR_PARAM;

    /* initialize buffer  - important for strcat to work properly */
    memset (buffer, 0x0, buffer_len);

    fp = fopen (LIBSPID_SYSTEM_MEMINFO_PATH, "r");
    if (fp != NULL)
    {
        while (fgets(line_buffer, LIBSPID_CONFIG_LINE_MAX_LEN - 1, fp))
        {
            /* check for buffer overload */
            len = strlen (line_buffer);
            total += len;
            if (total > buffer_len)
                return LIBSPID_ERROR_NO_SPACE;

            strcat (buffer, line_buffer);
        }

        fclose (fp);
    }
    else
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    return LIBSPID_SUCCESS;
}

/**
 * Reboot the whole system.
 *
 */

void
libspid_system_reboot(void)
{
    system ("reboot");
}

/**
 * Save the system configuration files into the user ffs.
 *
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_save(void)
{
    FILE *fp;
    char *ptr, filename[128], *dirptr, tmpbuf[128], command_buffer[256],        mkdir_buffer[256];
    int rc = 0;
    char prefix[16] = {0};
    struct stat st;

    /* create save.lst file if it is not present already */
    if (stat(LIBSPID_SAVE_LIST_PATH, &st) != 0)
    {
        sprintf (command_buffer, "touch %s", LIBSPID_SAVE_LIST_PATH);
        rc = system (command_buffer);
        if (rc != 0)
            return LIBSPID_ERROR_SYSTEM;
    }

    if ((fp = fopen (LIBSPID_SAVE_LIST_PATH, "r")) == NULL)
    {
        //syslog(LOG_WARNING, "libspid_save_config: cannot open %s (errno=%d)", LIBSPID_SAVE_LIST_PATH, errno);
        return LIBSPID_ERROR_SYSTEM;
    }
    /* check for /usr/local/etc validity */
    sprintf (mkdir_buffer, "mkdir -p %s", LIBSPID_CONF_SAVE_PATH);
    rc = system (mkdir_buffer);
    if (rc != 0)
    {
        fclose (fp);
        return LIBSPID_ERROR_SYSTEM;
    }

    while (fgets (filename, 127, fp))
    {
        if (strlen (filename) > 0)
        {
            filename[strlen(filename) - 1] = '\0';
        }
        /* check if the line in cnf file is /etc/<name> or just <name> */
        sprintf (prefix, "%s/", LIBSPID_CONF_ROOT_PATH);
        if (!strncmp (filename, prefix, strlen (prefix)))
            ptr = filename + strlen (prefix);
        else
            ptr = filename;
        if (0 == strlen (ptr))
        {
            continue;
        }
        strcpy (tmpbuf, ptr);
        dirptr = dirname (tmpbuf);
        sprintf (command_buffer, "mkdir -p %s/%.64s", LIBSPID_CONF_SAVE_PATH,
                 dirptr);
        rc = system (command_buffer);
        sprintf (command_buffer, "cp -a %s/%.64s %s/%s", LIBSPID_CONF_ROOT_PATH,
                 ptr, LIBSPID_CONF_SAVE_PATH, dirptr);
        rc = system (command_buffer);
        if (rc !=0)
        {
            fclose (fp);
            return LIBSPID_ERROR_SYSTEM;
        }
    }
    fclose (fp);
    /* make sure that all *.conf files have been copied, even new ones not in save.lst */
    sprintf (command_buffer, "cp -a %s/*.conf %s", LIBSPID_CONF_ROOT_PATH,
             LIBSPID_CONF_SAVE_PATH);
    rc = system (command_buffer);
    if (rc !=0)
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    return LIBSPID_SUCCESS;
}

/**
 * Save a configuration file inside the user ffs.
 *
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad parameter
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_save_file (const char *filename)
{
    char command_buffer[256], *dirptr, tmpbuf[128];
    int rc = 0;

    if (filename == NULL)
    {
        return LIBSPID_ERROR_PARAM;
    }
    strcpy (tmpbuf, filename);
    dirptr = dirname (tmpbuf);

    sprintf (command_buffer, "mkdir -p %s%s", LIBSPID_SAVE_DIR_PATH,
             dirptr);
    rc = system (command_buffer);
    sprintf (command_buffer, "cp -a %s %s%s", filename, LIBSPID_SAVE_DIR_PATH,
             dirptr);
    rc = system (command_buffer);
    if (rc != 0)
    {
        return LIBSPID_ERROR_SYSTEM;
    }
    return LIBSPID_SUCCESS;
}

/**
 * Restore the system into the factory configuration.
 *
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_factory (void)
{
    int rc;
    char cmd[256] = {0};

    sprintf (cmd, "rm -rf %s/*", LIBSPID_CONF_SAVE_PATH);
    rc = system (cmd);
    if (rc != 0)
        return LIBSPID_ERROR_SYSTEM;

    //syslog("libspid_factory: returned to factory default");
    return LIBSPID_SUCCESS;
}

/**
 * Get the NVRAM content.
 *
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NOT_FOUND: key not found or no more
 * line to read
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_get_nvram (spc300_nvram_t *nvram)
{
    FILE *fp;
    int fd;
    char *nvram_mtd_num;
    char nvram_mtd_path[128];
    char line_buffer[LIBSPID_CONFIG_LINE_MAX_LEN];
    char *strtok_ctx;
    int is_found = 0;

    if (nvram == NULL)
        return LIBSPID_ERROR_PARAM;

    fp = fopen (LIBSPID_SYSTEM_MTD_PATH, "r");
    if (fp != NULL)
    {
        while (fgets (line_buffer, LIBSPID_CONFIG_LINE_MAX_LEN - 1, fp) != NULL)
        {
            if (strstr(line_buffer, NVRAM_MTD_NAME) != NULL)
            {
                is_found = 1;
                /* Extract mtd path from line mtd<num>: <size> <erasesize> "nvram" */
                nvram_mtd_num = strtok_r (line_buffer, ": ", &strtok_ctx);
                sprintf (nvram_mtd_path, "%s/%s", LIBSPID_DEV_PATH, nvram_mtd_num);
            }
        }

        fclose (fp);

        if (is_found == 0)
        {
            return LIBSPID_ERROR_NOT_FOUND;
        }
    }
    else
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    /* open found mtd path using fd, i.e. with open sys call,
       read NVRAM magic string and verify (done below) */
    if ((fd = open (nvram_mtd_path, O_RDONLY)) < 0)
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    if (read (fd, nvram, sizeof (spc300_nvram_t)) < sizeof (spc300_nvram_t))
    {
        close (fd);
        return LIBSPID_ERROR_SYSTEM;
    }
    close (fd);
    /* check NVRAM validity */
    if (!NVRAM_IS_VALID (nvram))
    {
       return LIBSPID_ERROR_SYSTEM;
    }

    return LIBSPID_SUCCESS;
}

/**
 * Set the NVRAM content.
 *
 * \param nvram  pointer to the new NVRAM contents
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NOT_FOUND: key not found
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_set_nvram (spc300_nvram_t *nvram)
{
    FILE *fp;
    int fd;
    char *nvram_mtd_num;
    char nvram_mtd_path[128];
    char line_buffer[LIBSPID_CONFIG_LINE_MAX_LEN];
    char *strtok_ctx;
    int is_found = 0;
#ifndef __UTESTS__
    erase_info_t erase;
#endif

    if (nvram == NULL) return LIBSPID_ERROR_PARAM;

    fp = fopen (LIBSPID_SYSTEM_MTD_PATH, "r");
    if (fp != NULL)
    {
        while (fgets (line_buffer, LIBSPID_CONFIG_LINE_MAX_LEN - 1, fp) != NULL)
        {
            if (strstr (line_buffer, NVRAM_MTD_NAME) != NULL)
            {
                is_found = 1;
                /* Extract mtd path from line mtd<num>: <size> <erasesize> "nvram" */
                nvram_mtd_num = strtok_r (line_buffer, ": ", &strtok_ctx);
                sprintf (nvram_mtd_path, "%s/%s", LIBSPID_DEV_PATH, nvram_mtd_num);
            }
        }

        fclose (fp);

        if (is_found == 0) return LIBSPID_ERROR_NOT_FOUND;
    }
    else
    {
        return LIBSPID_ERROR_SYSTEM;
    }

    /* open found mtd path using fd */
    if ((fd = open (nvram_mtd_path, O_RDWR)) < 0) return LIBSPID_ERROR_SYSTEM;

#ifndef __UTESTS__
    /* erase the NVRAM sector */
    erase.start = 0;
    erase.length = 64*1024;
    if (ioctl (fd, MEMERASE, &erase) != 0)
    {
        close (fd);
        return LIBSPID_ERROR_SYSTEM;
    }
#endif

    /* store new NVRAM contents */
    if (write (fd, nvram, sizeof (spc300_nvram_t)) < sizeof (spc300_nvram_t))
    {
        close (fd);
        return LIBSPID_ERROR_SYSTEM;
    }
    close (fd);

    /* check NVRAM validity */
    if (!NVRAM_IS_VALID (nvram)) return LIBSPID_ERROR_SYSTEM;

    return LIBSPID_SUCCESS;
}

/**
 * Returns master date and time inside a provided buffer.
 * Date and time are given in the format of seconds elapsed since UNIX Epoch (01/01/1970).
 *
 * \param buffer buffer where to put the result
 * \param buffer_len length of buffer where to put the result
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_NO_SPACE: no enough space in buffer
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_get_date (char *buffer, const int buffer_len)
{
    time_t now;
    char time_buffer[LIBSPID_CONFIG_LINE_MAX_LEN];

    /* check validity of parameters */
    if (buffer == NULL || buffer_len <= 0)
        return LIBSPID_ERROR_PARAM;

    /* get current time in seconds since UNIX Epoch */
    now = time(NULL);

    sprintf(time_buffer, "%ld", now);

    /* check length of time buffer */
    if (strlen (time_buffer) > buffer_len)
        return LIBSPID_ERROR_NO_SPACE;

    strcpy (buffer, time_buffer);

    return LIBSPID_SUCCESS;
}

/**
 * Sets master date and time to value provided in buffer.
 * Date and time are given in the format of seconds elapsed since UNIX Epoch (01/01/1970).
 *
 * \param buffer buffer containing time value
 * \return error type (LIBSPID_SUCCESS if success)
 * \return LIBSPID_ERROR_PARAM: bad input parameters
 * \return LIBSPID_ERROR_SYSTEM: system error, see errno
 */

libspid_error_t
libspid_system_set_date (const char *buffer)
{
    time_t timer;

    if (buffer == NULL)
        return LIBSPID_ERROR_PARAM;

    if (1 != sscanf (buffer, "%ld", &timer))
        return LIBSPID_ERROR_PARAM;

    if (0 != stime (&timer))
        return LIBSPID_ERROR_SYSTEM;

    return LIBSPID_SUCCESS;
}

/**
 * Register a process to be informed about a file modification.
 *
 * Each time the file is modified, the registered process will receive a signal SIGHUP,
 * which will be handled by the callback.
 *
 * \param  rx_pid  identifier of the process requesting to be informed
 * \param  filename  name of the file on which any modification will trigger a signal
 * intended for the given process
 * \param  callback  signal handler
 * \return error type:
 * - LIBSPID_SUCCESS if success
 * - LIBSPID_ERROR_PARAM if bad input parameters
 * -  LIBSPID_ERROR_NO_SPACE if too much processes registered on the same file
 * - LIBSPID_ERROR_SYSTEM if system error, see errno set by sigaction() system call:
 *   - EINVAL if signal_nb is out-of-range (signal_nb <=0 or signal_nb >= NSIG)
 * or is SIGKILL or SIGSTOP
 * - error from libspid_system_file_is_registered(), libspid_config_write_line() or
 * libspid_config_read_line()
 */
libspid_error_t
libspid_system_file_update_register (pid_t rx_pid, const char *filename,
                                     const libspid_signal_handler_t callback)
{
    libspid_error_t ret = LIBSPID_SUCCESS;
    const char delimiter = *LIBSPID_SIGNAL_INFO_DELIMITER;
    char pid_str[8] = {0};
    char *elt[LIBSPID_CONFIG_ELT_MAX_NB] = {NULL};
    char key[LIBSPID_CONFIG_KEY_MAX_LEN] = {0};
    unsigned int elt_number = LIBSPID_CONFIG_ELT_MAX_NB;
    char buffer[LIBSPID_CONFIG_LINE_MAX_LEN] = {0};
    unsigned int i = 0;

    /* Check input parameters. */
    if ((0 >= rx_pid)
        || (NULL == filename)
        || (LIBSPID_CONFIG_KEY_MAX_LEN < strlen (filename))
        || (NULL == callback))
    {
        return LIBSPID_ERROR_PARAM;
    }

    /* Initialize key. */
    strcpy (key, filename);

    /* Register the given signal handler of the given process to receive signals. */
    if (SIG_ERR == signal (SIGHUP, callback))
    {
        syslog (LOG_ERR, "signal(): %m");
        return LIBSPID_ERROR_SYSTEM;
    }

    /* Lock the file to prevent race conditions when multiple processes
     * concurrently register themselves for updates on the same file. */
    file_lock_t lock;
    ret = libspid_system_file_lock (LIBSPID_SIGNAL_INFO_PATH, LIBSPID_TRUE, &lock);
    if (ret != LIBSPID_SUCCESS)
    {
        return ret;
    }

    /* Check "signal.info" file appropriate line. */
    ret = libspid_config_read_line (LIBSPID_SIGNAL_INFO_PATH,
        LIBSPID_SIGNAL_INFO_DELIMITER, key, &elt_number, elt, buffer, LIBSPID_CONFIG_LINE_MAX_LEN);

    if (LIBSPID_ERROR_NOT_FOUND == ret)
    {
        elt_number = 0;
    }
    else if (LIBSPID_SUCCESS != ret)
    {
        goto error;
    }

    /* Check that the given process has not already registered to the given file update
     * by looping on returned elements, and comparing process identifiers.
     * If one matches with the input rx_pid, return LIBSPID_SUCCESS. */
    sprintf (pid_str, "%d",  rx_pid);
    for (i=0; i<elt_number; i++)
    {
        if (!strcmp (elt[i], pid_str))
        {
            goto success;
        }
    }

    /* To know which process(es) to inform in case the given file is modified,
    * save information into the "signal.info" file. */
    if (LIBSPID_CONFIG_ELT_MAX_NB <= elt_number)
    {
        ret = LIBSPID_ERROR_NO_SPACE;
        goto error;
    }

    elt[elt_number] = pid_str;
    elt_number++;
    ret = libspid_config_write_line (LIBSPID_SIGNAL_INFO_PATH, delimiter,
                                     filename, elt_number, elt);
    if (ret != LIBSPID_SUCCESS)
    {
        goto error;
    }

success:
    return libspid_system_file_unlock (&lock);

error:
    libspid_system_file_unlock (&lock);

    return ret;
}

/**
 * Unregister a process to be informed about a file modification.
 *
 * \param  rx_pid  identifier of the process requesting to unregister
 * \param  filename  name of the file on which the process was registered
 * \return error type:
 * - LIBSPID_SUCCESS if success
 * - LIBSPID_ERROR_PARAM if bad input parameters
 * - error from libspid_config_read_line(), libspid_config_write_line() or
 * libspid_config_remove_line()
 */
libspid_error_t
libspid_system_file_update_unregister (pid_t rx_pid, const char *filename)
{
    char key[LIBSPID_CONFIG_KEY_MAX_LEN] = {0};
    unsigned int elt_number = LIBSPID_CONFIG_ELT_MAX_NB;
    char *elt[LIBSPID_CONFIG_ELT_MAX_NB] = { NULL };
    char buffer[LIBSPID_CONFIG_LINE_MAX_LEN] = {0};
    char pid_str[8] = {0};
    const char delimiter = *LIBSPID_SIGNAL_INFO_DELIMITER;
    libspid_error_t ret = LIBSPID_SUCCESS;
    libspid_boolean_t remove = LIBSPID_FALSE;
    unsigned int i = 0;

    /* Check input parameters. */
    if ((0 >= rx_pid)
        || (NULL == filename)
        || (LIBSPID_CONFIG_KEY_MAX_LEN < strlen (filename)))
    {
        return LIBSPID_ERROR_PARAM;
    }

    /* Initialize key. */
    strcpy (key, filename);

    /* Lock the file to prevent race conditions when multiple processes
     * concurrently unregister themselves for updates on the same file. */
    file_lock_t lock;
    ret = libspid_system_file_lock (LIBSPID_SIGNAL_INFO_PATH, LIBSPID_FALSE, &lock);
    if (ret == LIBSPID_ERROR_NOT_FOUND)
    {
        /* "signal.info" doesn't exist,
         * so no unregistration to do,
         * so "success". */
        return LIBSPID_SUCCESS;
    }
    else if (LIBSPID_SUCCESS != ret)
    {
        return ret;
    }

    /* Read "signal.info" file appropriate line. */
    ret = libspid_config_read_line (LIBSPID_SIGNAL_INFO_PATH,
                                    LIBSPID_SIGNAL_INFO_DELIMITER, key,
                                    &elt_number, elt, buffer,
                                    LIBSPID_CONFIG_LINE_MAX_LEN);
    if (LIBSPID_SUCCESS != ret)
    {
        goto error;
    }

    /* If the given PID is present in returned elements,
     * remove the given PID from elements. */
    sprintf (pid_str, "%d",  rx_pid);
    for (i=0; i<elt_number; i++)
    {
        if (!strcmp (elt[i], pid_str))
        {
            remove = LIBSPID_TRUE;
        }
        if (LIBSPID_TRUE == remove)
        {
            elt[i] = elt[i+1];
        }
    }

    if (LIBSPID_TRUE == remove)
    {
        /* Remove old line from "signal.info" file. */
        if (LIBSPID_SUCCESS != (ret = libspid_config_remove_line
            (LIBSPID_SIGNAL_INFO_PATH, LIBSPID_SIGNAL_INFO_DELIMITER, filename)))
        {
            goto error;
        }
        /* Write the new line in "signal.info" file. */
        elt_number--;
        if (0 < elt_number)
        {
            ret = libspid_config_write_line (LIBSPID_SIGNAL_INFO_PATH, delimiter,
                                             filename, elt_number, elt);
            if (ret != LIBSPID_SUCCESS)
            {
                goto error;
            }
        }
    }

    return libspid_system_file_unlock (&lock);

error:
    libspid_system_file_unlock (&lock);

    return ret;
}

/**
 * Check if a process is already registered to a particular file update.
 *
 * \param  rx_pid  identifier of the process to search
 * \param  filename  name of the file to search
 * \param  is_registered  inout parameter to give the answer
 * \return error type:
 * - LIBSPID_SUCCESS if success
 * - LIBSPID_ERROR_PARAM if bad input parameters
 * - error from libspid_config_read_line()
 */
libspid_error_t
libspid_system_file_update_is_registered (pid_t rx_pid, const char *filename,
                                          libspid_boolean_t *is_registered)
{
    libspid_error_t ret = LIBSPID_SUCCESS;
    char key[LIBSPID_CONFIG_KEY_MAX_LEN] = {0};
    unsigned int elt_number = LIBSPID_CONFIG_ELT_MAX_NB;
    char *elt[LIBSPID_CONFIG_ELT_MAX_NB] = {NULL};
    char buffer[LIBSPID_CONFIG_LINE_MAX_LEN] = {0};
    char pid_str[8] = {0};
    unsigned int i = 0;

    /* Check input parameters. */
    if ((0 >= rx_pid)
        || (NULL == filename)
        || (LIBSPID_CONFIG_KEY_MAX_LEN < strlen (filename))
        || (NULL == is_registered))
    {
        return LIBSPID_ERROR_PARAM;
    }

    /* Initialize is_registered and key. */
    *is_registered = LIBSPID_FALSE;
    strcpy (key, filename);

    /* Check in "signal.info" file if some processes are registered to the given file. */
    ret = libspid_config_read_line (LIBSPID_SIGNAL_INFO_PATH,
        LIBSPID_SIGNAL_INFO_DELIMITER, key, &elt_number, elt, buffer,
        LIBSPID_CONFIG_LINE_MAX_LEN);
    if ((LIBSPID_ERROR_NOT_FOUND == ret)
        || ((LIBSPID_ERROR_SYSTEM == ret) && (ENOENT == errno)))
    {
        return LIBSPID_SUCCESS;
    }
    else if (LIBSPID_SUCCESS != ret)
    {
        return ret;
    }

    /* Check if the given process is registered to the given file
     * by looping on returned elements, and comparing process identifiers.
     * If one matches with the input rx_pid, set inout is_registered to LIBSPID_TRUE. */
    sprintf (pid_str, "%d",  rx_pid);
    for (i=0; i<elt_number; i++)
    {
        if (!strcmp (elt[i], pid_str))
        {
            *is_registered = LIBSPID_TRUE;
            break;
        }
    }

    return LIBSPID_SUCCESS;
}

/**
 * Send the SIGHUP signal to all registered processes.
 *
 * Call this function when you want to inform other processes
 * that the given file has been modified.
 *
 * \param  tx_pid  identifier of the calling process
 * \param  filename  name of the file which has been modified
 * \return error type:
 * - LIBSPID_SUCCESS if success
 * - LIBSPID_ERROR_PARAM if bad input parameters
 * - LIBSPID_ERROR_SYSTEM if system error, see errno set by kill() system call:
 *   - EPERM in case of authorization constraints
 *   - ESRCH if pid not found
 *   - EINVAL if signal_nb < 0 or signal_nb >= NSIG
 * - error from libspid_config_read_line()
 */
libspid_error_t
libspid_system_file_update_warn (pid_t tx_pid, const char *filename)
{
    libspid_error_t ret = LIBSPID_SUCCESS;
    char key[LIBSPID_CONFIG_KEY_MAX_LEN] = {0};
    unsigned int elt_number = LIBSPID_CONFIG_ELT_MAX_NB;
    char *elt[LIBSPID_CONFIG_ELT_MAX_NB] = {NULL};
    char buffer[LIBSPID_CONFIG_LINE_MAX_LEN] = {0};
    pid_t rx_pid = 0;
    unsigned int i = 0;

    /* Check input parameters. */
    if ((0 > tx_pid)
        || (NULL == filename)
        || (LIBSPID_CONFIG_KEY_MAX_LEN < strlen (filename)))
    {
        return LIBSPID_ERROR_PARAM;
    }

    /* Initialize key. */
    strcpy (key, filename);

    /* To know which process(es) to inform, get information from the "signal.info" file. */
    ret = libspid_config_read_line (LIBSPID_SIGNAL_INFO_PATH,
        LIBSPID_SIGNAL_INFO_DELIMITER, key, &elt_number, elt, buffer,
        LIBSPID_CONFIG_LINE_MAX_LEN);
    if ((LIBSPID_ERROR_SYSTEM == ret) && (ENOENT == errno))
    {
        /* If the "signal.info" file does not exist, it means that no process has registered
         * to any files updates. */
        return LIBSPID_SUCCESS;
    }
    else if (LIBSPID_ERROR_NOT_FOUND == ret)
    {
        /* No process has registered to the given file update. */
        return LIBSPID_SUCCESS;
    }
    else if (LIBSPID_SUCCESS != ret)
    {
        return ret;
    }

    /* Transmit the signal to the registered processes. */
    for (i=0; i<elt_number; i++)
    {
        /* Check that rx_pid is different from the calling process.
         * Note that if input tx_pid = 0, the calling process will also receive the signal. */
        if ((0 != (rx_pid = atoi (elt[i])))
            && (tx_pid != rx_pid)
            && (0 != kill (rx_pid, SIGHUP)))
        {
            return LIBSPID_ERROR_SYSTEM;
        }
    }

    return LIBSPID_SUCCESS;
}