summaryrefslogtreecommitdiffstats
path: root/isys/nl.c
blob: aacea534bfaadd087aa7c626253d57909923022f (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
/*
 * nl.c - Netlink helper functions
 *
 * Copyright 2006 Red Hat, Inc.
 *
 * David Cantrell <dcantrell@redhat.com>
 *
 * This software may be freely redistributed under the terms of the GNU
 * general public license.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <arpa/inet.h>
#include <net/if_arp.h>

#include <glib.h>

#include "nl.h"
#include "str.h"

/* A linked list of interface_info_t structures (see nl.h) */
static GSList *interfaces = NULL;

/**
 * Not really Netlink-specific, but handy nonetheless.  Takes a MAC address
 * and converts it to the familiar hexidecimal notation for easy reading.
 *
 * @param mac The unsigned char MAC address value.
 * @param buf The string to write the formatted address to.
 * @return Pointer to buf.
 */
char *netlink_format_mac_addr(char *buf, unsigned char *mac) {
   if (buf == NULL) {
      if ((buf = malloc(20)) == NULL) {
         perror("malloc in netlink_format_mac_addr");
         return NULL;
      }
   }

   sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

   return str2upper(buf);
}

/**
 * Convert cylon-readable IP address to human-readable format (either v4
 * or v6).
 *
 * @param family The address family.
 * @param intf The interface_info_t structure with the IP address info.
 * @param buf The buffer to write the formatted IP address to.
 * @return A pointer to buf.
 */
char *netlink_format_ip_addr(int family, interface_info_t *intf, char *buf) {
   int iplen;

   if (family == AF_INET6)
      iplen = INET6_ADDRSTRLEN;
   else
      iplen = INET_ADDRSTRLEN;

   if (buf == NULL) {
      if ((buf = malloc(iplen)) == NULL) {
         perror("malloc in netlink_format_ip_addr");
         return NULL;
      }

      memset(buf, 0, iplen);
   }

   switch (family) {
      case AF_INET:
         inet_ntop(family, &(intf->ip_addr), buf, iplen);
         break;
      case AF_INET6:
         inet_ntop(family, &(intf->ip6_addr), buf, iplen);
         break;
   }

   return buf;
}

/**
 * Create a new PF_NETLINK socket for communication with the kernel Netlink
 * layer.  Open with NETLINK_ROUTE protocol since we want IPv4 and IPv6
 * interface, address, and routing information.
 *
 * @return Handle to new socket or -1 on error.
 */
int netlink_create_socket(void) {
   int sock;

   sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
   if (sock < 0) {
      perror("netlink socket");
      return -1;
   }

   return sock;
}

/**
 * Send a dump request message for the specified information in the
 * specified family type.  Family may be AF_INET or AF_INET6, for
 * example.  The request type should be a GET type as specified in
 * /usr/include/linux/rtnetlink.h (for example, RTM_GETLINK).
 *
 * @param sock The Netlink socket to use.
 * @param type The Netlink request type.
 * @param family The address family.
 * @return The number of characters sent or -1 on error.
 */
int netlink_send_dump_request(int sock, int type, int family) {
   int ret;
   char buf[4096];
   struct sockaddr_nl snl;
   struct nlmsghdr *nlh;
   struct rtgenmsg *g;

   memset(&snl, 0, sizeof(snl));
   snl.nl_family = AF_NETLINK;

   memset(buf, 0, sizeof(buf));
   nlh = (struct nlmsghdr *)buf;
   g = (struct rtgenmsg *)(buf + sizeof(struct nlmsghdr));

   nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
   nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_DUMP;
   nlh->nlmsg_type = type;
   g->rtgen_family = family;

   ret = sendto(sock, buf, nlh->nlmsg_len, 0, (struct sockaddr *)&snl,
                sizeof(snl));
   if (ret < 0) {
      perror("netlink_send_dump_request sendto");
      return -1;
   }

   return ret;
}

/**
 * Look for an IP address for the given interface.
 *
 * @param index The interface index number.
 * @param family The address family (AF_INET or AF_INET6).
 * @param addr Pointer to where we should write the IP address.
 * @return -1 on error, 0 on success.
 */
int netlink_get_interface_ip(int index, int family, void *addr) {
   int sock, ret, len, alen;
   char buf[4096];
   struct nlmsghdr *nlh;
   struct ifaddrmsg *ifa;
   struct rtattr *rta;
   struct rtattr *tb[IFLA_MAX+1];

   /* get a socket */
   if ((sock = netlink_create_socket()) == -1) {
      perror("netlink_create_socket in netlink_get_interface_ip");
      close(sock);
      return -1;
   }

   /* send dump request */
   if (netlink_send_dump_request(sock, RTM_GETADDR, family) == -1) {
      perror("netlink_send_dump_request in netlink_get_interface_ip");
      close(sock);
      return -1;
   }

   /* read back messages */
   memset(buf, 0, sizeof(buf));
   ret = recvfrom(sock, buf, sizeof(buf), 0, NULL, 0);
   if (ret < 0) {
      perror("recvfrom in netlink_init_interfaces_table");
      close(sock);
      return -1;
   }

   nlh = (struct nlmsghdr *) buf;
   while (NLMSG_OK(nlh, ret)) {
      switch (nlh->nlmsg_type) {
         case NLMSG_DONE:
            break;
         case RTM_NEWADDR:
            break;
         default:
            nlh = NLMSG_NEXT(nlh, ret);
            continue;
      }

      /* RTM_NEWADDR */
      ifa = NLMSG_DATA(nlh);
      rta = IFA_RTA(ifa);
      len = NLMSG_PAYLOAD(nlh, 0);     /* IFA_PAYLOAD(nlh) ???? */

      if (ifa->ifa_family != family) {
         nlh = NLMSG_NEXT(nlh, ret);
         continue;
      }

      while (RTA_OK(rta, len)) {
         if (rta->rta_type <= len)
            tb[rta->rta_type] = rta;
         rta = RTA_NEXT(rta, len);
      }

      alen = RTA_PAYLOAD(tb[IFA_ADDRESS]);

      /* write the address */
      if (tb[IFA_ADDRESS] && ifa->ifa_index == index) {
         memset(addr, 0, sizeof(*addr));
         switch (family) {
            case AF_INET:
               memcpy(addr, (struct in_addr *)RTA_DATA(tb[IFA_ADDRESS]), alen);
               break;
            case AF_INET6:
               memcpy(addr, (struct in6_addr *)RTA_DATA(tb[IFA_ADDRESS]), alen);
               break;
         }

         close(sock);
         return 0;
      }

      /* next netlink msg */
      nlh = NLMSG_NEXT(nlh, ret);
   }

   close(sock);
   return 0;
}

/**
 * Initialize the interfaces linked list with the interface name, MAC
 * address, and IP addresses.  This function is only called once to
 * initialize the structure, but may be called again if the structure
 * should be reinitialized.
 *
 * @return 0 on succes, -1 on error.
 */
int netlink_init_interfaces_list(void) {
   int sock, ret, len, alen, r;
   char buf[4096];
   struct nlmsghdr *nlh;
   struct ifinfomsg *ifi;
   struct rtattr *rta;
   struct rtattr *tb[IFLA_MAX+1];
   interface_info_t *intfinfo;

   /* get a socket */
   if ((sock = netlink_create_socket()) == -1) {
      perror("netlink_create_socket in netlink_init_interfaces_table");
      close(sock);
      return -1;
   }

   /* send dump request */
   if (netlink_send_dump_request(sock, RTM_GETLINK, AF_NETLINK) == -1) {
      perror("netlink_send_dump_request in netlink_init_interfaces_table");
      close(sock);
      return -1;
   }

   /* read back messages */
   memset(buf, 0, sizeof(buf));
   ret = recvfrom(sock, buf, sizeof(buf), 0, NULL, 0);
   if (ret < 0) {
      perror("recvfrom in netlink_init_interfaces_table");
      close(sock);
      return -1;
   }

   nlh = (struct nlmsghdr *) buf;
   while (NLMSG_OK(nlh, ret)) {
      switch (nlh->nlmsg_type) {
         case NLMSG_DONE:
            break;
         case RTM_NEWLINK:
            break;
         default:
            nlh = NLMSG_NEXT(nlh, ret);
            continue;
      }

      /* RTM_NEWLINK */
      memset(tb, 0, sizeof(tb));
      memset(tb, 0, sizeof(struct rtattr *) * (IFLA_MAX + 1));

      ifi = NLMSG_DATA(nlh);
      rta = IFLA_RTA(ifi);
      len = IFLA_PAYLOAD(nlh);

      /* void and none are bad */
      if (ifi->ifi_type == ARPHRD_VOID || ifi->ifi_type == ARPHRD_NONE) {
         nlh = NLMSG_NEXT(nlh, ret);
         continue;
      }

      while (RTA_OK(rta, len)) {
         if (rta->rta_type <= len)
            tb[rta->rta_type] = rta;
         rta = RTA_NEXT(rta, len);
      }

      alen = RTA_PAYLOAD(tb[IFLA_ADDRESS]);

      /* we have an ethernet MAC addr if alen=6 */
      if (alen == 6) {
         /* make some room! */
         intfinfo = malloc(sizeof(struct _interface_info_t));
         if (intfinfo == NULL) {
            perror("malloc in netlink_init_interfaces_table");
            close(sock);
            return -1;
         }

         /* copy the interface index */
         intfinfo->i = ifi->ifi_index;

         /* copy the interface name (eth0, eth1, ...) */
         intfinfo->name = strndup((char *) RTA_DATA(tb[IFLA_IFNAME]),
                                  sizeof(RTA_DATA(tb[IFLA_IFNAME])));

         /* copy the MAC addr */
         memcpy(&intfinfo->mac, RTA_DATA(tb[IFLA_ADDRESS]), alen);

         /* get the IPv4 address of this interface (if any) */
         r = netlink_get_interface_ip(intfinfo->i, AF_INET, &intfinfo->ip_addr);
         if (r == -1)
            intfinfo->ip_addr.s_addr = 0;

         /* get the IPv6 address of this interface (if any) */
         r = netlink_get_interface_ip(intfinfo->i,AF_INET6,&intfinfo->ip6_addr);
         if (r == -1)
            memset(intfinfo->ip6_addr.s6_addr, 0, sizeof(intfinfo->ip6_addr.s6_addr));

         /* add this interface */
         interfaces = g_slist_append(interfaces, intfinfo);
      }

      /* next netlink msg */
      nlh = NLMSG_NEXT(nlh, ret);
   }

   close(sock);
   return 0;
}

/**
 * Take the cylon-readable IP address for the specified device and format
 * it for human reading.  NOTE:  This function will check for IPv6 and IPv4
 * addresses.  In the case where the interface has both, the IPv4 address
 * is returned.  The only way you will get an IPv6 address from this function
 * is if that's the only address configured for the interface.
 *
 * @param ifname The interface name (e.g., eth0).
 * @return The human-readable IP address (either IPv4 or IPv6) or NULL on
 *         error/no match.
 */
char *netlink_interfaces_ip2str(char *ifname) {
   char *ret = NULL;
   GSList *e;
   interface_info_t *intf;

   if (ifname == NULL)
      return NULL;

   /* init the interfaces list if it's empty */
   if (interfaces == NULL) {
      if (netlink_init_interfaces_list() == -1) {
         perror("netlink_init_interfaces_list in netlink_interface_mac2str");
         return NULL;
      }
   }

   e = g_slist_find_custom(interfaces,ifname,&_netlink_interfaces_elem_find);
   if (e == NULL) {
      return NULL;
   } else {
      intf = (interface_info_t *) e->data;

      if (intf->ip_addr.s_addr == 0 && intf->ip6_addr.s6_addr[0] == 0)
         /* neither IP set, return null */
         ret = NULL;
      else if (intf->ip_addr.s_addr == 0 && intf->ip6_addr.s6_addr[0] != 0)
         /* only IPv6 addr, return that */
         ret = netlink_format_ip_addr(AF_INET6, intf, ret);
      else if (intf->ip_addr.s_addr != 0)
         /* if IPv4 is set, return that (regardless of IPv6 value) */
         ret = netlink_format_ip_addr(AF_INET, intf, ret);
      else
         /* we have no idea what happened, return NULL */
         ret = NULL;

      return ret;
   }
}

/**
 * Take the cylon-readable MAC address for the specified device and
 * format it for human reading.
 *
 * @param ifname The interface name (e.g., eth0).
 * @return The human-readable MAC address (e.g., 01:0A:3E:4B:91:12) or NULL
 *         on error.
 */
char *netlink_interfaces_mac2str(char *ifname) {
   char *ret = NULL;
   GSList *e;
   interface_info_t *intf;

   if (ifname == NULL)
      return NULL;

   /* init the interfaces list if it's empty */
   if (interfaces == NULL) {
      if (netlink_init_interfaces_list() == -1) {
         perror("netlink_init_interfaces_list in netlink_interface_mac2str");
         return NULL;
      }
   }

   e = g_slist_find_custom(interfaces,ifname,&_netlink_interfaces_elem_find);
   if (e == NULL) {
      return NULL;
   } else {
      intf = (interface_info_t *) e->data;
      ret = netlink_format_mac_addr(ret, intf->mac);
      return ret;
   }
}

/**
 * Free memory for each element of the specified linked list.  Frees the
 * list after all elements have been freed (say 'free' some more).
 */
void netlink_interfaces_list_free(void) {
   g_slist_foreach(interfaces, &_netlink_interfaces_elem_free, NULL);
   g_slist_free(interfaces);
   interfaces = NULL;
}

/**
 * Callback function for netlink_interfaces_list_free.  Frees an individual
 * list element.
 *
 * @see netlink_interfaces_list_free
 */
void _netlink_interfaces_elem_free(gpointer data, gpointer user_data) {
   free(data);
   return;
}

/**
 * Compares one list element to the specified interface name.  Callback
 * function used to locate a list element by interface name.
 *
 * @see netlink_interfaces_mac2str
 * @see netlink_interfaces_ip2str
 */
gint _netlink_interfaces_elem_find(gconstpointer a, gconstpointer b) {
   char *ifname = (char *) b;
   GSList *elemdata = (GSList *) a;
   interface_info_t *intf;

   intf = (interface_info_t *) elemdata;
   if (intf->name == NULL)
      return -1;
   else
      return strncmp(ifname, intf->name, strlen(ifname));
}

#ifdef TESTING
void print_interfaces(gpointer data, gpointer user_data) {
   char *buf = NULL;
   char *ipbuf = NULL;
   interface_info_t *intf;

   intf = (interface_info_t *) data;
   printf("Interface %d\n", intf->i);
   printf("   Name: %s\n", intf->name);
   if (intf->ip_addr.s_addr != 0)
      printf("   IPv4: %s\n", netlink_format_ip_addr(AF_INET, intf, ipbuf));
   else
      printf("   IPv4: not set\n");
   if (intf->ip6_addr.s6_addr[0] != 0)
      printf("   IPv6: %s\n", netlink_format_ip_addr(AF_INET6, intf, ipbuf));
   else
      printf("   IPv6: not set\n");
   printf("    MAC: %s\n\n", netlink_format_mac_addr(buf, intf->mac));

   printf("   mac2str test for %s: |%s|\n", intf->name, netlink_interfaces_mac2str(intf->name));
   printf("    ip2str test for %s: |%s|\n", intf->name, netlink_interfaces_ip2str(intf->name));

   printf("----------------------------------------------------------------\n");

   return;
}

int main(void) {
   if (netlink_init_interfaces_list() == -1) {
      fprintf(stderr, "netlink_init_interfaces_list failure: %s\n", __func__);
      fflush(stderr);
      return EXIT_FAILURE;
   }

   g_slist_foreach(interfaces, print_interfaces, NULL);

   return EXIT_SUCCESS;
}
#endif