Factor out hostname parsing for reuse
[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_name_internal.h>
40 #include <tr_util.h>
41 #include <stdlib.h>
42
43 void tr_bin_to_hex(const unsigned char * bin, size_t bin_len,
44                    char * hex_out, size_t hex_len)
45 {
46   assert(hex_len >= 2*bin_len);
47   while (bin_len >0) {
48     snprintf(hex_out, hex_len, "%.2x", bin[0]);
49     bin++, hex_out += 2;
50     bin_len--;
51     hex_len -= 2;
52   }
53 }
54
55 /**
56  * Compare two timespecs
57  *
58  * Assumes tv_nsec <= 1e9
59  *
60  * @param ts1
61  * @param ts2
62  * @return 0 if ts1==ts2, -1 if ts1<ts2, 1 if ts1>ts2.
63  */
64 int tr_cmp_timespec(const struct timespec *ts1, const struct timespec *ts2)
65 {
66   if (ts1->tv_sec > ts2->tv_sec)
67     return 1;
68
69   if (ts1->tv_sec < ts2->tv_sec)
70     return -1;
71
72   /* ts1->tv_sec==ts2->tv_sec */
73
74   if (ts1->tv_nsec > ts2->tv_nsec)
75     return 1;
76
77   if (ts1->tv_nsec < ts2->tv_nsec)
78     return -1;
79
80   return 0;
81 }
82
83 /**
84  * Compute ts1 + ts2
85  *
86  * @param ts1
87  * @param ts2
88  * @param sum ts1 + ts2
89  * @return 0 on success, nonzero on error
90  */
91 int tr_add_timespec(const struct timespec *ts1, const struct timespec *ts2, struct timespec *sum)
92 {
93   const time_t ONE_BILLION = 1000000000;
94
95   if (!ts1 || !ts2 || !sum)
96     return -1;
97
98   /* would be nice to do range checking, but I don't know a portable way to get the
99    * max value of a time_t. Figure that nsec <= 1e9 and seconds are unlikely to go off
100    * too close to infinity, so overflow is unlikely */
101   sum->tv_nsec = ts1->tv_nsec + ts2->tv_nsec;
102   sum->tv_sec = ts1->tv_sec + ts2->tv_sec;
103
104   /* make sure that we have no more than a second worth of nsec */
105   while (sum->tv_nsec >= ONE_BILLION) {
106     sum->tv_nsec -= ONE_BILLION;
107     sum->tv_sec += 1;
108   }
109
110   return 0;
111 }
112
113 /**
114  * Compute ts1 - ts2
115  *
116  * Allows negative results, which will be represented as a negative tv_sec.
117  * The returned tv_nsec is always positive and less than 1e9.
118  *
119  * (The value represented is tv_sec + tv_nsec/1e9 seconds - this is a little
120  * counterintuitive when tv_sec is negative. E.g., -1.5 seconds is represented
121  * as {-2, 500000000). Negative time_t values are not guaranteed to be supported
122  * anyway, so it's probably best to stay away from them.)
123  *
124  * @param ts1
125  * @param ts2
126  * @param diff ts1 - ts2
127  * @return 0 on success, nonzero on error
128  */
129 int tr_sub_timespec(const struct timespec *ts1, const struct timespec *ts2, struct timespec *diff)
130 {
131   const time_t ONE_BILLION = 1000000000;
132   struct timespec ts1_copy = {0};
133   struct timespec ts2_copy = {0};
134   
135   if (!ts1 || !ts2 || !diff)
136     return -1;
137
138   ts1_copy = *ts1;
139   ts2_copy = *ts2;
140   
141   while (ts2_copy.tv_nsec > ts1_copy.tv_nsec) {
142     /* Reduce ts2 by one second worth of nsec, balanced by removing a second
143      * from ts1. Repeat until ts2->tv_nsec <= ts1->tv_nsec. */
144     ts2_copy.tv_nsec -= ONE_BILLION;
145     ts1_copy.tv_sec -= 1;
146   }
147
148   diff->tv_nsec = ts1_copy.tv_nsec - ts2_copy.tv_nsec; /* >= 0 */
149   diff->tv_sec = ts1_copy.tv_sec - ts2_copy.tv_sec; /* sign indeterminate */
150
151   /* make sure we have no more than 1 sec worth of nsec */
152   while (diff->tv_nsec > ONE_BILLION) {
153     diff->tv_nsec -= ONE_BILLION;
154     diff->tv_sec += 1;
155   }
156
157   return 0;
158 }
159
160 /**
161  * Convert a struct timespec to a string representation
162  * @param ts
163  * @return
164  */
165 char *timespec_to_str(const struct timespec *ts)
166 {
167   struct tm tm;
168   char *s=NULL;
169
170   if (gmtime_r(&(ts->tv_sec), &tm)==NULL)
171     return NULL;
172
173   s=malloc(40); /* long enough to contain strftime result */
174   if (s==NULL)
175     return NULL;
176
177   if (strftime(s, 40, "%F %T UTC", &tm)==0) {
178     free(s);
179     return NULL;
180   }
181   return s;
182 }
183
184 /**
185  * Convert a time from one clock to another
186  *
187  * Because this involves reading each clock, it is not exact.
188  *
189  * @param from clock to convert from
190  * @param when time to convert, measured on the 'from' clock
191  * @param to clock to convert to
192  * @param dst destination, measured on the 'to' clock
193  * @return dst or null on error
194  */
195 struct timespec *tr_clock_convert(clockid_t from, const struct timespec *when,
196                                   clockid_t to, struct timespec *dst)
197 {
198   struct timespec now_from = {0};
199   struct timespec diff = {0}; /* difference between when and now_from */
200   struct timespec now_to = {0};
201
202   if ((clock_gettime(from, &now_from) != 0)
203       || (clock_gettime(to, &now_to) != 0)) {
204     return NULL;
205   }
206   if (tr_sub_timespec(when, &now_from, &diff) != 0) {
207     return NULL;
208   }
209   if (tr_add_timespec(&now_to, &diff, dst) != 0) {
210     return NULL;
211   }
212   return dst;
213 }
214
215 TR_NAME *tr_parse_hostname(const char *s)
216 {
217   const char *colon;
218   char *hostname;
219   size_t hostname_len;
220   TR_NAME *retval;
221
222   if (s == NULL)
223     return NULL;
224
225   /* find the colon */
226   colon = strchr(s, ':');
227   if (colon == NULL)
228     return tr_new_name(s); /* there was no colon, take the whole string */
229
230   /* make a copy of the hostname portion of the string */
231   hostname_len = colon - s;
232   hostname = malloc(hostname_len + 1); /* +1 for the null termination */
233   if (hostname == NULL)
234     return NULL;
235
236   /* copy up to the colon, add a null termination, and make a TR_NAME */
237   strncpy(hostname, s, hostname_len);
238   hostname[hostname_len] = '\0';
239   retval = tr_new_name(hostname);
240
241   /* clean up and return */
242   free(hostname);
243   return retval;
244 }
245
246 /**
247  * Parse the port from a hostname:port string
248  *
249  * @param s string to parse
250  * @return the specified port, 0 if none specified, -1 if invalid
251  */
252 int tr_parse_port(const char *s)
253 {
254   const char *s_port;
255   char *end_of_conversion;
256   long int port; /* long instead of int because we use strtol */
257
258   /* Find the first colon */
259   s_port = strchr(s, ':'); /* port starts at s_port + 1 */
260   if (s_port == NULL)
261     return 0; /* no port */
262
263   /* Check that the last colon is the same as the first */
264   if (strrchr(s, ':') != s_port)
265     return -1; /* multiple colons are invalid*/
266
267   s_port += 1; /* port now starts at s_port */
268
269   /* Parse the port number */
270   port = strtol(s, &end_of_conversion, /* base */ 10);
271
272   /* validate */
273   if ((end_of_conversion == s_port) /* there was no port, just a colon */
274       || (*end_of_conversion != '\0') /* did not reach the end of the string */
275       || (port <= 0) || (port > 65535)) {
276     return -1;
277   }
278
279   return (int) port;
280 }
281
282 /**
283  * Parse hostname and port
284  *
285  * @param s
286  * @param hn_dest
287  * @param p_dest
288  * @return 0 on success, -1 on error
289  */
290 int tr_parse_hostname_and_port(const char *s, TR_NAME **hn_dest, int *p_dest)
291 {
292   if ((hn_dest == NULL) || (p_dest == NULL))
293     return -1;
294
295   *hn_dest = tr_parse_hostname(s);
296   if (*hn_dest == NULL)
297     return -1;
298
299   *p_dest = tr_parse_port(s);
300   if ((*p_dest < 0) || (*p_dest > 65535)) {
301     tr_free_name(*hn_dest);
302     *hn_dest = NULL;
303     return -1;
304   }
305
306   return 0;
307 }
308