TAS
TCP Acceleration as an OS Service
utils.c
1 /*
2  * Copyright 2019 University of Washington, Max Planck Institute for
3  * Software Systems, and The University of Texas at Austin
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be
14  * included in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <ctype.h>
29 #include <arpa/inet.h>
30 #include <utils.h>
31 #include <assert.h>
32 #include <unistd.h>
33 
34 int util_parse_ipv4(const char *s, uint32_t *ip)
35 {
36  if (inet_pton(AF_INET, s, ip) != 1) {
37  return -1;
38  }
39  *ip = htonl(*ip);
40  return 0;
41 }
42 
43 int util_parse_mac(const char *s, uint64_t *mac)
44 {
45  char buf[18];
46  int i;
47  uint64_t x, y;
48 
49  /* mac address has length 17 = 2x6 digits + 5 colons */
50  if (strlen(s) != 17 || s[2] != ':' || s[5] != ':' ||
51  s[8] != ':' || s[11] != ':' || s[14] != ':')
52  {
53  return -1;
54  }
55  memcpy(buf, s, sizeof(buf));
56 
57  /* replace colons by NUL bytes to separate strings */
58  buf[2] = buf[5] = buf[8] = buf[11] = buf[14] = 0;
59 
60  y = 0;
61  for (i = 5; i >= 0; i--) {
62  if (!isxdigit(buf[3 * i]) || !isxdigit(buf[3 * i + 1])) {
63  return -1;
64  }
65  x = strtoul(&buf[3 * i], NULL, 16);
66  y = (y << 8) | x;
67  }
68  *mac = y;
69 
70  return 0;
71 }
72 
73 void util_dump_mem(const void *mem, size_t len)
74 {
75  const uint8_t *b = mem;
76  size_t i;
77  for (i = 0; i < len; i++) {
78  fprintf(stderr, "%02x ", b[i]);
79  }
80  fprintf(stderr, "\n");
81 }