f45ca2b73b08ec8d3ad72bac111d1fddf3fbca5f
[trust_router.git] / common / tr_util.c
1 /*
2  * Copyright (c) 2012, 2013, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <assert.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <time.h>
39 #include <tr_util.h>
40 #include <stdlib.h>
41
42 void tr_bin_to_hex(const unsigned char * bin, size_t bin_len,
43                    char * hex_out, size_t hex_len)
44 {
45   assert(hex_len >= 2*bin_len);
46   while (bin_len >0) {
47     snprintf(hex_out, hex_len, "%.2x", bin[0]);
48     bin++, hex_out += 2;
49     bin_len--;
50     hex_len -= 2;
51   }
52 }
53
54 /**
55  * Compare two timespecs
56  *
57  * Assumes tv_nsec <= 1e9
58  *
59  * @param ts1
60  * @param ts2
61  * @return 0 if ts1==ts2, -1 if ts1<ts2, 1 if ts1>ts2.
62  */
63 int tr_cmp_timespec(const struct timespec *ts1, const struct timespec *ts2)
64 {
65   if (ts1->tv_sec > ts2->tv_sec)
66     return 1;
67
68   if (ts1->tv_sec < ts2->tv_sec)
69     return -1;
70
71   /* ts1->tv_sec==ts2->tv_sec */
72
73   if (ts1->tv_nsec > ts2->tv_nsec)
74     return 1;
75
76   if (ts1->tv_nsec < ts2->tv_nsec)
77     return -1;
78
79   return 0;
80 }
81
82 /**
83  * Compute ts1 + ts2
84  *
85  * @param ts1
86  * @param ts2
87  * @param sum ts1 + ts2
88  * @return 0 on success, nonzero on error
89  */
90 int tr_add_timespec(const struct timespec *ts1, const struct timespec *ts2, struct timespec *sum)
91 {
92   const time_t ONE_BILLION = 1000000000;
93
94   if (!ts1 || !ts2 || !sum)
95     return -1;
96
97   /* would be nice to do range checking, but I don't know a portable way to get the
98    * max value of a time_t. Figure that nsec <= 1e9 and seconds are unlikely to go off
99    * too close to infinity, so overflow is unlikely */
100   sum->tv_nsec = ts1->tv_nsec + ts2->tv_nsec;
101   sum->tv_sec = ts1->tv_sec + ts2->tv_sec;
102
103   /* make sure that we have no more than a second worth of nsec */
104   while (sum->tv_nsec >= ONE_BILLION) {
105     sum->tv_nsec -= ONE_BILLION;
106     sum->tv_sec += 1;
107   }
108
109   return 0;
110 }
111
112 /**
113  * Compute ts1 - ts2
114  *
115  * Allows negative results, which will be represented as a negative tv_sec.
116  * The returned tv_nsec is always positive and less than 1e9.
117  *
118  * (The value represented is tv_sec + tv_nsec/1e9 seconds - this is a little
119  * counterintuitive when tv_sec is positive. E.g., -1.5 seconds is represented
120  * as {-2, 500000000).)
121  *
122  * @param ts1
123  * @param ts2
124  * @param diff ts1 - ts2
125  * @return 0 on success, nonzero on error
126  */
127 int tr_sub_timespec(const struct timespec *ts1, const struct timespec *ts2, struct timespec *diff)
128 {
129   const time_t ONE_BILLION = 1000000000;
130   struct timespec ts1_copy = {0};
131   struct timespec ts2_copy = {0};
132   
133   if (!ts1 || !ts2 || !diff)
134     return -1;
135
136   ts1_copy = *ts1;
137   ts2_copy = *ts2;
138   
139   while (ts2_copy.tv_nsec > ts1_copy.tv_nsec) {
140     /* Reduce ts2 by one second worth of nsec, balanced by removing a second
141      * from ts1. Repeat until ts2->tv_nsec <= ts1->tv_nsec. */
142     ts2_copy.tv_nsec -= ONE_BILLION;
143     ts1_copy.tv_sec -= 1;
144   }
145
146   diff->tv_nsec = ts1_copy.tv_nsec - ts2_copy.tv_nsec; /* >= 0 */
147   diff->tv_sec = ts1_copy.tv_sec - ts2_copy.tv_sec; /* sign indeterminate */
148
149   /* make sure we have no more than 1 sec worth of nsec */
150   while (diff->tv_nsec > ONE_BILLION) {
151     diff->tv_nsec -= ONE_BILLION;
152     diff->tv_sec += 1;
153   }
154
155   return 0;
156 }
157
158 /**
159  * Convert a struct timespec to a string representation
160  * @param ts
161  * @return
162  */
163 char *timespec_to_str(const struct timespec *ts)
164 {
165   struct tm tm;
166   char *s=NULL;
167
168   if (gmtime_r(&(ts->tv_sec), &tm)==NULL)
169     return NULL;
170
171   s=malloc(40); /* long enough to contain strftime result */
172   if (s==NULL)
173     return NULL;
174
175   if (strftime(s, 40, "%F %T UTC", &tm)==0) {
176     free(s);
177     return NULL;
178   }
179   return s;
180 }
181
182 /**
183  * Convert a time from one clock to another
184  *
185  * Because this involves reading each clock, it is not exact.
186  *
187  * @param from clock to convert from
188  * @param when time to convert, measured on the 'from' clock
189  * @param to clock to convert to
190  * @param dst destination, measured on the 'to' clock
191  * @return dst or null on error
192  */
193 struct timespec *tr_clock_convert(clockid_t from, const struct timespec *when,
194                                   clockid_t to, struct timespec *dst)
195 {
196   struct timespec now_from = {0};
197   struct timespec diff = {0}; /* difference between when and now_from */
198   struct timespec now_to = {0};
199
200   if ((clock_gettime(from, &now_from) != 0)
201       || (clock_gettime(to, &now_to) != 0)) {
202     return NULL;
203   }
204   if (tr_sub_timespec(when, &now_from, &diff) != 0) {
205     return NULL;
206   }
207   if (tr_add_timespec(&now_to, &diff, dst) != 0) {
208     return NULL;
209   }
210   return dst;
211 }