usb_moded  0.86.0+mer57
usb_moded-mac.c
Go to the documentation of this file.
1 
25 #include "usb_moded-mac.h"
26 
27 #include "usb_moded-log.h"
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 
33 /* ========================================================================= *
34  * Prototypes
35  * ========================================================================= */
36 
37 /* ------------------------------------------------------------------------- *
38  * MAC
39  * ------------------------------------------------------------------------- */
40 
41 static void mac_random_ether_addr (unsigned char *addr);
42 void mac_generate_random_mac(void);
43 char *mac_read_mac (void);
44 
45 /* ========================================================================= *
46  * Functions
47  * ========================================================================= */
48 
49 static void mac_random_ether_addr(unsigned char *addr)
50 {
51  LOG_REGISTER_CONTEXT;
52 
53  FILE *random;
54  size_t count = 0;
55 
56  random = fopen("/dev/urandom", "r");
57  count = fread(addr, 1, 6, random);
58  fclose(random);
59 
60  if(count > 0 )
61  {
62  addr [0] &= 0xfe; /* clear multicast bit */
63  addr [0] |= 0x02; /* set local assignment bit (IEEE802) */
64  }
65  else
66  log_warning("MAC generation failed!\n");
67 }
68 
69 void mac_generate_random_mac (void)
70 {
71  LOG_REGISTER_CONTEXT;
72 
73  unsigned char addr[6];
74  int i;
75  FILE *g_ether;
76 
77  log_debug("Getting random usb ethernet mac\n");
78  mac_random_ether_addr(addr);
79 
80  g_ether = fopen("/etc/modprobe.d/g_ether.conf", "w");
81  if(!g_ether)
82  {
83  log_warning("Failed to write mac address to /etc/modprobe.d/g_ether.conf\n");
84  return;
85  }
86  fprintf(g_ether, "options g_ether host_addr=");
87 
88  for(i=0; i<5; i++)
89  {
90  fprintf(g_ether, "%02x:",addr[i]);
91  }
92  fprintf(g_ether, "%02x\n",addr[i]);
93  fclose(g_ether);
94 }
95 
96 char * mac_read_mac(void)
97 {
98  LOG_REGISTER_CONTEXT;
99 
100  FILE *g_ether;
101  char *mac = NULL, *ret = NULL;
102  size_t read = 0;
103  int test = 0;
104 
105  g_ether = fopen("/etc/modprobe.d/g_ether.conf", "r");
106  if(!g_ether)
107  {
108  log_warning("Failed to read mac address from /etc/modprobe.d/g_ether.conf\n");
109  return NULL;
110  }
111  test = fseek(g_ether, 26, SEEK_SET);
112  if(test == -1)
113  {
114  fclose(g_ether);
115  return 0;
116  }
117  mac = malloc(17);
118  if(mac)
119  read = fread(mac, 1, 17, g_ether);
120  if(read == 17)
121  ret = strndup(mac,17);
122  else
123  ret = 0;
124 
125  free(mac);
126  fclose(g_ether);
127  return ret;
128 }
usb_moded-mac.h
usb_moded-log.h