1 /*
2  * Fig2dev: Translate Fig code to various Devices
3  * Parts Copyright (c) 2016, 2017 by Thomas Loimer
4  *
5  * Any party obtaining a copy of these files is granted, free of charge, a
6  * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
7  * nonexclusive right and license to deal in this software and documentation
8  * files (the "Software"), including without limitation the rights to use,
9  * copy, modify, merge, publish, distribute, sublicense and/or sell copies
10  * of the Software, and to permit persons who receive copies from any such
11  * party to do so, with the only requirement being that the above copyright
12  * and this permission notice remain intact.
13  *
14  */
15 
16 /*
17  * creationdate.c: provide the creation time and enable reproducibe builds
18  * Author: Thomas Loimer, 2016-06-28
19  *
20  */
21 
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #ifdef	HAVE_STRERROR
30 #include <errno.h>
31 #endif
32 #include <time.h>
33 #include <limits.h>
34 #include "bool.h"
35 
36 #include "creationdate.h"
37 
38 
39 int
creation_date(char * buf)40 creation_date(char *buf)
41 {
42     time_t now;
43 
44 #ifdef	HAVE_STRERROR
45     char *source_date_epoch;
46     unsigned long long epoch;
47     char *endptr;
48 
49     source_date_epoch = getenv("SOURCE_DATE_EPOCH");
50     if (source_date_epoch) {
51 	errno = 0;
52 	epoch = strtoull(source_date_epoch, &endptr, 10);
53 	if ((errno == ERANGE && (epoch == ULLONG_MAX || epoch == 0))
54 		|| (errno != 0 && epoch == 0)) {
55 	    fprintf(stderr,
56 		"Environment variable $SOURCE_DATE_EPOCH: strtoull: %s\n",
57 		strerror(errno));
58 	} else if (endptr == source_date_epoch) {
59 	    fprintf(stderr,
60 		"Environment variable $SOURCE_DATE_EPOCH: No digits were found: %s\n",
61 		endptr);
62 	} else if (*endptr != '\0') {
63 	    fprintf(stderr,
64 		"Environment variable $SOURCE_DATE_EPOCH: Trailing garbage: %s\n",
65 		endptr);
66 	} else if (epoch > ULONG_MAX) {
67 	    fprintf(stderr,
68 		"Environment variable $SOURCE_DATE_EPOCH: value must be smaller than or equal to: %lu but was found to be: %llu \n",
69 		ULONG_MAX, epoch);
70 	} else {
71 	    /* no errors, epoch is valid */
72 	    now = epoch;
73 	    strftime(buf, CREATION_TIME_LEN, "%F %H:%M:%S", gmtime(&now));
74 	    return true;
75 	}
76     }
77 #endif
78 
79     /* fall trough on errors or !source_date_epoch */
80     time(&now);
81     if (strftime(buf, CREATION_TIME_LEN, "%F %H:%M:%S", localtime(&now)))
82 	return true;
83     else
84 	return false;
85 }
86