#endif
#ifndef AVL_DEPTH
-static int lg(unsigned int u) __attribute__ ((__const__));
+static int lg(unsigned int u) __attribute__((__const__));
-static int lg(unsigned int u)
-{
+static int lg(unsigned int u) {
int r = 1;
- if(!u)
+ if(!u) {
return 0;
+ }
if(u & 0xffff0000) {
u >>= 16;
r += 2;
}
- if(u & 0x00000002)
+ if(u & 0x00000002) {
r++;
+ }
return r;
}
/* Internal helper functions */
-static int avl_check_balance(const avl_node_t *node)
-{
+static int avl_check_balance(const avl_node_t *node) {
#ifdef AVL_DEPTH
int d;
return d < -1 ? -1 : d > 1 ? 1 : 0;
#else
-/* int d;
- * d = lg(AVL_R_COUNT(node)) - lg(AVL_L_COUNT(node));
- * d = d<-1?-1:d>1?1:0;
- */
+ /* int d;
+ * d = lg(AVL_R_COUNT(node)) - lg(AVL_L_COUNT(node));
+ * d = d<-1?-1:d>1?1:0;
+ */
int pl, r;
pl = lg(AVL_L_COUNT(node));
r = AVL_R_COUNT(node);
- if(r >> pl + 1)
+ if(r >> pl + 1) {
return 1;
+ }
- if(pl < 2 || r >> pl - 2)
+ if(pl < 2 || r >> pl - 2) {
return 0;
+ }
return -1;
#endif
}
-static void avl_rebalance(avl_tree_t *tree, avl_node_t *node)
-{
+static void avl_rebalance(avl_tree_t *tree, avl_node_t *node) {
avl_node_t *child;
avl_node_t *gchild;
avl_node_t *parent;
parent = node->parent;
superparent =
- parent ? node ==
- parent->left ? &parent->left : &parent->right : &tree->root;
+ parent ? node ==
+ parent->left ? &parent->left : &parent->right : &tree->root;
- switch (avl_check_balance(node)) {
- case -1:
- child = node->left;
+ switch(avl_check_balance(node)) {
+ case -1:
+ child = node->left;
#ifdef AVL_DEPTH
- if(L_AVL_DEPTH(child) >= R_AVL_DEPTH(child)) {
+
+ if(L_AVL_DEPTH(child) >= R_AVL_DEPTH(child)) {
#else
- if(AVL_L_COUNT(child) >= AVL_R_COUNT(child)) {
+
+ if(AVL_L_COUNT(child) >= AVL_R_COUNT(child)) {
#endif
- node->left = child->right;
- if(node->left)
- node->left->parent = node;
-
- child->right = node;
- node->parent = child;
- *superparent = child;
- child->parent = parent;
+ node->left = child->right;
+
+ if(node->left) {
+ node->left->parent = node;
+ }
+
+ child->right = node;
+ node->parent = child;
+ *superparent = child;
+ child->parent = parent;
#ifdef AVL_COUNT
- node->count = AVL_CALC_COUNT(node);
- child->count = AVL_CALC_COUNT(child);
+ node->count = AVL_CALC_COUNT(node);
+ child->count = AVL_CALC_COUNT(child);
#endif
#ifdef AVL_DEPTH
- node->depth = AVL_CALC_DEPTH(node);
- child->depth = AVL_CALC_DEPTH(child);
+ node->depth = AVL_CALC_DEPTH(node);
+ child->depth = AVL_CALC_DEPTH(child);
#endif
- } else {
- gchild = child->right;
- node->left = gchild->right;
+ } else {
+ gchild = child->right;
+ node->left = gchild->right;
- if(node->left)
- node->left->parent = node;
- child->right = gchild->left;
+ if(node->left) {
+ node->left->parent = node;
+ }
+
+ child->right = gchild->left;
+
+ if(child->right) {
+ child->right->parent = child;
+ }
- if(child->right)
- child->right->parent = child;
- gchild->right = node;
+ gchild->right = node;
- gchild->right->parent = gchild;
- gchild->left = child;
+ gchild->right->parent = gchild;
+ gchild->left = child;
- gchild->left->parent = gchild;
+ gchild->left->parent = gchild;
- *superparent = gchild;
- gchild->parent = parent;
+ *superparent = gchild;
+ gchild->parent = parent;
#ifdef AVL_COUNT
- node->count = AVL_CALC_COUNT(node);
- child->count = AVL_CALC_COUNT(child);
- gchild->count = AVL_CALC_COUNT(gchild);
+ node->count = AVL_CALC_COUNT(node);
+ child->count = AVL_CALC_COUNT(child);
+ gchild->count = AVL_CALC_COUNT(gchild);
#endif
#ifdef AVL_DEPTH
- node->depth = AVL_CALC_DEPTH(node);
- child->depth = AVL_CALC_DEPTH(child);
- gchild->depth = AVL_CALC_DEPTH(gchild);
+ node->depth = AVL_CALC_DEPTH(node);
+ child->depth = AVL_CALC_DEPTH(child);
+ gchild->depth = AVL_CALC_DEPTH(gchild);
#endif
- }
- break;
+ }
+
+ break;
- case 1:
- child = node->right;
+ case 1:
+ child = node->right;
#ifdef AVL_DEPTH
- if(R_AVL_DEPTH(child) >= L_AVL_DEPTH(child)) {
+
+ if(R_AVL_DEPTH(child) >= L_AVL_DEPTH(child)) {
#else
- if(AVL_R_COUNT(child) >= AVL_L_COUNT(child)) {
+
+ if(AVL_R_COUNT(child) >= AVL_L_COUNT(child)) {
#endif
- node->right = child->left;
- if(node->right)
- node->right->parent = node;
- child->left = node;
- node->parent = child;
- *superparent = child;
- child->parent = parent;
+ node->right = child->left;
+
+ if(node->right) {
+ node->right->parent = node;
+ }
+
+ child->left = node;
+ node->parent = child;
+ *superparent = child;
+ child->parent = parent;
#ifdef AVL_COUNT
- node->count = AVL_CALC_COUNT(node);
- child->count = AVL_CALC_COUNT(child);
+ node->count = AVL_CALC_COUNT(node);
+ child->count = AVL_CALC_COUNT(child);
#endif
#ifdef AVL_DEPTH
- node->depth = AVL_CALC_DEPTH(node);
- child->depth = AVL_CALC_DEPTH(child);
+ node->depth = AVL_CALC_DEPTH(node);
+ child->depth = AVL_CALC_DEPTH(child);
#endif
- } else {
- gchild = child->left;
- node->right = gchild->left;
+ } else {
+ gchild = child->left;
+ node->right = gchild->left;
+
+ if(node->right) {
+ node->right->parent = node;
+ }
- if(node->right)
- node->right->parent = node;
- child->left = gchild->right;
+ child->left = gchild->right;
+
+ if(child->left) {
+ child->left->parent = child;
+ }
- if(child->left)
- child->left->parent = child;
- gchild->left = node;
+ gchild->left = node;
- gchild->left->parent = gchild;
- gchild->right = child;
+ gchild->left->parent = gchild;
+ gchild->right = child;
- gchild->right->parent = gchild;
+ gchild->right->parent = gchild;
- *superparent = gchild;
- gchild->parent = parent;
+ *superparent = gchild;
+ gchild->parent = parent;
#ifdef AVL_COUNT
- node->count = AVL_CALC_COUNT(node);
- child->count = AVL_CALC_COUNT(child);
- gchild->count = AVL_CALC_COUNT(gchild);
+ node->count = AVL_CALC_COUNT(node);
+ child->count = AVL_CALC_COUNT(child);
+ gchild->count = AVL_CALC_COUNT(gchild);
#endif
#ifdef AVL_DEPTH
- node->depth = AVL_CALC_DEPTH(node);
- child->depth = AVL_CALC_DEPTH(child);
- gchild->depth = AVL_CALC_DEPTH(gchild);
+ node->depth = AVL_CALC_DEPTH(node);
+ child->depth = AVL_CALC_DEPTH(child);
+ gchild->depth = AVL_CALC_DEPTH(gchild);
#endif
- }
- break;
+ }
- default:
+ break;
+
+ default:
#ifdef AVL_COUNT
- node->count = AVL_CALC_COUNT(node);
+ node->count = AVL_CALC_COUNT(node);
#endif
#ifdef AVL_DEPTH
- node->depth = AVL_CALC_DEPTH(node);
+ node->depth = AVL_CALC_DEPTH(node);
#endif
}
+
node = parent;
}
}
/* (De)constructors */
-avl_tree_t *avl_alloc_tree(avl_compare_t compare, avl_action_t delete)
-{
+avl_tree_t *avl_alloc_tree(avl_compare_t compare, avl_action_t delete) {
avl_tree_t *tree;
tree = xmalloc_and_zero(sizeof(avl_tree_t));
return tree;
}
-void avl_free_tree(avl_tree_t *tree)
-{
+void avl_free_tree(avl_tree_t *tree) {
free(tree);
}
-avl_node_t *avl_alloc_node(void)
-{
+avl_node_t *avl_alloc_node(void) {
return xmalloc_and_zero(sizeof(avl_node_t));
}
-void avl_free_node(avl_tree_t *tree, avl_node_t *node)
-{
- if(node->data && tree->delete)
+void avl_free_node(avl_tree_t *tree, avl_node_t *node) {
+ if(node->data && tree->delete) {
tree->delete(node->data);
+ }
free(node);
}
/* Searching */
-void *avl_search(const avl_tree_t *tree, const void *data)
-{
+void *avl_search(const avl_tree_t *tree, const void *data) {
avl_node_t *node;
node = avl_search_node(tree, data);
return node ? node->data : NULL;
}
-void *avl_search_closest(const avl_tree_t *tree, const void *data, int *result)
-{
+void *avl_search_closest(const avl_tree_t *tree, const void *data, int *result) {
avl_node_t *node;
node = avl_search_closest_node(tree, data, result);
return node ? node->data : NULL;
}
-void *avl_search_closest_smaller(const avl_tree_t *tree, const void *data)
-{
+void *avl_search_closest_smaller(const avl_tree_t *tree, const void *data) {
avl_node_t *node;
node = avl_search_closest_smaller_node(tree, data);
return node ? node->data : NULL;
}
-void *avl_search_closest_greater(const avl_tree_t *tree, const void *data)
-{
+void *avl_search_closest_greater(const avl_tree_t *tree, const void *data) {
avl_node_t *node;
node = avl_search_closest_greater_node(tree, data);
return node ? node->data : NULL;
}
-avl_node_t *avl_search_node(const avl_tree_t *tree, const void *data)
-{
+avl_node_t *avl_search_node(const avl_tree_t *tree, const void *data) {
avl_node_t *node;
int result;
}
avl_node_t *avl_search_closest_node(const avl_tree_t *tree, const void *data,
- int *result)
-{
+ int *result) {
avl_node_t *node;
int c;
node = tree->root;
if(!node) {
- if(result)
+ if(result) {
*result = 0;
+ }
+
return NULL;
}
c = tree->compare(data, node->data);
if(c < 0) {
- if(node->left)
+ if(node->left) {
node = node->left;
- else {
- if(result)
+ } else {
+ if(result) {
*result = -1;
+ }
+
break;
}
} else if(c > 0) {
- if(node->right)
+ if(node->right) {
node = node->right;
- else {
- if(result)
+ } else {
+ if(result) {
*result = 1;
+ }
+
break;
}
} else {
- if(result)
+ if(result) {
*result = 0;
+ }
+
break;
}
}
}
avl_node_t *avl_search_closest_smaller_node(const avl_tree_t *tree,
- const void *data)
-{
+ const void *data) {
avl_node_t *node;
int result;
node = avl_search_closest_node(tree, data, &result);
- if(result < 0)
+ if(result < 0) {
node = node->prev;
+ }
return node;
}
avl_node_t *avl_search_closest_greater_node(const avl_tree_t *tree,
- const void *data)
-{
+ const void *data) {
avl_node_t *node;
int result;
node = avl_search_closest_node(tree, data, &result);
- if(result > 0)
+ if(result > 0) {
node = node->next;
+ }
return node;
}
/* Insertion and deletion */
-avl_node_t *avl_insert(avl_tree_t *tree, void *data)
-{
+avl_node_t *avl_insert(avl_tree_t *tree, void *data) {
avl_node_t *closest, *new;
int result;
} else {
closest = avl_search_closest_node(tree, data, &result);
- switch (result) {
- case -1:
- new = avl_alloc_node();
- new->data = data;
- avl_insert_before(tree, closest, new);
- break;
+ switch(result) {
+ case -1:
+ new = avl_alloc_node();
+ new->data = data;
+ avl_insert_before(tree, closest, new);
+ break;
- case 1:
- new = avl_alloc_node();
- new->data = data;
- avl_insert_after(tree, closest, new);
- break;
+ case 1:
+ new = avl_alloc_node();
+ new->data = data;
+ avl_insert_after(tree, closest, new);
+ break;
- default:
- return NULL;
+ default:
+ return NULL;
}
}
return new;
}
-avl_node_t *avl_insert_node(avl_tree_t *tree, avl_node_t *node)
-{
+avl_node_t *avl_insert_node(avl_tree_t *tree, avl_node_t *node) {
avl_node_t *closest;
int result;
- if(!tree->root)
+ if(!tree->root) {
avl_insert_top(tree, node);
- else {
+ } else {
closest = avl_search_closest_node(tree, node->data, &result);
- switch (result) {
- case -1:
- avl_insert_before(tree, closest, node);
- break;
+ switch(result) {
+ case -1:
+ avl_insert_before(tree, closest, node);
+ break;
- case 1:
- avl_insert_after(tree, closest, node);
- break;
+ case 1:
+ avl_insert_after(tree, closest, node);
+ break;
- case 0:
- return NULL;
+ case 0:
+ return NULL;
}
}
return node;
}
-void avl_insert_top(avl_tree_t *tree, avl_node_t *node)
-{
+void avl_insert_top(avl_tree_t *tree, avl_node_t *node) {
node->prev = node->next = node->parent = NULL;
tree->head = tree->tail = tree->root = node;
}
void avl_insert_before(avl_tree_t *tree, avl_node_t *before,
- avl_node_t *node)
-{
+ avl_node_t *node) {
if(!before) {
- if(tree->tail)
+ if(tree->tail) {
avl_insert_after(tree, tree->tail, node);
- else
+ } else {
avl_insert_top(tree, node);
+ }
+
return;
}
return;
}
- if(before->prev)
+ if(before->prev) {
before->prev->next = node;
- else
+ } else {
tree->head = node;
+ }
before->prev = node;
before->left = node;
avl_rebalance(tree, before);
}
-void avl_insert_after(avl_tree_t *tree, avl_node_t *after, avl_node_t *node)
-{
+void avl_insert_after(avl_tree_t *tree, avl_node_t *after, avl_node_t *node) {
if(!after) {
- if(tree->head)
+ if(tree->head) {
avl_insert_before(tree, tree->head, node);
- else
+ } else {
avl_insert_top(tree, node);
+ }
+
return;
}
node->parent = after;
node->next = after->next;
- if(after->next)
+ if(after->next) {
after->next->prev = node;
- else
+ } else {
tree->tail = node;
+ }
after->next = node;
after->right = node;
avl_rebalance(tree, after);
}
-avl_node_t *avl_unlink(avl_tree_t *tree, void *data)
-{
+avl_node_t *avl_unlink(avl_tree_t *tree, void *data) {
avl_node_t *node;
node = avl_search_node(tree, data);
- if(node)
+ if(node) {
avl_unlink_node(tree, node);
+ }
return node;
}
-void avl_unlink_node(avl_tree_t *tree, avl_node_t *node)
-{
+void avl_unlink_node(avl_tree_t *tree, avl_node_t *node) {
avl_node_t *parent;
avl_node_t **superparent;
avl_node_t *subst, *left, *right;
avl_node_t *balnode;
- if(node->prev)
+ if(node->prev) {
node->prev->next = node->next;
- else
+ } else {
tree->head = node->next;
- if(node->next)
+ }
+
+ if(node->next) {
node->next->prev = node->prev;
- else
+ } else {
tree->tail = node->prev;
+ }
parent = node->parent;
superparent =
- parent ? node ==
- parent->left ? &parent->left : &parent->right : &tree->root;
+ parent ? node ==
+ parent->left ? &parent->left : &parent->right : &tree->root;
left = node->left;
right = node->right;
+
if(!left) {
*superparent = right;
- if(right)
+ if(right) {
right->parent = parent;
+ }
balnode = parent;
} else if(!right) {
balnode = parent;
} else {
subst = node->prev;
- if(!subst) // This only happens if node is not actually in a tree at all.
+
+ if(!subst) { // This only happens if node is not actually in a tree at all.
abort();
+ }
if(subst == left) {
balnode = subst;
balnode = subst->parent;
balnode->right = subst->left;
- if(balnode->right)
+ if(balnode->right) {
balnode->right->parent = balnode;
+ }
subst->left = left;
left->parent = subst;
#endif
}
-void avl_delete_node(avl_tree_t *tree, avl_node_t *node)
-{
+void avl_delete_node(avl_tree_t *tree, avl_node_t *node) {
avl_unlink_node(tree, node);
avl_free_node(tree, node);
}
-void avl_delete(avl_tree_t *tree, void *data)
-{
+void avl_delete(avl_tree_t *tree, void *data) {
avl_node_t *node;
node = avl_search_node(tree, data);
- if(node)
+ if(node) {
avl_delete_node(tree, node);
+ }
}
/* Fast tree cleanup */
-void avl_delete_tree(avl_tree_t *tree)
-{
+void avl_delete_tree(avl_tree_t *tree) {
avl_node_t *node, *next;
for(node = tree->head; node; node = next) {
/* Tree walking */
-void avl_foreach(const avl_tree_t *tree, avl_action_t action)
-{
+void avl_foreach(const avl_tree_t *tree, avl_action_t action) {
avl_node_t *node, *next;
for(node = tree->head; node; node = next) {
}
}
-void avl_foreach_node(const avl_tree_t *tree, avl_action_t action)
-{
+void avl_foreach_node(const avl_tree_t *tree, avl_action_t action) {
avl_node_t *node, *next;
for(node = tree->head; node; node = next) {
/* Indexing */
#ifdef AVL_COUNT
-unsigned int avl_count(const avl_tree_t *tree)
-{
+unsigned int avl_count(const avl_tree_t *tree) {
return AVL_NODE_COUNT(tree->root);
}
-avl_node_t *avl_get_node(const avl_tree_t *tree, unsigned int index)
-{
+avl_node_t *avl_get_node(const avl_tree_t *tree, unsigned int index) {
avl_node_t *node;
unsigned int c;
return NULL;
}
-unsigned int avl_index(const avl_node_t *node)
-{
+unsigned int avl_index(const avl_node_t *node) {
avl_node_t *next;
unsigned int index;
index = AVL_L_COUNT(node);
while((next = node->parent)) {
- if(node == next->right)
+ if(node == next->right) {
index += AVL_L_COUNT(next) + 1;
+ }
+
node = next;
}
}
#endif
#ifdef AVL_DEPTH
-unsigned int avl_depth(const avl_tree_t *tree)
-{
+unsigned int avl_depth(const avl_tree_t *tree) {
return AVL_NODE_DEPTH(tree->root);
}
#endif
#ifdef HAVE_NET_IF_UTUN_H
static bool setup_utun(void) {
device_fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
+
if(device_fd == -1) {
logger(LOG_ERR, "Could not open PF_SYSTEM socket: %s\n", strerror(errno));
return false;
}
struct ctl_info info = {};
+
strlcpy(info.ctl_name, UTUN_CONTROL_NAME, sizeof(info.ctl_name));
if(ioctl(device_fd, CTLIOCGINFO, &info) == -1) {
int unit = -1;
char *p = strstr(device, "utun"), *e = NULL;
+
if(p) {
unit = strtol(p + 4, &e, 10);
- if(!e)
+
+ if(!e) {
unit = -1;
+ }
}
struct sockaddr_ctl sc = {
char name[64] = "";
socklen_t len = sizeof(name);
+
if(getsockopt(device_fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, name, &len)) {
iface = xstrdup(device);
} else {
// Find out which device file to open
if(!get_config_string(lookup_config(config_tree, "Device"), &device)) {
- if(routing_mode == RMODE_ROUTER)
+ if(routing_mode == RMODE_ROUTER) {
device = xstrdup(DEFAULT_TUN_DEVICE);
- else
+ } else {
device = xstrdup(DEFAULT_TAP_DEVICE);
+ }
}
// Find out if it's supposed to be a tun or a tap device
if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
if(!strcasecmp(type, "tun"))
- /* use default */;
+ /* use default */;
+
#ifdef ENABLE_TUNEMU
- else if(!strcasecmp(type, "tunemu"))
+ else if(!strcasecmp(type, "tunemu")) {
device_type = DEVICE_TYPE_TUNEMU;
+ }
+
#endif
#ifdef HAVE_NET_IF_UTUN_H
- else if(!strcasecmp(type, "utun"))
+ else if(!strcasecmp(type, "utun")) {
device_type = DEVICE_TYPE_UTUN;
+ }
+
#endif
- else if(!strcasecmp(type, "tunnohead"))
+ else if(!strcasecmp(type, "tunnohead")) {
device_type = DEVICE_TYPE_TUN;
- else if(!strcasecmp(type, "tunifhead"))
+ } else if(!strcasecmp(type, "tunifhead")) {
device_type = DEVICE_TYPE_TUNIFHEAD;
- else if(!strcasecmp(type, "tap"))
+ } else if(!strcasecmp(type, "tap")) {
device_type = DEVICE_TYPE_TAP;
- else {
+ } else {
logger(LOG_ERR, "Unknown device type %s!", type);
return false;
}
} else {
#ifdef HAVE_NET_IF_UTUN_H
- if(strncmp(device, "utun", 4) == 0 || strncmp(device, "/dev/utun", 9) == 0)
+
+ if(strncmp(device, "utun", 4) == 0 || strncmp(device, "/dev/utun", 9) == 0) {
device_type = DEVICE_TYPE_UTUN;
- else
+ } else
#endif
- if(strstr(device, "tap") || routing_mode != RMODE_ROUTER)
- device_type = DEVICE_TYPE_TAP;
+ if(strstr(device, "tap") || routing_mode != RMODE_ROUTER) {
+ device_type = DEVICE_TYPE_TAP;
+ }
}
if(routing_mode == RMODE_SWITCH && device_type != DEVICE_TYPE_TAP) {
switch(device_type) {
#ifdef ENABLE_TUNEMU
- case DEVICE_TYPE_TUNEMU: {
- char dynamic_name[256] = "";
- device_fd = tunemu_open(dynamic_name);
- }
- break;
+
+ case DEVICE_TYPE_TUNEMU: {
+ char dynamic_name[256] = "";
+ device_fd = tunemu_open(dynamic_name);
+ }
+ break;
#endif
#ifdef HAVE_NET_IF_UTUN_H
- case DEVICE_TYPE_UTUN:
- return setup_utun();
+
+ case DEVICE_TYPE_UTUN:
+ return setup_utun();
#endif
- default:
- device_fd = open(device, O_RDWR | O_NONBLOCK);
+
+ default:
+ device_fd = open(device, O_RDWR | O_NONBLOCK);
}
if(device_fd < 0) {
realname = fdevname(device_fd);
#elif defined(HAVE_DEVNAME)
struct stat buf;
- if(!fstat(device_fd, &buf))
+
+ if(!fstat(device_fd, &buf)) {
realname = devname(buf.st_rdev, S_IFCHR);
+ }
+
#endif
- if(!realname)
+ if(!realname) {
realname = device;
+ }
- if(!get_config_string(lookup_config(config_tree, "Interface"), &iface))
+ if(!get_config_string(lookup_config(config_tree, "Interface"), &iface)) {
iface = xstrdup(strrchr(realname, '/') ? strrchr(realname, '/') + 1 : realname);
- else if(strcmp(iface, strrchr(realname, '/') ? strrchr(realname, '/') + 1 : realname))
+ } else if(strcmp(iface, strrchr(realname, '/') ? strrchr(realname, '/') + 1 : realname)) {
logger(LOG_WARNING, "Warning: Interface does not match Device. $INTERFACE might be set incorrectly.");
+ }
// Configure the device as best as we can
switch(device_type) {
- default:
- device_type = DEVICE_TYPE_TUN;
- case DEVICE_TYPE_TUN:
+ default:
+ device_type = DEVICE_TYPE_TUN;
+
+ case DEVICE_TYPE_TUN:
#ifdef TUNSIFHEAD
- {
+ {
const int zero = 0;
+
if(ioctl(device_fd, TUNSIFHEAD, &zero, sizeof(zero)) == -1) {
logger(LOG_ERR, "System call `%s' failed: %s", "ioctl", strerror(errno));
return false;
}
}
+
#endif
#if defined(TUNSIFMODE) && defined(IFF_BROADCAST) && defined(IFF_MULTICAST)
{
}
#endif
- device_info = "Generic BSD tun device";
- break;
- case DEVICE_TYPE_TUNIFHEAD:
+ device_info = "Generic BSD tun device";
+ break;
+
+ case DEVICE_TYPE_TUNIFHEAD:
#ifdef TUNSIFHEAD
{
const int one = 1;
+
if(ioctl(device_fd, TUNSIFHEAD, &one, sizeof(one)) == -1) {
logger(LOG_ERR, "System call `%s' failed: %s", "ioctl", strerror(errno));
return false;
}
}
+
#endif
#if defined(TUNSIFMODE) && defined(IFF_BROADCAST) && defined(IFF_MULTICAST)
{
- const int mode = IFF_BROADCAST | IFF_MULTICAST;
- ioctl(device_fd, TUNSIFMODE, &mode, sizeof(mode));
+ const int mode = IFF_BROADCAST | IFF_MULTICAST;
+ ioctl(device_fd, TUNSIFMODE, &mode, sizeof(mode));
}
#endif
- device_info = "Generic BSD tun device";
- break;
- case DEVICE_TYPE_TAP:
- if(routing_mode == RMODE_ROUTER)
- overwrite_mac = true;
- device_info = "Generic BSD tap device";
+ device_info = "Generic BSD tun device";
+ break;
+
+ case DEVICE_TYPE_TAP:
+ if(routing_mode == RMODE_ROUTER) {
+ overwrite_mac = true;
+ }
+
+ device_info = "Generic BSD tap device";
#ifdef TAPGIFNAME
- {
- struct ifreq ifr;
- if(ioctl(device_fd, TAPGIFNAME, (void*)&ifr) == 0) {
- if(iface)
- free(iface);
- iface = xstrdup(ifr.ifr_name);
+ {
+ struct ifreq ifr;
+
+ if(ioctl(device_fd, TAPGIFNAME, (void *)&ifr) == 0) {
+ if(iface) {
+ free(iface);
}
+
+ iface = xstrdup(ifr.ifr_name);
}
-
+ }
+
#endif
- break;
+ break;
#ifdef ENABLE_TUNEMU
- case DEVICE_TYPE_TUNEMU:
- device_info = "BSD tunemu device";
- break;
+
+ case DEVICE_TYPE_TUNEMU:
+ device_info = "BSD tunemu device";
+ break;
#endif
}
#ifdef SIOCGIFADDR
- if(overwrite_mac)
+
+ if(overwrite_mac) {
ioctl(device_fd, SIOCGIFADDR, mymac.x);
+ }
+
#endif
logger(LOG_INFO, "%s is a %s", device, device_info);
static void close_device(void) {
switch(device_type) {
#ifdef ENABLE_TUNEMU
- case DEVICE_TYPE_TUNEMU:
- tunemu_close(device_fd);
- break;
+
+ case DEVICE_TYPE_TUNEMU:
+ tunemu_close(device_fd);
+ break;
#endif
- default:
- close(device_fd);
+
+ default:
+ close(device_fd);
}
free(device);
int lenin;
switch(device_type) {
- case DEVICE_TYPE_TUN:
+ case DEVICE_TYPE_TUN:
#ifdef ENABLE_TUNEMU
- case DEVICE_TYPE_TUNEMU:
- if(device_type == DEVICE_TYPE_TUNEMU)
- lenin = tunemu_read(device_fd, packet->data + 14, MTU - 14);
- else
+ case DEVICE_TYPE_TUNEMU:
+ if(device_type == DEVICE_TYPE_TUNEMU) {
+ lenin = tunemu_read(device_fd, packet->data + 14, MTU - 14);
+ } else
#endif
- lenin = read(device_fd, packet->data + 14, MTU - 14);
+ lenin = read(device_fd, packet->data + 14, MTU - 14);
- if(lenin <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
+ if(lenin <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
+ device, strerror(errno));
+ return false;
+ }
- switch(packet->data[14] >> 4) {
- case 4:
- packet->data[12] = 0x08;
- packet->data[13] = 0x00;
- break;
- case 6:
- packet->data[12] = 0x86;
- packet->data[13] = 0xDD;
- break;
- default:
- ifdebug(TRAFFIC) logger(LOG_ERR,
- "Unknown IP version %d while reading packet from %s %s",
- packet->data[14] >> 4, device_info, device);
- return false;
- }
+ switch(packet->data[14] >> 4) {
+ case 4:
+ packet->data[12] = 0x08;
+ packet->data[13] = 0x00;
+ break;
- memset(packet->data, 0, 12);
- packet->len = lenin + 14;
+ case 6:
+ packet->data[12] = 0x86;
+ packet->data[13] = 0xDD;
break;
- case DEVICE_TYPE_UTUN:
- case DEVICE_TYPE_TUNIFHEAD: {
- if((lenin = read(device_fd, packet->data + 10, MTU - 10)) <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
+ default:
+ ifdebug(TRAFFIC) logger(LOG_ERR,
+ "Unknown IP version %d while reading packet from %s %s",
+ packet->data[14] >> 4, device_info, device);
+ return false;
+ }
- switch(packet->data[14] >> 4) {
- case 4:
- packet->data[12] = 0x08;
- packet->data[13] = 0x00;
- break;
- case 6:
- packet->data[12] = 0x86;
- packet->data[13] = 0xDD;
- break;
- default:
- ifdebug(TRAFFIC) logger(LOG_ERR,
- "Unknown IP version %d while reading packet from %s %s",
- packet->data[14] >> 4, device_info, device);
- return false;
- }
+ memset(packet->data, 0, 12);
+ packet->len = lenin + 14;
+ break;
- memset(packet->data, 0, 12);
- packet->len = lenin + 10;
- break;
+ case DEVICE_TYPE_UTUN:
+ case DEVICE_TYPE_TUNIFHEAD: {
+ if((lenin = read(device_fd, packet->data + 10, MTU - 10)) <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
+ device, strerror(errno));
+ return false;
}
- case DEVICE_TYPE_TAP:
- if((lenin = read(device_fd, packet->data, MTU)) <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
+ switch(packet->data[14] >> 4) {
+ case 4:
+ packet->data[12] = 0x08;
+ packet->data[13] = 0x00;
+ break;
- packet->len = lenin;
+ case 6:
+ packet->data[12] = 0x86;
+ packet->data[13] = 0xDD;
break;
default:
+ ifdebug(TRAFFIC) logger(LOG_ERR,
+ "Unknown IP version %d while reading packet from %s %s",
+ packet->data[14] >> 4, device_info, device);
+ return false;
+ }
+
+ memset(packet->data, 0, 12);
+ packet->len = lenin + 10;
+ break;
+ }
+
+ case DEVICE_TYPE_TAP:
+ if((lenin = read(device_fd, packet->data, MTU)) <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
+ device, strerror(errno));
return false;
+ }
+
+ packet->len = lenin;
+ break;
+
+ default:
+ return false;
}
-
+
device_total_in += packet->len;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Read packet of %d bytes from %s",
- packet->len, device_info);
+ packet->len, device_info);
return true;
}
static bool write_packet(vpn_packet_t *packet) {
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
- packet->len, device_info);
+ packet->len, device_info);
switch(device_type) {
- case DEVICE_TYPE_TUN:
- if(write(device_fd, packet->data + 14, packet->len - 14) < 0) {
- logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
- break;
+ case DEVICE_TYPE_TUN:
+ if(write(device_fd, packet->data + 14, packet->len - 14) < 0) {
+ logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
+ device, strerror(errno));
+ return false;
+ }
- case DEVICE_TYPE_UTUN:
- case DEVICE_TYPE_TUNIFHEAD: {
- int af = (packet->data[12] << 8) + packet->data[13];
- uint32_t type;
-
- switch (af) {
- case 0x0800:
- type = htonl(AF_INET);
- break;
- case 0x86DD:
- type = htonl(AF_INET6);
- break;
- default:
- ifdebug(TRAFFIC) logger(LOG_ERR,
- "Unknown address family %x while writing packet to %s %s",
- af, device_info, device);
- return false;
- }
+ break;
- memcpy(packet->data + 10, &type, sizeof(type));
+ case DEVICE_TYPE_UTUN:
+ case DEVICE_TYPE_TUNIFHEAD: {
+ int af = (packet->data[12] << 8) + packet->data[13];
+ uint32_t type;
- if(write(device_fd, packet->data + 10, packet->len - 10) < 0) {
- logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
- strerror(errno));
- return false;
- }
- break;
- }
-
- case DEVICE_TYPE_TAP:
- if(write(device_fd, packet->data, packet->len) < 0) {
- logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
+ switch(af) {
+ case 0x0800:
+ type = htonl(AF_INET);
break;
-#ifdef ENABLE_TUNEMU
- case DEVICE_TYPE_TUNEMU:
- if(tunemu_write(device_fd, packet->data + 14, packet->len - 14) < 0) {
- logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
- device, strerror(errno));
- return false;
- }
+ case 0x86DD:
+ type = htonl(AF_INET6);
break;
-#endif
default:
+ ifdebug(TRAFFIC) logger(LOG_ERR,
+ "Unknown address family %x while writing packet to %s %s",
+ af, device_info, device);
+ return false;
+ }
+
+ memcpy(packet->data + 10, &type, sizeof(type));
+
+ if(write(device_fd, packet->data + 10, packet->len - 10) < 0) {
+ logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
+ strerror(errno));
+ return false;
+ }
+
+ break;
+ }
+
+ case DEVICE_TYPE_TAP:
+ if(write(device_fd, packet->data, packet->len) < 0) {
+ logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
+ device, strerror(errno));
return false;
+ }
+
+ break;
+
+#ifdef ENABLE_TUNEMU
+
+ case DEVICE_TYPE_TUNEMU:
+ if(tunemu_write(device_fd, packet->data + 14, packet->len - 14) < 0) {
+ logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
+ device, strerror(errno));
+ return false;
+ }
+
+ break;
+#endif
+
+ default:
+ return false;
}
device_total_out += packet->len;
/*
* tunemu - Tun device emulation for Darwin
* Copyright (C) 2009 Friedrich Schöller <friedrich.schoeller@gmail.com>
- *
+ *
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ *
*/
#include "tunemu.h"
#define PPPPROTO_CTL 1
-#define PPP_IP 0x21
-#define PPP_IPV6 0x57
+#define PPP_IP 0x21
+#define PPP_IPV6 0x57
#define SC_LOOP_TRAFFIC 0x00000200
-#define PPPIOCNEWUNIT _IOWR('t', 62, int)
-#define PPPIOCSFLAGS _IOW('t', 89, int)
-#define PPPIOCSNPMODE _IOW('t', 75, struct npioctl)
-#define PPPIOCATTCHAN _IOW('t', 56, int)
-#define PPPIOCGCHAN _IOR('t', 55, int)
-#define PPPIOCCONNECT _IOW('t', 58, int)
-#define PPPIOCGUNIT _IOR('t', 86, int)
+#define PPPIOCNEWUNIT _IOWR('t', 62, int)
+#define PPPIOCSFLAGS _IOW('t', 89, int)
+#define PPPIOCSNPMODE _IOW('t', 75, struct npioctl)
+#define PPPIOCATTCHAN _IOW('t', 56, int)
+#define PPPIOCGCHAN _IOR('t', 55, int)
+#define PPPIOCCONNECT _IOW('t', 58, int)
+#define PPPIOCGUNIT _IOR('t', 86, int)
-struct sockaddr_ppp
-{
+struct sockaddr_ppp {
u_int8_t ppp_len;
u_int8_t ppp_family;
u_int16_t ppp_proto;
u_int32_t ppp_cookie;
};
-enum NPmode
-{
+enum NPmode {
NPMODE_PASS,
- NPMODE_DROP,
- NPMODE_ERROR,
- NPMODE_QUEUE
+ NPMODE_DROP,
+ NPMODE_ERROR,
+ NPMODE_QUEUE
};
-struct npioctl
-{
+struct npioctl {
int protocol;
enum NPmode mode;
};
static int data_buffer_length = 0;
static char *data_buffer = NULL;
-static void tun_error(char *format, ...)
-{
+static void tun_error(char *format, ...) {
va_list vl;
va_start(vl, format);
vsnprintf(tunemu_error, ERROR_BUFFER_SIZE, format, vl);
va_end(vl);
}
-static void tun_noerror()
-{
+static void tun_noerror() {
*tunemu_error = 0;
}
-static void closeall()
-{
- int fd = getdtablesize();
- while (fd--)
+static void closeall() {
+ int fd = getdtablesize();
+
+ while(fd--) {
close(fd);
+ }
- open("/dev/null", O_RDWR, 0);
- dup(0);
- dup(0);
+ open("/dev/null", O_RDWR, 0);
+ dup(0);
+ dup(0);
}
-static int ppp_load_kext()
-{
+static int ppp_load_kext() {
int pid = fork();
- if (pid < 0)
- {
+
+ if(pid < 0) {
tun_error("fork for ppp kext: %s", strerror(errno));
return -1;
}
- if (pid == 0)
- {
+ if(pid == 0) {
closeall();
execle("/sbin/kextload", "kextload", PPP_KEXT_PATH, NULL, NULL);
exit(1);
}
int status;
- while (waitpid(pid, &status, 0) < 0)
- {
- if (errno == EINTR)
+
+ while(waitpid(pid, &status, 0) < 0) {
+ if(errno == EINTR) {
continue;
+ }
tun_error("waitpid for ppp kext: %s", strerror(errno));
return -1;
}
- if (WEXITSTATUS(status) != 0)
- {
+ if(WEXITSTATUS(status) != 0) {
tun_error("could not load ppp kext \"%s\"", PPP_KEXT_PATH);
return -1;
}
return 0;
}
-static int ppp_new_instance()
-{
+static int ppp_new_instance() {
// create ppp socket
- int ppp_sockfd = socket(PF_PPP, SOCK_RAW, PPPPROTO_CTL);
- if (ppp_sockfd < 0)
- {
- if (ppp_load_kext() < 0)
+ int ppp_sockfd = socket(PF_PPP, SOCK_RAW, PPPPROTO_CTL);
+
+ if(ppp_sockfd < 0) {
+ if(ppp_load_kext() < 0) {
return -1;
+ }
ppp_sockfd = socket(PF_PPP, SOCK_RAW, PPPPROTO_CTL);
- if (ppp_sockfd < 0)
- {
+
+ if(ppp_sockfd < 0) {
tun_error("creating ppp socket: %s", strerror(errno));
return -1;
}
}
// connect to ppp procotol
- struct sockaddr_ppp pppaddr;
- pppaddr.ppp_len = sizeof(struct sockaddr_ppp);
- pppaddr.ppp_family = AF_PPP;
- pppaddr.ppp_proto = PPPPROTO_CTL;
- pppaddr.ppp_cookie = 0;
- if (connect(ppp_sockfd, (struct sockaddr *)&pppaddr, sizeof(struct sockaddr_ppp)) < 0)
- {
+ struct sockaddr_ppp pppaddr;
+ pppaddr.ppp_len = sizeof(struct sockaddr_ppp);
+ pppaddr.ppp_family = AF_PPP;
+ pppaddr.ppp_proto = PPPPROTO_CTL;
+ pppaddr.ppp_cookie = 0;
+
+ if(connect(ppp_sockfd, (struct sockaddr *)&pppaddr, sizeof(struct sockaddr_ppp)) < 0) {
tun_error("connecting ppp socket: %s", strerror(errno));
close(ppp_sockfd);
return -1;
- }
+ }
tun_noerror();
return ppp_sockfd;
}
-static int ppp_new_unit(int *unit_number)
-{
+static int ppp_new_unit(int *unit_number) {
int fd = ppp_new_instance();
- if (fd < 0)
+
+ if(fd < 0) {
return -1;
+ }
// create ppp unit
- if (ioctl(fd, PPPIOCNEWUNIT, unit_number) < 0)
- {
+ if(ioctl(fd, PPPIOCNEWUNIT, unit_number) < 0) {
tun_error("creating ppp unit: %s", strerror(errno));
close(fd);
return -1;
- }
+ }
tun_noerror();
return fd;
}
-static int ppp_setup_unit(int unit_fd)
-{
+static int ppp_setup_unit(int unit_fd) {
// send traffic to program
int flags = SC_LOOP_TRAFFIC;
- if (ioctl(unit_fd, PPPIOCSFLAGS, &flags) < 0)
- {
+
+ if(ioctl(unit_fd, PPPIOCSFLAGS, &flags) < 0) {
tun_error("setting ppp loopback mode: %s", strerror(errno));
return -1;
- }
+ }
// allow packets
struct npioctl npi;
npi.protocol = PPP_IP;
npi.mode = NPMODE_PASS;
- if (ioctl(unit_fd, PPPIOCSNPMODE, &npi) < 0)
- {
+
+ if(ioctl(unit_fd, PPPIOCSNPMODE, &npi) < 0) {
tun_error("starting ppp unit: %s", strerror(errno));
return -1;
}
return 0;
}
-static int open_pcap()
-{
- if (pcap != NULL)
- {
+static int open_pcap() {
+ if(pcap != NULL) {
pcap_use_count++;
return 0;
}
pcap = pcap_open_live("lo0", BUFSIZ, 0, 1, errbuf);
pcap_use_count = 1;
- if (pcap == NULL)
- {
+ if(pcap == NULL) {
tun_error("opening pcap: %s", errbuf);
return -1;
}
return 0;
}
-static void close_pcap()
-{
- if (pcap == NULL)
+static void close_pcap() {
+ if(pcap == NULL) {
return;
+ }
pcap_use_count--;
- if (pcap_use_count == 0)
- {
+
+ if(pcap_use_count == 0) {
pcap_close(pcap);
pcap = NULL;
}
}
-static void allocate_data_buffer(int size)
-{
- if (data_buffer_length < size)
- {
+static void allocate_data_buffer(int size) {
+ if(data_buffer_length < size) {
free(data_buffer);
data_buffer_length = size;
data_buffer = malloc(data_buffer_length);
}
}
-static void make_device_name(tunemu_device device, int unit_number)
-{
+static void make_device_name(tunemu_device device, int unit_number) {
snprintf(device, sizeof(tunemu_device), "ppp%d", unit_number);
}
-static int check_device_name(tunemu_device device)
-{
- if (strlen(device) < 4)
+static int check_device_name(tunemu_device device) {
+ if(strlen(device) < 4) {
return -1;
+ }
int unit_number = atoi(device + 3);
- if (unit_number < 0 || unit_number > 999)
+
+ if(unit_number < 0 || unit_number > 999) {
return -1;
+ }
tunemu_device compare;
make_device_name(compare, unit_number);
- if (strcmp(device, compare) != 0)
+ if(strcmp(device, compare) != 0) {
return -1;
+ }
return 0;
}
-int tunemu_open(tunemu_device device)
-{
+int tunemu_open(tunemu_device device) {
int ppp_unit_number = -1;
- if (device[0] != 0)
- {
- if (check_device_name(device) < 0)
- {
+
+ if(device[0] != 0) {
+ if(check_device_name(device) < 0) {
tun_error("invalid device name \"%s\"", device);
return -1;
}
}
int ppp_unit_fd = ppp_new_unit(&ppp_unit_number);
- if (ppp_unit_fd < 0)
+
+ if(ppp_unit_fd < 0) {
return -1;
+ }
- if (ppp_setup_unit(ppp_unit_fd) < 0)
- {
+ if(ppp_setup_unit(ppp_unit_fd) < 0) {
close(ppp_unit_fd);
return -1;
}
- if (open_pcap() < 0)
- {
+ if(open_pcap() < 0) {
close(ppp_unit_fd);
return -1;
}
return ppp_unit_fd;
}
-int tunemu_close(int ppp_sockfd)
-{
+int tunemu_close(int ppp_sockfd) {
int ret = close(ppp_sockfd);
- if (ret == 0)
+ if(ret == 0) {
close_pcap();
+ }
return ret;
}
-int tunemu_read(int ppp_sockfd, char *buffer, int length)
-{
+int tunemu_read(int ppp_sockfd, char *buffer, int length) {
allocate_data_buffer(length + 2);
length = read(ppp_sockfd, data_buffer, length + 2);
- if (length < 0)
- {
+
+ if(length < 0) {
tun_error("reading packet: %s", strerror(errno));
return length;
}
+
tun_noerror();
length -= 2;
- if (length < 0)
+
+ if(length < 0) {
return 0;
+ }
memcpy(buffer, data_buffer + 2, length);
return length;
}
-int tunemu_write(int ppp_sockfd, char *buffer, int length)
-{
+int tunemu_write(int ppp_sockfd, char *buffer, int length) {
allocate_data_buffer(length + 4);
data_buffer[0] = 0x02;
memcpy(data_buffer + 4, buffer, length);
- if (pcap == NULL)
- {
+ if(pcap == NULL) {
tun_error("pcap not open");
return -1;
}
length = pcap_inject(pcap, data_buffer, length + 4);
- if (length < 0)
- {
+
+ if(length < 0) {
tun_error("injecting packet: %s", pcap_geterr(pcap));
return length;
}
+
tun_noerror();
length -= 4;
- if (length < 0)
+
+ if(length < 0) {
return 0;
+ }
return length;
}
/*
* tunemu - Tun device emulation for Darwin
* Copyright (C) 2009 Friedrich Schöller <friedrich.schoeller@gmail.com>
- *
+ *
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ *
*/
#ifndef TUNEMU_H
1998-2005 Ivo Timmermans
2000-2014 Guus Sliepen <guus@tinc-vpn.org>
2010-2011 Julien Muchembled <jm@jmuchemb.eu>
- 2000 Cris van Pelt
+ 2000 Cris van Pelt
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
#include "conf.h"
#include "list.h"
#include "logger.h"
-#include "netutl.h" /* for str2address */
+#include "netutl.h" /* for str2address */
#include "protocol.h"
-#include "utils.h" /* for cp */
+#include "utils.h" /* for cp */
#include "xalloc.h"
avl_tree_t *config_tree;
-int pinginterval = 0; /* seconds between pings */
-int pingtimeout = 0; /* seconds to wait for response */
-char *confbase = NULL; /* directory in which all config files are */
-char *netname = NULL; /* name of the vpn network */
-list_t *cmdline_conf = NULL; /* global/host configuration values given at the command line */
+int pinginterval = 0; /* seconds between pings */
+int pingtimeout = 0; /* seconds to wait for response */
+char *confbase = NULL; /* directory in which all config files are */
+char *netname = NULL; /* name of the vpn network */
+list_t *cmdline_conf = NULL; /* global/host configuration values given at the command line */
static int config_compare(const config_t *a, const config_t *b) {
result = strcasecmp(a->variable, b->variable);
- if(result)
+ if(result) {
return result;
+ }
/* give priority to command line options */
result = !b->file - !a->file;
- if (result)
+
+ if(result) {
return result;
+ }
result = a->line - b->line;
- if(result)
+ if(result) {
return result;
- else
+ } else {
return a->file ? strcmp(a->file, b->file) : 0;
+ }
}
-void init_configuration(avl_tree_t ** config_tree) {
+void init_configuration(avl_tree_t **config_tree) {
*config_tree = avl_alloc_tree((avl_compare_t) config_compare, (avl_action_t) free_config);
}
-void exit_configuration(avl_tree_t ** config_tree) {
+void exit_configuration(avl_tree_t **config_tree) {
avl_delete_tree(*config_tree);
*config_tree = NULL;
}
}
void free_config(config_t *cfg) {
- if(cfg->variable)
+ if(cfg->variable) {
free(cfg->variable);
+ }
- if(cfg->value)
+ if(cfg->value) {
free(cfg->value);
+ }
- if(cfg->file)
+ if(cfg->file) {
free(cfg->file);
+ }
free(cfg);
}
found = avl_search_closest_greater(config_tree, &cfg);
- if(!found)
+ if(!found) {
return NULL;
+ }
- if(strcasecmp(found->variable, variable))
+ if(strcasecmp(found->variable, variable)) {
return NULL;
+ }
return found;
}
if(node->next) {
found = node->next->data;
- if(!strcasecmp(found->variable, cfg->variable))
+ if(!strcasecmp(found->variable, cfg->variable)) {
return found;
+ }
}
}
}
bool get_config_bool(const config_t *cfg, bool *result) {
- if(!cfg)
+ if(!cfg) {
return false;
+ }
if(!strcasecmp(cfg->value, "yes")) {
*result = true;
}
logger(LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
- cfg->variable, cfg->file, cfg->line);
+ cfg->variable, cfg->file, cfg->line);
return false;
}
bool get_config_int(const config_t *cfg, int *result) {
- if(!cfg)
+ if(!cfg) {
return false;
+ }
- if(sscanf(cfg->value, "%d", result) == 1)
+ if(sscanf(cfg->value, "%d", result) == 1) {
return true;
+ }
logger(LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
- cfg->variable, cfg->file, cfg->line);
+ cfg->variable, cfg->file, cfg->line);
return false;
}
bool get_config_string(const config_t *cfg, char **result) {
- if(!cfg)
+ if(!cfg) {
return false;
+ }
*result = xstrdup(cfg->value);
bool get_config_address(const config_t *cfg, struct addrinfo **result) {
struct addrinfo *ai;
- if(!cfg)
+ if(!cfg) {
return false;
+ }
ai = str2addrinfo(cfg->value, NULL, 0);
}
logger(LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
- cfg->variable, cfg->file, cfg->line);
+ cfg->variable, cfg->file, cfg->line);
return false;
}
-bool get_config_subnet(const config_t *cfg, subnet_t ** result) {
+bool get_config_subnet(const config_t *cfg, subnet_t **result) {
subnet_t subnet = {NULL};
- if(!cfg)
+ if(!cfg) {
return false;
+ }
if(!str2net(&subnet, cfg->value)) {
logger(LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
- cfg->variable, cfg->file, cfg->line);
+ cfg->variable, cfg->file, cfg->line);
return false;
}
/* Teach newbies what subnets are... */
if(((subnet.type == SUBNET_IPV4)
- && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
- || ((subnet.type == SUBNET_IPV6)
- && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
+ && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
+ || ((subnet.type == SUBNET_IPV6)
+ && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
logger(LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
- cfg->variable, cfg->file, cfg->line);
+ cfg->variable, cfg->file, cfg->line);
return false;
}
/*
Read exactly one line and strip the trailing newline if any.
*/
-static char *readline(FILE * fp, char *buf, size_t buflen) {
+static char *readline(FILE *fp, char *buf, size_t buflen) {
char *newline = NULL;
char *p;
- if(feof(fp))
+ if(feof(fp)) {
return NULL;
+ }
p = fgets(buf, buflen, fp);
- if(!p)
+ if(!p) {
return NULL;
+ }
newline = strchr(p, '\n');
- if(!newline)
+ if(!newline) {
return buf;
+ }
+
+ *newline = '\0'; /* kill newline */
- *newline = '\0'; /* kill newline */
- if(newline > p && newline[-1] == '\r') /* and carriage return if necessary */
+ if(newline > p && newline[-1] == '\r') { /* and carriage return if necessary */
newline[-1] = '\0';
+ }
return buf;
}
variable = value = line;
eol = line + strlen(line);
- while(strchr("\t ", *--eol))
+
+ while(strchr("\t ", *--eol)) {
*eol = '\0';
+ }
len = strcspn(value, "\t =");
value += len;
value += strspn(value, "\t ");
+
if(*value == '=') {
value++;
value += strspn(value, "\t ");
}
+
variable[len] = '\0';
if(!*value) {
const char err[] = "No value for variable";
- if (fname)
+
+ if(fname)
logger(LOG_ERR, "%s `%s' on line %d while reading config file %s",
- err, variable, lineno, fname);
+ err, variable, lineno, fname);
else
logger(LOG_ERR, "%s `%s' in command line option %d",
- err, variable, lineno);
+ err, variable, lineno);
+
return NULL;
}
line = readline(fp, buffer, sizeof(buffer));
if(!line) {
- if(feof(fp))
+ if(feof(fp)) {
result = true;
+ }
+
break;
}
lineno++;
- if(!*line || *line == '#')
+ if(!*line || *line == '#') {
continue;
+ }
if(ignore) {
- if(!strncmp(line, "-----END", 8))
+ if(!strncmp(line, "-----END", 8)) {
ignore = false;
+ }
+
continue;
}
-
+
if(!strncmp(line, "-----BEGIN", 10)) {
ignore = true;
continue;
}
cfg = parse_config_line(line, fname, lineno);
- if (!cfg)
+
+ if(!cfg) {
break;
+ }
+
config_add(config_tree, cfg);
}
const config_t *cfg = node->data;
if(!prefix) {
- if(strchr(cfg->variable, '.'))
+ if(strchr(cfg->variable, '.')) {
continue;
+ }
} else {
if(strncmp(prefix, cfg->variable, prefix_len) ||
- cfg->variable[prefix_len] != '.')
+ cfg->variable[prefix_len] != '.') {
continue;
+ }
}
config_t *new = new_config();
x = read_config_file(config_tree, fname);
// We will try to read the conf files in the "conf.d" dir
- if (x) {
+ if(x) {
char dname[PATH_MAX];
snprintf(dname, sizeof(dname), "%s/conf.d", confbase);
- DIR *dir = opendir (dname);
+ DIR *dir = opendir(dname);
+
// If we can find this dir
- if (dir) {
+ if(dir) {
struct dirent *ep;
+
// We list all the files in it
- while (x && (ep = readdir (dir))) {
+ while(x && (ep = readdir(dir))) {
size_t l = strlen(ep->d_name);
+
// And we try to read the ones that end with ".conf"
- if (l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
+ if(l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
snprintf(fname, sizeof(fname), "%s/%s", dname, ep->d_name);
x = read_config_file(config_tree, fname);
}
}
- closedir (dir);
+
+ closedir(dir);
}
}
FILE *r, *w;
r = fopen(filename, "r");
- if(!r)
+
+ if(!r) {
return;
+ }
snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", filename);
w = fopen(tmpfile, "w");
while(fgets(buf, sizeof(buf), r)) {
- if(!strncmp(buf, "-----BEGIN RSA", 14)) {
+ if(!strncmp(buf, "-----BEGIN RSA", 14)) {
buf[11] = 'O';
buf[12] = 'L';
buf[13] = 'D';
disabled = true;
- }
- else if(!strncmp(buf, "-----END RSA", 12)) {
+ } else if(!strncmp(buf, "-----END RSA", 12)) {
buf[ 9] = 'O';
buf[10] = 'L';
buf[11] = 'D';
disabled = true;
}
+
if(w && fputs(buf, w) < 0) {
disabled = false;
break;
}
}
- if(w)
+ if(w) {
fclose(w);
+ }
+
fclose(r);
if(!w && disabled) {
// We cannot atomically replace files on Windows.
char bakfile[PATH_MAX] = "";
snprintf(bakfile, sizeof(bakfile), "%s.bak", filename);
+
if(rename(filename, bakfile) || rename(tmpfile, filename)) {
rename(bakfile, filename);
#else
+
if(rename(tmpfile, filename)) {
#endif
fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
} else {
/* Ask for a file and/or directory name. */
fprintf(stdout, "Please enter a file to save %s to [%s]: ",
- what, filename);
+ what, filename);
fflush(stdout);
fn = readline(stdin, line, sizeof(line));
if(!fn) {
fprintf(stderr, "Error while reading stdin: %s\n",
- strerror(errno));
+ strerror(errno));
return NULL;
}
if(!strlen(fn))
/* User just pressed enter. */
+ {
fn = filename;
+ }
}
#ifdef HAVE_MINGW
+
if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
#else
+
if(fn[0] != '/') {
#endif
/* The directory is a relative path or a filename. */
fn = abspath;
}
- umask(0077); /* Disallow everything for group and other */
+ umask(0077); /* Disallow everything for group and other */
disable_old_keys(fn);
if(!r) {
fprintf(stderr, "Error opening file `%s': %s\n",
- fn, strerror(errno));
+ fn, strerror(errno));
return NULL;
}
extern void init_configuration(avl_tree_t **);
extern void exit_configuration(avl_tree_t **);
-extern config_t *new_config(void) __attribute__ ((__malloc__));
+extern config_t *new_config(void) __attribute__((__malloc__));
extern void free_config(config_t *);
extern void config_add(avl_tree_t *, config_t *);
extern config_t *lookup_config(const avl_tree_t *, char *);
#include "utils.h"
#include "xalloc.h"
-avl_tree_t *connection_tree; /* Meta connections */
+avl_tree_t *connection_tree; /* Meta connections */
connection_t *everyone;
static int connection_compare(const connection_t *a, const connection_t *b) {
c = xmalloc_and_zero(sizeof(connection_t));
- if(!c)
+ if(!c) {
return NULL;
+ }
gettimeofday(&c->start, NULL);
free(c->name);
free(c->hostname);
- if(c->config_tree)
+ if(c->config_tree) {
exit_configuration(&c->config_tree);
+ }
free(c);
}
for(node = connection_tree->head; node; node = node->next) {
c = node->data;
logger(LOG_DEBUG, " %s at %s options %x socket %d status %04x outbuf %d/%d/%d",
- c->name, c->hostname, c->options, c->socket, bitfield_to_int(&c->status, sizeof(c->status)),
- c->outbufsize, c->outbufstart, c->outbuflen);
+ c->name, c->hostname, c->options, c->socket, bitfield_to_int(&c->status, sizeof(c->status)),
+ c->outbufsize, c->outbufstart, c->outbuflen);
}
logger(LOG_DEBUG, "End of connections.");
#include "avl_tree.h"
-#define OPTION_INDIRECT 0x0001
-#define OPTION_TCPONLY 0x0002
-#define OPTION_PMTU_DISCOVERY 0x0004
-#define OPTION_CLAMP_MSS 0x0008
+#define OPTION_INDIRECT 0x0001
+#define OPTION_TCPONLY 0x0002
+#define OPTION_PMTU_DISCOVERY 0x0004
+#define OPTION_CLAMP_MSS 0x0008
typedef struct connection_status_t {
- unsigned int pinged:1; /* sent ping */
- unsigned int active:1; /* 1 if active.. */
- unsigned int connecting:1; /* 1 if we are waiting for a non-blocking connect() to finish */
- unsigned int unused_termreq:1; /* the termination of this connection was requested */
- unsigned int remove:1; /* Set to 1 if you want this connection removed */
- unsigned int timeout:1; /* 1 if gotten timeout */
- unsigned int encryptout:1; /* 1 if we can encrypt outgoing traffic */
- unsigned int decryptin:1; /* 1 if we have to decrypt incoming traffic */
- unsigned int mst:1; /* 1 if this connection is part of a minimum spanning tree */
- unsigned int proxy_passed:1; /* 1 if we are connecting via a proxy and we have finished talking with it */
- unsigned int unused:22;
+ unsigned int pinged: 1; /* sent ping */
+ unsigned int active: 1; /* 1 if active.. */
+ unsigned int connecting: 1; /* 1 if we are waiting for a non-blocking connect() to finish */
+ unsigned int unused_termreq: 1; /* the termination of this connection was requested */
+ unsigned int remove: 1; /* Set to 1 if you want this connection removed */
+ unsigned int timeout: 1; /* 1 if gotten timeout */
+ unsigned int encryptout: 1; /* 1 if we can encrypt outgoing traffic */
+ unsigned int decryptin: 1; /* 1 if we have to decrypt incoming traffic */
+ unsigned int mst: 1; /* 1 if this connection is part of a minimum spanning tree */
+ unsigned int proxy_passed: 1; /* 1 if we are connecting via a proxy and we have finished talking with it */
+ unsigned int unused: 22;
} connection_status_t;
#include "edge.h"
#include "node.h"
typedef struct connection_t {
- char *name; /* name he claims to have */
-
- union sockaddr_t address; /* his real (internet) ip */
- char *hostname; /* the hostname of its real ip */
- int protocol_version; /* used protocol */
-
- int socket; /* socket used for this connection */
- uint32_t options; /* options for this connection */
- connection_status_t status; /* status info */
- int estimated_weight; /* estimation for the weight of the edge for this connection */
- struct timeval start; /* time this connection was started, used for above estimation */
- struct outgoing_t *outgoing; /* used to keep track of outgoing connections */
-
- struct node_t *node; /* node associated with the other end */
- struct edge_t *edge; /* edge associated with this connection */
-
- RSA *rsa_key; /* his public/private key */
- const EVP_CIPHER *incipher; /* Cipher he will use to send data to us */
- const EVP_CIPHER *outcipher; /* Cipher we will use to send data to him */
- EVP_CIPHER_CTX *inctx; /* Context of encrypted meta data that will come from him to us */
- EVP_CIPHER_CTX *outctx; /* Context of encrypted meta data that will be sent from us to him */
+ char *name; /* name he claims to have */
+
+ union sockaddr_t address; /* his real (internet) ip */
+ char *hostname; /* the hostname of its real ip */
+ int protocol_version; /* used protocol */
+
+ int socket; /* socket used for this connection */
+ uint32_t options; /* options for this connection */
+ connection_status_t status; /* status info */
+ int estimated_weight; /* estimation for the weight of the edge for this connection */
+ struct timeval start; /* time this connection was started, used for above estimation */
+ struct outgoing_t *outgoing; /* used to keep track of outgoing connections */
+
+ struct node_t *node; /* node associated with the other end */
+ struct edge_t *edge; /* edge associated with this connection */
+
+ RSA *rsa_key; /* his public/private key */
+ const EVP_CIPHER *incipher; /* Cipher he will use to send data to us */
+ const EVP_CIPHER *outcipher; /* Cipher we will use to send data to him */
+ EVP_CIPHER_CTX *inctx; /* Context of encrypted meta data that will come from him to us */
+ EVP_CIPHER_CTX *outctx; /* Context of encrypted meta data that will be sent from us to him */
uint64_t inbudget; /* Encrypted bytes send budget */
uint64_t outbudget; /* Encrypted bytes receive budget */
- char *inkey; /* His symmetric meta key + iv */
- char *outkey; /* Our symmetric meta key + iv */
- int inkeylength; /* Length of his key + iv */
- int outkeylength; /* Length of our key + iv */
+ char *inkey; /* His symmetric meta key + iv */
+ char *outkey; /* Our symmetric meta key + iv */
+ int inkeylength; /* Length of his key + iv */
+ int outkeylength; /* Length of our key + iv */
const EVP_MD *indigest;
const EVP_MD *outdigest;
int inmaclength;
int outmaclength;
int incompression;
int outcompression;
- char *mychallenge; /* challenge we received from him */
- char *hischallenge; /* challenge we sent to him */
+ char *mychallenge; /* challenge we received from him */
+ char *hischallenge; /* challenge we sent to him */
- char buffer[MAXBUFSIZE]; /* metadata input buffer */
- int buflen; /* bytes read into buffer */
- int reqlen; /* length of incoming request */
- int tcplen; /* length of incoming TCPpacket */
- int allow_request; /* defined if there's only one request possible */
+ char buffer[MAXBUFSIZE]; /* metadata input buffer */
+ int buflen; /* bytes read into buffer */
+ int reqlen; /* length of incoming request */
+ int tcplen; /* length of incoming TCPpacket */
+ int allow_request; /* defined if there's only one request possible */
- char *outbuf; /* metadata output buffer */
- int outbufstart; /* index of first meaningful byte in output buffer */
- int outbuflen; /* number of meaningful bytes in output buffer */
- int outbufsize; /* number of bytes allocated to output buffer */
+ char *outbuf; /* metadata output buffer */
+ int outbufstart; /* index of first meaningful byte in output buffer */
+ int outbuflen; /* number of meaningful bytes in output buffer */
+ int outbufsize; /* number of bytes allocated to output buffer */
- time_t last_ping_time; /* last time we saw some activity from the other end or pinged them */
- time_t last_flushed_time; /* last time buffer was empty. Only meaningful if outbuflen > 0 */
+ time_t last_ping_time; /* last time we saw some activity from the other end or pinged them */
+ time_t last_flushed_time; /* last time buffer was empty. Only meaningful if outbuflen > 0 */
- avl_tree_t *config_tree; /* Pointer to configuration tree belonging to him */
+ avl_tree_t *config_tree; /* Pointer to configuration tree belonging to him */
} connection_t;
extern avl_tree_t *connection_tree;
extern void init_connections(void);
extern void exit_connections(void);
-extern connection_t *new_connection(void) __attribute__ ((__malloc__));
+extern connection_t *new_connection(void) __attribute__((__malloc__));
extern void free_connection(connection_t *);
extern void free_connection_partially(connection_t *);
extern void connection_add(connection_t *);
get_config_string(lookup_config(config_tree, "Device"), &device);
get_config_string(lookup_config(config_tree, "Interface"), &iface);
- if(device && iface)
+ if(device && iface) {
logger(LOG_WARNING, "Warning: both Device and Interface specified, results may not be as expected");
+ }
/* Open registry and look for network adapters */
return false;
}
- for (i = 0; ; i++) {
+ for(i = 0; ; i++) {
len = sizeof(adapterid);
- if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
+
+ if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL)) {
break;
+ }
/* Find out more about this adapter */
snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, adapterid);
- if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
+ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2)) {
continue;
+ }
len = sizeof(adaptername);
err = RegQueryValueEx(key2, "Name", 0, 0, adaptername, &len);
RegCloseKey(key2);
- if(err)
+ if(err) {
continue;
+ }
if(device) {
if(!strcmp(device, adapterid)) {
found = true;
break;
- } else
+ } else {
continue;
+ }
}
if(iface) {
if(!strcmp(iface, adaptername)) {
found = true;
break;
- } else
+ } else {
continue;
+ }
}
snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
+
if(device_handle != INVALID_HANDLE_VALUE) {
CloseHandle(device_handle);
found = true;
return false;
}
- if(!device)
+ if(!device) {
device = xstrdup(adapterid);
+ }
- if(!iface)
+ if(!iface) {
iface = xstrdup(adaptername);
+ }
snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);
-
+
/* Now we are going to open this device twice: once for reading and once for writing.
We do this because apparently it isn't possible to check for activity in the select() loop.
Furthermore I don't really know how to do it the "Windows" way. */
}
/* The parent opens the tap device for writing. */
-
- device_handle = CreateFile(tapname, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM , 0);
-
+
+ device_handle = CreateFile(tapname, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
+
if(device_handle == INVALID_HANDLE_VALUE) {
logger(LOG_ERR, "Could not open Windows tap device %s (%s) for writing: %s", device, iface, winerror(GetLastError()));
return false;
if(!reader_pid) {
/* The child opens the tap device for reading, blocking.
It passes everything it reads to the socket. */
-
+
char buf[MTU];
long lenin;
}
read(device_fd, &gelukt, 1);
+
if(gelukt != 1) {
logger(LOG_DEBUG, "Tap reader failed!");
return false;
if((lenin = read(sp[0], packet->data, MTU)) <= 0) {
logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
+ device, strerror(errno));
return false;
}
-
+
packet->len = lenin;
device_total_in += packet->len;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Read packet of %d bytes from %s", packet->len,
- device_info);
+ device_info);
return true;
}
long lenout;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
- packet->len, device_info);
+ packet->len, device_info);
- if(!WriteFile (device_handle, packet->data, packet->len, &lenout, NULL)) {
+ if(!WriteFile(device_handle, packet->data, packet->len, &lenout, NULL)) {
logger(LOG_ERR, "Error while writing to %s %s: %s", device_info, device, winerror(GetLastError()));
return false;
}
#ifndef HAVE_DAEMON
/*
Replacement for the daemon() function.
-
+
The daemon() function is for programs wishing to detach themselves
from the controlling terminal and run in the background as system
daemons.
}
/* If we are the parent, terminate */
- if(pid)
+ if(pid) {
exit(0);
+ }
/* Detach by becoming the new process group leader */
if(setsid() < 0) {
buf[len - 1] = 0;
va_end(aq);
- if(status >= 0)
+ if(status >= 0) {
*buf = xrealloc(*buf, status + 1);
+ }
if(status > len - 1) {
len = status;
#include "utils.h"
#include "xalloc.h"
-avl_tree_t *edge_weight_tree; /* Tree with all edges, sorted on weight */
+avl_tree_t *edge_weight_tree; /* Tree with all edges, sorted on weight */
static int edge_compare(const edge_t *a, const edge_t *b) {
return strcmp(a->to->name, b->to->name);
result = a->weight - b->weight;
- if(result)
+ if(result) {
return result;
+ }
result = strcmp(a->from->name, b->from->name);
- if(result)
+ if(result) {
return result;
+ }
return strcmp(a->to->name, b->to->name);
}
e->reverse = lookup_edge(e->to, e->from);
- if(e->reverse)
+ if(e->reverse) {
e->reverse->reverse = e;
+ }
}
void edge_del(edge_t *e) {
- if(e->reverse)
+ if(e->reverse) {
e->reverse->reverse = NULL;
+ }
avl_delete(edge_weight_tree, e);
avl_delete(e->from->edge_tree, e);
edge_t *lookup_edge(node_t *from, node_t *to) {
edge_t v;
-
+
v.from = from;
v.to = to;
for(node = node_tree->head; node; node = node->next) {
n = node->data;
+
for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
e = node2->data;
address = sockaddr2hostname(&e->address);
logger(LOG_DEBUG, " %s to %s at %s options %x weight %d",
- e->from->name, e->to->name, address, e->options, e->weight);
+ e->from->name, e->to->name, address, e->options, e->weight);
free(address);
}
}
struct node_t *to;
sockaddr_t address;
- uint32_t options; /* options turned on for this edge */
- int weight; /* weight of this edge */
+ uint32_t options; /* options turned on for this edge */
+ int weight; /* weight of this edge */
- struct connection_t *connection; /* connection associated with this edge, if available */
- struct edge_t *reverse; /* edge in the opposite direction, if available */
+ struct connection_t *connection; /* connection associated with this edge, if available */
+ struct edge_t *reverse; /* edge in the opposite direction, if available */
} edge_t;
-extern avl_tree_t *edge_weight_tree; /* Tree with all known edges sorted on weight */
+extern avl_tree_t *edge_weight_tree; /* Tree with all known edges sorted on weight */
extern void init_edges(void);
extern void exit_edges(void);
-extern edge_t *new_edge(void) __attribute__ ((__malloc__));
+extern edge_t *new_edge(void) __attribute__((__malloc__));
extern void free_edge(edge_t *);
-extern avl_tree_t *new_edge_tree(void) __attribute__ ((__malloc__));
+extern avl_tree_t *new_edge_tree(void) __attribute__((__malloc__));
extern void free_edge_tree(avl_tree_t *);
extern void edge_add(edge_t *);
extern void edge_del(edge_t *);
uint8_t ether_dhost[ETH_ALEN];
uint8_t ether_shost[ETH_ALEN];
uint16_t ether_type;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#endif
#ifndef HAVE_STRUCT_ARPHDR
uint16_t ar_hrd;
uint16_t ar_pro;
uint8_t ar_hln;
- uint8_t ar_pln;
- uint16_t ar_op;
-} __attribute__ ((__packed__));
+ uint8_t ar_pln;
+ uint16_t ar_op;
+} __attribute__((__packed__));
-#define ARPOP_REQUEST 1
-#define ARPOP_REPLY 2
-#define ARPOP_RREQUEST 3
-#define ARPOP_RREPLY 4
-#define ARPOP_InREQUEST 8
-#define ARPOP_InREPLY 9
-#define ARPOP_NAK 10
+#define ARPOP_REQUEST 1
+#define ARPOP_REPLY 2
+#define ARPOP_RREQUEST 3
+#define ARPOP_RREPLY 4
+#define ARPOP_InREQUEST 8
+#define ARPOP_InREPLY 9
+#define ARPOP_NAK 10
#endif
#ifndef HAVE_STRUCT_ETHER_ARP
uint8_t arp_spa[4];
uint8_t arp_tha[ETH_ALEN];
uint8_t arp_tpa[4];
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#define arp_hrd ea_hdr.ar_hrd
#define arp_pro ea_hdr.ar_pro
#define arp_hln ea_hdr.ar_hln
static int id;
static int event_compare(const event_t *a, const event_t *b) {
- if(a->time > b->time)
+ if(a->time > b->time) {
return 1;
+ }
- if(a->time < b->time)
+ if(a->time < b->time) {
return -1;
+ }
return a->id - b->id;
}
/*
* Make all events appear expired by substracting the difference between
- * the expiration time of the last event and the current time.
+ * the expiration time of the last event and the current time.
*/
- if(!event_tree->tail)
+ if(!event_tree->tail) {
return;
+ }
event = event_tree->tail->data;
- if(event->time <= now)
+
+ if(event->time <= now) {
return;
+ }
diff = event->time - now;
-
+
for(node = event_tree->head; node; node = node->next) {
event = node->data;
event->time -= diff;
}
event_t *peek_next_event(void) {
- if (event_tree->head)
+ if(event_tree->head) {
return event_tree->head->data;
+ }
+
return NULL;
}
extern void init_events(void);
extern void exit_events(void);
extern void expire_events(void);
-extern event_t *new_event(void) __attribute__ ((__malloc__));
+extern event_t *new_event(void) __attribute__((__malloc__));
extern void free_event(event_t *);
extern void event_add(event_t *);
extern void event_del(event_t *);
#include "xalloc.h"
#if !HAVE_DECL_GAI_STRERROR
-char *gai_strerror(int ecode)
-{
- switch (ecode) {
- case EAI_NODATA:
- return "No address associated with hostname";
- case EAI_MEMORY:
- return "Memory allocation failure";
- case EAI_FAMILY:
- return "Address family not supported";
- default:
- return "Unknown error";
+char *gai_strerror(int ecode) {
+ switch(ecode) {
+ case EAI_NODATA:
+ return "No address associated with hostname";
+
+ case EAI_MEMORY:
+ return "Memory allocation failure";
+
+ case EAI_FAMILY:
+ return "Address family not supported";
+
+ default:
+ return "Unknown error";
}
-}
+}
#endif /* !HAVE_GAI_STRERROR */
#if !HAVE_DECL_FREEADDRINFO
-void freeaddrinfo(struct addrinfo *ai)
-{
+void freeaddrinfo(struct addrinfo *ai) {
struct addrinfo *next;
while(ai) {
#endif /* !HAVE_FREEADDRINFO */
#if !HAVE_DECL_GETADDRINFO
-static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr)
-{
+static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) {
struct addrinfo *ai;
ai = xmalloc_and_zero(sizeof(struct addrinfo) + sizeof(struct sockaddr_in));
-
+
ai->ai_addr = (struct sockaddr *)(ai + 1);
ai->ai_addrlen = sizeof(struct sockaddr_in);
ai->ai_addr->sa_family = ai->ai_family = AF_INET;
((struct sockaddr_in *)(ai)->ai_addr)->sin_port = port;
((struct sockaddr_in *)(ai)->ai_addr)->sin_addr.s_addr = addr;
-
+
return ai;
}
-int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res)
-{
+int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res) {
struct addrinfo *prev = NULL;
struct hostent *hp;
struct in_addr in = {0};
int i;
uint16_t port = 0;
- if(hints && hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC)
+ if(hints && hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC) {
return EAI_FAMILY;
+ }
- if (servname)
+ if(servname) {
port = htons(atoi(servname));
+ }
- if (hints && hints->ai_flags & AI_PASSIVE) {
+ if(hints && hints->ai_flags & AI_PASSIVE) {
*res = malloc_ai(port, htonl(0x00000000));
return 0;
}
-
- if (!hostname) {
+
+ if(!hostname) {
*res = malloc_ai(port, htonl(0x7f000001));
return 0;
}
-
+
hp = gethostbyname(hostname);
- if(!hp || !hp->h_addr_list || !hp->h_addr_list[0])
+ if(!hp || !hp->h_addr_list || !hp->h_addr_list[0]) {
return EAI_NODATA;
+ }
- for (i = 0; hp->h_addr_list[i]; i++) {
+ for(i = 0; hp->h_addr_list[i]; i++) {
*res = malloc_ai(port, ((struct in_addr *)hp->h_addr_list[i])->s_addr);
- if(prev)
+ if(prev) {
prev->ai_next = *res;
+ }
prev = *res;
}
#define TINC_FAKE_GETADDRINFO_H
#ifndef EAI_NODATA
-#define EAI_NODATA 1
+#define EAI_NODATA 1
#endif
#ifndef EAI_MEMORY
-#define EAI_MEMORY 2
+#define EAI_MEMORY 2
#endif
#ifndef EAI_FAMILY
-#define EAI_FAMILY 3
+#define EAI_FAMILY 3
#endif
#ifndef AI_PASSIVE
#ifndef HAVE_STRUCT_ADDRINFO
struct addrinfo {
- int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
- int ai_family; /* PF_xxx */
- int ai_socktype; /* SOCK_xxx */
- int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
- size_t ai_addrlen; /* length of ai_addr */
- char *ai_canonname; /* canonical name for hostname */
- struct sockaddr *ai_addr; /* binary address */
- struct addrinfo *ai_next; /* next structure in linked list */
+ int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
+ int ai_family; /* PF_xxx */
+ int ai_socktype; /* SOCK_xxx */
+ int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
+ size_t ai_addrlen; /* length of ai_addr */
+ char *ai_canonname; /* canonical name for hostname */
+ struct sockaddr *ai_addr; /* binary address */
+ struct addrinfo *ai_next; /* next structure in linked list */
};
#endif /* !HAVE_STRUCT_ADDRINFO */
#if !HAVE_DECL_GETADDRINFO
-int getaddrinfo(const char *hostname, const char *servname,
+int getaddrinfo(const char *hostname, const char *servname,
const struct addrinfo *hints, struct addrinfo **res);
#endif /* !HAVE_GETADDRINFO */
#if !HAVE_DECL_GETNAMEINFO
-int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags)
-{
+int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) {
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
struct hostent *hp;
int len;
- if(sa->sa_family != AF_INET)
+ if(sa->sa_family != AF_INET) {
return EAI_FAMILY;
+ }
if(serv && servlen) {
len = snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
- if(len < 0 || len >= servlen)
+
+ if(len < 0 || len >= servlen) {
return EAI_MEMORY;
+ }
}
- if(!host || !hostlen)
+ if(!host || !hostlen) {
return 0;
+ }
if(flags & NI_NUMERICHOST) {
len = snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
- if(len < 0 || len >= hostlen)
+
+ if(len < 0 || len >= hostlen) {
return EAI_MEMORY;
+ }
+
return 0;
}
hp = gethostbyaddr((char *)&sin->sin_addr, sizeof(struct in_addr), AF_INET);
-
- if(!hp || !hp->h_name || !hp->h_name[0])
+
+ if(!hp || !hp->h_name || !hp->h_name[0]) {
return EAI_NODATA;
-
+ }
+
len = snprintf(host, hostlen, "%s", hp->h_name);
- if(len < 0 || len >= hostlen)
+
+ if(len < 0 || len >= hostlen) {
return EAI_MEMORY;
+ }
return 0;
}
#define TINC_FAKE_GETNAMEINFO_H
#if !HAVE_DECL_GETNAMEINFO
-int getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
+int getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
size_t hostlen, char *serv, size_t servlen, int flags);
#endif /* !HAVE_GETNAMEINFO */
before changing it!
Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97
- Free Software Foundation, Inc.
+ Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to bug-glibc@prep.ai.mit.edu.
/* This needs to come after some library #include
to get GNU_LIBRARY defined. */
-#ifdef GNU_LIBRARY
+#ifdef GNU_LIBRARY
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
#include <stdlib.h>
#include <unistd.h>
-#endif /* GNU C library. */
+#endif /* GNU C library. */
#ifdef VMS
#include <unixlib.h>
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `optind' != ARGC. */
-static enum
-{
- REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
+static enum {
+ REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
\f
-#ifdef GNU_LIBRARY
+#ifdef GNU_LIBRARY
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
#include <string.h>
-#define my_index strchr
+#define my_index strchr
#else
/* Avoid depending on library functions or files
whose names are inconsistent. */
-char *getenv ();
+char *getenv();
static char *
-my_index (str, chr)
- const char *str;
- int chr;
+my_index(str, chr)
+const char *str;
+int chr;
{
- while (*str)
- {
- if (*str == chr)
- return (char *) str;
- str++;
- }
- return 0;
+ while(*str) {
+ if(*str == chr) {
+ return (char *) str;
+ }
+
+ str++;
+ }
+
+ return 0;
}
/* If using GCC, we can safely declare strlen this way.
#if !defined (STDC) || !STDC
/* gcc with -traditional declares the built-in strlen to return int,
and has done so at least since version 2.4.5. -- rms. */
-extern int strlen (const char *);
+extern int strlen(const char *);
#endif /* not STDC */
#endif /* GNUC */
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void
-__attribute__ ((__unused__))
-store_args_and_env (int argc, char *const *argv)
-{
- /* XXX This is no good solution. We should rather copy the args so
- that we can compare them later. But we must not use malloc(3). */
- original_argc = argc;
- original_argv = argv;
+__attribute__((__unused__))
+store_args_and_env(int argc, char *const *argv) {
+ /* XXX This is no good solution. We should rather copy the args so
+ that we can compare them later. But we must not use malloc(3). */
+ original_argc = argc;
+ original_argv = argv;
}
-text_set_element (libc_subinit, store_args_and_env);
+text_set_element(libc_subinit, store_args_and_env);
# define SWAP_FLAGS(ch1, ch2) \
- if (nonoption_flags_len > 0) \
- { \
- char tmp = getopt_nonoption_flags[ch1]; \
- getopt_nonoption_flags[ch1] = getopt_nonoption_flags[ch2]; \
- getopt_nonoption_flags[ch2] = tmp; \
- }
-#else /* !_LIBC */
+ if (nonoption_flags_len > 0) \
+ { \
+ char tmp = getopt_nonoption_flags[ch1]; \
+ getopt_nonoption_flags[ch1] = getopt_nonoption_flags[ch2]; \
+ getopt_nonoption_flags[ch2] = tmp; \
+ }
+#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
-#endif /* _LIBC */
+#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
the new indices of the non-options in ARGV after they are moved. */
#if defined (STDC) && STDC
-static void exchange (char **);
+static void exchange(char **);
#endif
static void
-exchange (argv)
- char **argv;
+exchange(argv)
+char **argv;
{
- int bottom = first_nonopt;
- int middle = last_nonopt;
- int top = optind;
- char *tem;
+ int bottom = first_nonopt;
+ int middle = last_nonopt;
+ int top = optind;
+ char *tem;
- /* Exchange the shorter segment with the far end of the longer segment.
- That puts the shorter segment into the right place.
- It leaves the longer segment in the right place overall,
- but it consists of two parts that need to be swapped next. */
+ /* Exchange the shorter segment with the far end of the longer segment.
+ That puts the shorter segment into the right place.
+ It leaves the longer segment in the right place overall,
+ but it consists of two parts that need to be swapped next. */
#ifdef _LIBC
- /* First make sure the handling of the `getopt_nonoption_flags'
- string can work normally. Our top argument must be in the range
- of the string. */
- if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
- {
- /* We must extend the array. The user plays games with us and
- presents new arguments. */
- char *new_str = malloc (top + 1);
- if (new_str == NULL)
- nonoption_flags_len = nonoption_flags_max_len = 0;
- else
- {
- memcpy (new_str, getopt_nonoption_flags, nonoption_flags_max_len);
- memset (&new_str[nonoption_flags_max_len], '\0',
- top + 1 - nonoption_flags_max_len);
- nonoption_flags_max_len = top + 1;
- getopt_nonoption_flags = new_str;
+
+ /* First make sure the handling of the `getopt_nonoption_flags'
+ string can work normally. Our top argument must be in the range
+ of the string. */
+ if(nonoption_flags_len > 0 && top >= nonoption_flags_max_len) {
+ /* We must extend the array. The user plays games with us and
+ presents new arguments. */
+ char *new_str = malloc(top + 1);
+
+ if(new_str == NULL) {
+ nonoption_flags_len = nonoption_flags_max_len = 0;
+ } else {
+ memcpy(new_str, getopt_nonoption_flags, nonoption_flags_max_len);
+ memset(&new_str[nonoption_flags_max_len], '\0',
+ top + 1 - nonoption_flags_max_len);
+ nonoption_flags_max_len = top + 1;
+ getopt_nonoption_flags = new_str;
+ }
}
- }
+
#endif
- while (top > middle && middle > bottom)
- {
- if (top - middle > middle - bottom)
- {
- /* Bottom segment is the short one. */
- int len = middle - bottom;
- register int i;
-
- /* Swap it with the top part of the top segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[top - (middle - bottom) + i];
- argv[top - (middle - bottom) + i] = tem;
- SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
- }
- /* Exclude the moved bottom segment from further swapping. */
- top -= len;
- }
- else
- {
- /* Top segment is the short one. */
- int len = top - middle;
- register int i;
-
- /* Swap it with the bottom part of the bottom segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[middle + i];
- argv[middle + i] = tem;
- SWAP_FLAGS (bottom + i, middle + i);
- }
- /* Exclude the moved top segment from further swapping. */
- bottom += len;
+ while(top > middle && middle > bottom) {
+ if(top - middle > middle - bottom) {
+ /* Bottom segment is the short one. */
+ int len = middle - bottom;
+ register int i;
+
+ /* Swap it with the top part of the top segment. */
+ for(i = 0; i < len; i++) {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[top - (middle - bottom) + i];
+ argv[top - (middle - bottom) + i] = tem;
+ SWAP_FLAGS(bottom + i, top - (middle - bottom) + i);
+ }
+
+ /* Exclude the moved bottom segment from further swapping. */
+ top -= len;
+ } else {
+ /* Top segment is the short one. */
+ int len = top - middle;
+ register int i;
+
+ /* Swap it with the bottom part of the bottom segment. */
+ for(i = 0; i < len; i++) {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[middle + i];
+ argv[middle + i] = tem;
+ SWAP_FLAGS(bottom + i, middle + i);
+ }
+
+ /* Exclude the moved top segment from further swapping. */
+ bottom += len;
+ }
}
- }
- /* Update records for the slots the non-options now occupy. */
+ /* Update records for the slots the non-options now occupy. */
- first_nonopt += (optind - last_nonopt);
- last_nonopt = optind;
+ first_nonopt += (optind - last_nonopt);
+ last_nonopt = optind;
}
/* Initialize the internal data when the first call is made. */
#if defined (STDC) && STDC
-static const char *_getopt_initialize (int, char *const *, const char *);
+static const char *_getopt_initialize(int, char *const *, const char *);
#endif
static const char *
-_getopt_initialize (argc, argv, optstring)
- int argc;
- char *const *argv;
- const char *optstring;
+_getopt_initialize(argc, argv, optstring)
+int argc;
+char *const *argv;
+const char *optstring;
{
- /* Start processing options with ARGV-element 1 (since ARGV-element 0
- is the program name); the sequence of previously skipped
- non-option ARGV-elements is empty. */
+ /* Start processing options with ARGV-element 1 (since ARGV-element 0
+ is the program name); the sequence of previously skipped
+ non-option ARGV-elements is empty. */
- first_nonopt = last_nonopt = optind;
+ first_nonopt = last_nonopt = optind;
- nextchar = NULL;
+ nextchar = NULL;
- posixly_correct = getenv ("POSIXLY_CORRECT");
+ posixly_correct = getenv("POSIXLY_CORRECT");
- /* Determine how to handle the ordering of options and nonoptions. */
+ /* Determine how to handle the ordering of options and nonoptions. */
- if (optstring[0] == '-')
- {
- ordering = RETURN_IN_ORDER;
- ++optstring;
- }
- else if (optstring[0] == '+')
- {
- ordering = REQUIRE_ORDER;
- ++optstring;
- }
- else if (posixly_correct != NULL)
- ordering = REQUIRE_ORDER;
- else
- ordering = PERMUTE;
+ if(optstring[0] == '-') {
+ ordering = RETURN_IN_ORDER;
+ ++optstring;
+ } else if(optstring[0] == '+') {
+ ordering = REQUIRE_ORDER;
+ ++optstring;
+ } else if(posixly_correct != NULL) {
+ ordering = REQUIRE_ORDER;
+ } else {
+ ordering = PERMUTE;
+ }
#ifdef _LIBC
- if (posixly_correct == NULL
- && argc == original_argc && argv == original_argv)
- {
- if (nonoption_flags_max_len == 0)
- {
- if (getopt_nonoption_flags == NULL
- || getopt_nonoption_flags[0] == '\0')
- nonoption_flags_max_len = -1;
- else
- {
- const char *orig_str = getopt_nonoption_flags;
- int len = nonoption_flags_max_len = strlen (orig_str);
- if (nonoption_flags_max_len < argc)
- nonoption_flags_max_len = argc;
- getopt_nonoption_flags =
- (char *) malloc (nonoption_flags_max_len);
- if (getopt_nonoption_flags == NULL)
- nonoption_flags_max_len = -1;
- else
- {
- memcpy (getopt_nonoption_flags, orig_str, len);
- memset (&getopt_nonoption_flags[len], '\0',
- nonoption_flags_max_len - len);
+
+ if(posixly_correct == NULL
+ && argc == original_argc && argv == original_argv) {
+ if(nonoption_flags_max_len == 0) {
+ if(getopt_nonoption_flags == NULL
+ || getopt_nonoption_flags[0] == '\0') {
+ nonoption_flags_max_len = -1;
+ } else {
+ const char *orig_str = getopt_nonoption_flags;
+ int len = nonoption_flags_max_len = strlen(orig_str);
+
+ if(nonoption_flags_max_len < argc) {
+ nonoption_flags_max_len = argc;
+ }
+
+ getopt_nonoption_flags =
+ (char *) malloc(nonoption_flags_max_len);
+
+ if(getopt_nonoption_flags == NULL) {
+ nonoption_flags_max_len = -1;
+ } else {
+ memcpy(getopt_nonoption_flags, orig_str, len);
+ memset(&getopt_nonoption_flags[len], '\0',
+ nonoption_flags_max_len - len);
+ }
+ }
}
- }
+
+ nonoption_flags_len = nonoption_flags_max_len;
+ } else {
+ nonoption_flags_len = 0;
}
- nonoption_flags_len = nonoption_flags_max_len;
- }
- else
- nonoption_flags_len = 0;
+
#endif
- return optstring;
+ return optstring;
}
\f
/* Scan elements of ARGV (whose length is ARGC) for option characters
long-named options. */
int
-_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
- int argc;
- char *const *argv;
- const char *optstring;
- const struct option *longopts;
- int *longind;
- int long_only;
+_getopt_internal(argc, argv, optstring, longopts, longind, long_only)
+int argc;
+char *const *argv;
+const char *optstring;
+const struct option *longopts;
+int *longind;
+int long_only;
{
- optarg = NULL;
-
- if (optind == 0 || !getopt_initialized)
- {
- if (optind == 0)
- optind = 1; /* Don't scan ARGV[0], the program name. */
- optstring = _getopt_initialize (argc, argv, optstring);
- getopt_initialized = 1;
- }
-
- /* Test whether ARGV[optind] points to a non-option argument.
- Either it does not have option syntax, or there is an environment flag
- from the shell indicating it is not an option. The later information
- is only used when the used in the GNU libc. */
+ optarg = NULL;
+
+ if(optind == 0 || !getopt_initialized) {
+ if(optind == 0) {
+ optind = 1; /* Don't scan ARGV[0], the program name. */
+ }
+
+ optstring = _getopt_initialize(argc, argv, optstring);
+ getopt_initialized = 1;
+ }
+
+ /* Test whether ARGV[optind] points to a non-option argument.
+ Either it does not have option syntax, or there is an environment flag
+ from the shell indicating it is not an option. The later information
+ is only used when the used in the GNU libc. */
#ifdef _LIBC
-#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
- || (optind < nonoption_flags_len \
- && getopt_nonoption_flags[optind] == '1'))
+#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
+ || (optind < nonoption_flags_len \
+ && getopt_nonoption_flags[optind] == '1'))
#else
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
- if (nextchar == NULL || *nextchar == '\0')
- {
- /* Advance to the next ARGV-element. */
+ if(nextchar == NULL || *nextchar == '\0') {
+ /* Advance to the next ARGV-element. */
- /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
- moved back by the user (who may also have changed the arguments). */
- if (last_nonopt > optind)
- last_nonopt = optind;
- if (first_nonopt > optind)
- first_nonopt = optind;
+ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
+ moved back by the user (who may also have changed the arguments). */
+ if(last_nonopt > optind) {
+ last_nonopt = optind;
+ }
- if (ordering == PERMUTE)
- {
- /* If we have just processed some options following some non-options,
- exchange them so that the options come first. */
+ if(first_nonopt > optind) {
+ first_nonopt = optind;
+ }
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange ((char **) argv);
- else if (last_nonopt != optind)
- first_nonopt = optind;
+ if(ordering == PERMUTE) {
+ /* If we have just processed some options following some non-options,
+ exchange them so that the options come first. */
- /* Skip any additional non-options
- and extend the range of non-options previously skipped. */
+ if(first_nonopt != last_nonopt && last_nonopt != optind) {
+ exchange((char **) argv);
+ } else if(last_nonopt != optind) {
+ first_nonopt = optind;
+ }
- while (optind < argc && NONOPTION_P)
- optind++;
- last_nonopt = optind;
- }
+ /* Skip any additional non-options
+ and extend the range of non-options previously skipped. */
- /* The special ARGV-element `--' means premature end of options.
- Skip it like a null option,
- then exchange with previous non-options as if it were an option,
- then skip everything else like a non-option. */
+ while(optind < argc && NONOPTION_P) {
+ optind++;
+ }
- if (optind != argc && !strcmp (argv[optind], "--"))
- {
- optind++;
+ last_nonopt = optind;
+ }
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange ((char **) argv);
- else if (first_nonopt == last_nonopt)
- first_nonopt = optind;
- last_nonopt = argc;
+ /* The special ARGV-element `--' means premature end of options.
+ Skip it like a null option,
+ then exchange with previous non-options as if it were an option,
+ then skip everything else like a non-option. */
- optind = argc;
- }
+ if(optind != argc && !strcmp(argv[optind], "--")) {
+ optind++;
- /* If we have done all the ARGV-elements, stop the scan
- and back over any non-options that we skipped and permuted. */
+ if(first_nonopt != last_nonopt && last_nonopt != optind) {
+ exchange((char **) argv);
+ } else if(first_nonopt == last_nonopt) {
+ first_nonopt = optind;
+ }
- if (optind == argc)
- {
- /* Set the next-arg-index to point at the non-options
- that we previously skipped, so the caller will digest them. */
- if (first_nonopt != last_nonopt)
- optind = first_nonopt;
- return -1;
- }
+ last_nonopt = argc;
- /* If we have come to a non-option and did not permute it,
- either stop the scan or describe it to the caller and pass it by. */
+ optind = argc;
+ }
- if (NONOPTION_P)
- {
- if (ordering == REQUIRE_ORDER)
- return -1;
- optarg = argv[optind++];
- return 1;
- }
+ /* If we have done all the ARGV-elements, stop the scan
+ and back over any non-options that we skipped and permuted. */
- /* We have found another option-ARGV-element.
- Skip the initial punctuation. */
-
- nextchar = (argv[optind] + 1
- + (longopts != NULL && argv[optind][1] == '-'));
- }
-
- /* Decode the current option-ARGV-element. */
-
- /* Check whether the ARGV-element is a long option.
-
- If long_only and the ARGV-element has the form "-f", where f is
- a valid short option, don't consider it an abbreviated form of
- a long option that starts with f. Otherwise there would be no
- way to give the -f short option.
-
- On the other hand, if there's a long option "fubar" and
- the ARGV-element is "-fu", do consider that an abbreviation of
- the long option, just like "--fu", and not "-f" with arg "u".
-
- This distinction seems to be the most useful approach. */
-
- if (longopts != NULL
- && (argv[optind][1] == '-'
- || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
- {
- char *nameend;
- const struct option *p;
- const struct option *pfound = NULL;
- int exact = 0;
- int ambig = 0;
- int indfound = -1;
- int option_index;
-
- for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
-
- /* Test all long options for either exact match
- or abbreviated matches. */
- for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar)
- == (unsigned int) strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
-
- if (ambig && !exact)
- {
- if (opterr)
- fprintf (stderr, "%s: option `%s' is ambiguous\n",
- argv[0], argv[optind]);
- nextchar += strlen (nextchar);
- optind++;
- optopt = 0;
- return '?';
+ if(optind == argc) {
+ /* Set the next-arg-index to point at the non-options
+ that we previously skipped, so the caller will digest them. */
+ if(first_nonopt != last_nonopt) {
+ optind = first_nonopt;
+ }
+
+ return -1;
+ }
+
+ /* If we have come to a non-option and did not permute it,
+ either stop the scan or describe it to the caller and pass it by. */
+
+ if(NONOPTION_P) {
+ if(ordering == REQUIRE_ORDER) {
+ return -1;
+ }
+
+ optarg = argv[optind++];
+ return 1;
+ }
+
+ /* We have found another option-ARGV-element.
+ Skip the initial punctuation. */
+
+ nextchar = (argv[optind] + 1
+ + (longopts != NULL && argv[optind][1] == '-'));
}
- if (pfound != NULL)
- {
- option_index = indfound;
- optind++;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- optarg = nameend + 1;
- else
- {
- if (opterr)
- {
- if (argv[optind - 1][1] == '-')
- /* --option */
- fprintf (stderr,
- "%s: option `--%s' doesn't allow an argument\n",
- argv[0], pfound->name);
- else
- /* +option or -option */
- fprintf (stderr,
- "%s: option `%c%s' doesn't allow an argument\n",
- argv[0], argv[optind - 1][0], pfound->name);
- }
-
- nextchar += strlen (nextchar);
-
- optopt = pfound->val;
- return '?';
+ /* Decode the current option-ARGV-element. */
+
+ /* Check whether the ARGV-element is a long option.
+
+ If long_only and the ARGV-element has the form "-f", where f is
+ a valid short option, don't consider it an abbreviated form of
+ a long option that starts with f. Otherwise there would be no
+ way to give the -f short option.
+
+ On the other hand, if there's a long option "fubar" and
+ the ARGV-element is "-fu", do consider that an abbreviation of
+ the long option, just like "--fu", and not "-f" with arg "u".
+
+ This distinction seems to be the most useful approach. */
+
+ if(longopts != NULL
+ && (argv[optind][1] == '-'
+ || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1]))))) {
+ char *nameend;
+ const struct option *p;
+ const struct option *pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = -1;
+ int option_index;
+
+ for(nameend = nextchar; *nameend && *nameend != '='; nameend++)
+ /* Do nothing. */ ;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for(p = longopts, option_index = 0; p->name; p++, option_index++)
+ if(!strncmp(p->name, nextchar, nameend - nextchar)) {
+ if((unsigned int)(nameend - nextchar)
+ == (unsigned int) strlen(p->name)) {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ } else if(pfound == NULL) {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ } else
+ /* Second or later nonexact match found. */
+ {
+ ambig = 1;
+ }
+ }
+
+ if(ambig && !exact) {
+ if(opterr)
+ fprintf(stderr, "%s: option `%s' is ambiguous\n",
+ argv[0], argv[optind]);
+
+ nextchar += strlen(nextchar);
+ optind++;
+ optopt = 0;
+ return '?';
}
- }
- else if (pfound->has_arg == 1)
- {
- if (optind < argc)
- optarg = argv[optind++];
- else
- {
- if (opterr)
- fprintf (stderr,
- "%s: option `%s' requires an argument\n",
- argv[0], argv[optind - 1]);
- nextchar += strlen (nextchar);
- optopt = pfound->val;
- return optstring[0] == ':' ? ':' : '?';
+
+ if(pfound != NULL) {
+ option_index = indfound;
+ optind++;
+
+ if(*nameend) {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if(pfound->has_arg) {
+ optarg = nameend + 1;
+ } else {
+ if(opterr) {
+ if(argv[optind - 1][1] == '-')
+ /* --option */
+ fprintf(stderr,
+ "%s: option `--%s' doesn't allow an argument\n",
+ argv[0], pfound->name);
+ else
+ /* +option or -option */
+ fprintf(stderr,
+ "%s: option `%c%s' doesn't allow an argument\n",
+ argv[0], argv[optind - 1][0], pfound->name);
+ }
+
+ nextchar += strlen(nextchar);
+
+ optopt = pfound->val;
+ return '?';
+ }
+ } else if(pfound->has_arg == 1) {
+ if(optind < argc) {
+ optarg = argv[optind++];
+ } else {
+ if(opterr)
+ fprintf(stderr,
+ "%s: option `%s' requires an argument\n",
+ argv[0], argv[optind - 1]);
+
+ nextchar += strlen(nextchar);
+ optopt = pfound->val;
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+
+ nextchar += strlen(nextchar);
+
+ if(longind != NULL) {
+ *longind = option_index;
+ }
+
+ if(pfound->flag) {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+
+ return pfound->val;
+ }
+
+ /* Can't find it as a long option. If this is not getopt_long_only,
+ or the option starts with '--' or is not a valid short
+ option, then it's an error.
+ Otherwise interpret it as a short option. */
+ if(!long_only || argv[optind][1] == '-'
+ || my_index(optstring, *nextchar) == NULL) {
+ if(opterr) {
+ if(argv[optind][1] == '-')
+ /* --option */
+ fprintf(stderr, "%s: unrecognized option `--%s'\n",
+ argv[0], nextchar);
+ else
+ /* +option or -option */
+ fprintf(stderr, "%s: unrecognized option `%c%s'\n",
+ argv[0], argv[optind][0], nextchar);
+ }
+
+ nextchar = (char *) "";
+ optind++;
+ optopt = 0;
+ return '?';
}
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
}
- /* Can't find it as a long option. If this is not getopt_long_only,
- or the option starts with '--' or is not a valid short
- option, then it's an error.
- Otherwise interpret it as a short option. */
- if (!long_only || argv[optind][1] == '-'
- || my_index (optstring, *nextchar) == NULL)
+ /* Look at and handle the next short option-character. */
+
{
- if (opterr)
- {
- if (argv[optind][1] == '-')
- /* --option */
- fprintf (stderr, "%s: unrecognized option `--%s'\n",
- argv[0], nextchar);
- else
- /* +option or -option */
- fprintf (stderr, "%s: unrecognized option `%c%s'\n",
- argv[0], argv[optind][0], nextchar);
- }
- nextchar = (char *) "";
- optind++;
- optopt = 0;
- return '?';
- }
- }
-
- /* Look at and handle the next short option-character. */
-
- {
- char c = *nextchar++;
- char *temp = my_index (optstring, c);
-
- /* Increment `optind' when we start to process its last character. */
- if (*nextchar == '\0')
- ++optind;
-
- if (temp == NULL || c == ':')
- {
- if (opterr)
- {
- if (posixly_correct)
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, "%s: illegal option -- %c\n",
- argv[0], c);
- else
- fprintf (stderr, "%s: invalid option -- %c\n",
- argv[0], c);
- }
- optopt = c;
- return '?';
- }
- /* Convenience. Treat POSIX -W foo same as long option --foo */
- if (temp[0] == 'W' && temp[1] == ';')
- {
- char *nameend;
- const struct option *p;
- const struct option *pfound = NULL;
- int exact = 0;
- int ambig = 0;
- int indfound = 0;
- int option_index;
-
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- optind++;
- }
- else if (optind == argc)
- {
- if (opterr)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, "%s: option requires an argument -- %c\n",
- argv[0], c);
- }
- optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- return c;
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- optarg = argv[optind++];
-
- /* optarg is now the argument, see if it's in the
- table of longopts. */
-
- for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
-
- /* Test all long options for either exact match
- or abbreviated matches. */
- for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar) == strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
+ char c = *nextchar++;
+ char *temp = my_index(optstring, c);
+
+ /* Increment `optind' when we start to process its last character. */
+ if(*nextchar == '\0') {
+ ++optind;
}
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
+
+ if(temp == NULL || c == ':') {
+ if(opterr) {
+ if(posixly_correct)
+ /* 1003.2 specifies the format of this message. */
+ fprintf(stderr, "%s: illegal option -- %c\n",
+ argv[0], c);
+ else
+ fprintf(stderr, "%s: invalid option -- %c\n",
+ argv[0], c);
+ }
+
+ optopt = c;
+ return '?';
+ }
+
+ /* Convenience. Treat POSIX -W foo same as long option --foo */
+ if(temp[0] == 'W' && temp[1] == ';') {
+ char *nameend;
+ const struct option *p;
+ const struct option *pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = 0;
+ int option_index;
+
+ /* This is an option that requires an argument. */
+ if(*nextchar != '\0') {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ } else if(optind == argc) {
+ if(opterr) {
+ /* 1003.2 specifies the format of this message. */
+ fprintf(stderr, "%s: option requires an argument -- %c\n",
+ argv[0], c);
+ }
+
+ optopt = c;
+
+ if(optstring[0] == ':') {
+ c = ':';
+ } else {
+ c = '?';
+ }
+
+ return c;
+ } else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ {
+ optarg = argv[optind++];
+ }
+
+ /* optarg is now the argument, see if it's in the
+ table of longopts. */
+
+ for(nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
+ /* Do nothing. */ ;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for(p = longopts, option_index = 0; p->name; p++, option_index++)
+ if(!strncmp(p->name, nextchar, nameend - nextchar)) {
+ if((unsigned int)(nameend - nextchar) == strlen(p->name)) {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ } else if(pfound == NULL) {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ } else
+ /* Second or later nonexact match found. */
+ {
+ ambig = 1;
+ }
+ }
+
+ if(ambig && !exact) {
+ if(opterr)
+ fprintf(stderr, "%s: option `-W %s' is ambiguous\n",
+ argv[0], argv[optind]);
+
+ nextchar += strlen(nextchar);
+ optind++;
+ return '?';
+ }
+
+ if(pfound != NULL) {
+ option_index = indfound;
+
+ if(*nameend) {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if(pfound->has_arg) {
+ optarg = nameend + 1;
+ } else {
+ if(opterr)
+ fprintf(stderr,
+ "%s: option `-W %s' doesn't allow an argument\n",
+ argv[0], pfound->name);
+
+ nextchar += strlen(nextchar);
+ return '?';
+ }
+ } else if(pfound->has_arg == 1) {
+ if(optind < argc) {
+ optarg = argv[optind++];
+ } else {
+ if(opterr)
+ fprintf(stderr,
+ "%s: option `%s' requires an argument\n",
+ argv[0], argv[optind - 1]);
+
+ nextchar += strlen(nextchar);
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+
+ nextchar += strlen(nextchar);
+
+ if(longind != NULL) {
+ *longind = option_index;
+ }
+
+ if(pfound->flag) {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+
+ return pfound->val;
+ }
+
+ nextchar = NULL;
+ return 'W'; /* Let the application handle it. */
}
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
- if (ambig && !exact)
- {
- if (opterr)
- fprintf (stderr, "%s: option `-W %s' is ambiguous\n",
- argv[0], argv[optind]);
- nextchar += strlen (nextchar);
- optind++;
- return '?';
- }
- if (pfound != NULL)
- {
- option_index = indfound;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- optarg = nameend + 1;
- else
- {
- if (opterr)
- fprintf (stderr,
- "%s: option `-W %s' doesn't allow an argument\n",
- argv[0], pfound->name);
-
- nextchar += strlen (nextchar);
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (optind < argc)
- optarg = argv[optind++];
- else
- {
- if (opterr)
- fprintf (stderr,
- "%s: option `%s' requires an argument\n",
- argv[0], argv[optind - 1]);
- nextchar += strlen (nextchar);
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
- nextchar = NULL;
- return 'W'; /* Let the application handle it. */
- }
- if (temp[1] == ':')
- {
- if (temp[2] == ':')
- {
- /* This is an option that accepts an argument optionally. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- optind++;
- }
- else
- optarg = NULL;
- nextchar = NULL;
- }
- else
- {
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- optind++;
- }
- else if (optind == argc)
- {
- if (opterr)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr,
- "%s: option requires an argument -- %c\n",
- argv[0], c);
- }
- optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- optarg = argv[optind++];
- nextchar = NULL;
- }
- }
- return c;
- }
+
+ if(temp[1] == ':') {
+ if(temp[2] == ':') {
+ /* This is an option that accepts an argument optionally. */
+ if(*nextchar != '\0') {
+ optarg = nextchar;
+ optind++;
+ } else {
+ optarg = NULL;
+ }
+
+ nextchar = NULL;
+ } else {
+ /* This is an option that requires an argument. */
+ if(*nextchar != '\0') {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ } else if(optind == argc) {
+ if(opterr) {
+ /* 1003.2 specifies the format of this message. */
+ fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ argv[0], c);
+ }
+
+ optopt = c;
+
+ if(optstring[0] == ':') {
+ c = ':';
+ } else {
+ c = '?';
+ }
+ } else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ {
+ optarg = argv[optind++];
+ }
+
+ nextchar = NULL;
+ }
+ }
+
+ return c;
+ }
}
int
-getopt (argc, argv, optstring)
- int argc;
- char *const *argv;
- const char *optstring;
+getopt(argc, argv, optstring)
+int argc;
+char *const *argv;
+const char *optstring;
{
- return _getopt_internal (argc, argv, optstring,
- (const struct option *) 0,
- (int *) 0,
- 0);
+ return _getopt_internal(argc, argv, optstring,
+ (const struct option *) 0,
+ (int *) 0,
+ 0);
}
-#endif /* Not ELIDE_CODE. */
+#endif /* Not ELIDE_CODE. */
\f
#ifdef TEST
the above definition of `getopt'. */
int
-main (argc, argv)
- int argc;
- char **argv;
+main(argc, argv)
+int argc;
+char **argv;
{
- int c;
- int digit_optind = 0;
+ int c;
+ int digit_optind = 0;
- while (1)
- {
- int this_option_optind = optind ? optind : 1;
+ while(1) {
+ int this_option_optind = optind ? optind : 1;
- c = getopt (argc, argv, "abc:d:0123456789");
- if (c == -1)
- break;
+ c = getopt(argc, argv, "abc:d:0123456789");
- switch (c)
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
+ if(c == -1) {
+ break;
+ }
+
+ switch(c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if(digit_optind != 0 && digit_optind != this_option_optind) {
+ printf("digits occur in two different argv-elements.\n");
+ }
+
+ digit_optind = this_option_optind;
+ printf("option %c\n", c);
+ break;
+
+ case 'a':
+ printf("option a\n");
+ break;
+
+ case 'b':
+ printf("option b\n");
+ break;
+
+ case 'c':
+ printf("option c with value `%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf("?? getopt returned character code 0%o ??\n", c);
+ }
}
- }
- if (optind < argc)
- {
- printf ("non-option ARGV-elements: ");
- while (optind < argc)
- printf ("%s ", argv[optind++]);
- printf ("\n");
- }
+ if(optind < argc) {
+ printf("non-option ARGV-elements: ");
+
+ while(optind < argc) {
+ printf("%s ", argv[optind++]);
+ }
+
+ printf("\n");
+ }
- exit (0);
+ exit(0);
}
#endif /* TEST */
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-#ifdef cplusplus
+#ifdef cplusplus
extern "C" {
#endif
-/* For communication from `getopt' to the caller.
- When `getopt' finds an option that takes an argument,
- the argument value is returned here.
- Also, when `ordering' is RETURN_IN_ORDER,
- each non-option ARGV-element is returned here. */
+ /* For communication from `getopt' to the caller.
+ When `getopt' finds an option that takes an argument,
+ the argument value is returned here.
+ Also, when `ordering' is RETURN_IN_ORDER,
+ each non-option ARGV-element is returned here. */
-extern char *optarg;
+ extern char *optarg;
-/* Index in ARGV of the next element to be scanned.
- This is used for communication to and from the caller
- and for communication between successive calls to `getopt'.
+ /* Index in ARGV of the next element to be scanned.
+ This is used for communication to and from the caller
+ and for communication between successive calls to `getopt'.
- On entry to `getopt', zero means this is the first call; initialize.
+ On entry to `getopt', zero means this is the first call; initialize.
- When `getopt' returns -1, this is the index of the first of the
- non-option elements that the caller should itself scan.
+ When `getopt' returns -1, this is the index of the first of the
+ non-option elements that the caller should itself scan.
- Otherwise, `optind' communicates from one call to the next
- how much of ARGV has been scanned so far. */
+ Otherwise, `optind' communicates from one call to the next
+ how much of ARGV has been scanned so far. */
-extern int optind;
+ extern int optind;
-/* Callers store zero here to inhibit the error message `getopt' prints
- for unrecognized options. */
+ /* Callers store zero here to inhibit the error message `getopt' prints
+ for unrecognized options. */
-extern int opterr;
+ extern int opterr;
-/* Set to an option character which was unrecognized. */
+ /* Set to an option character which was unrecognized. */
-extern int optopt;
+ extern int optopt;
-/* Describe the long-named options requested by the application.
- The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
- of `struct option' terminated by an element containing a name which is
- zero.
+ /* Describe the long-named options requested by the application.
+ The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
+ of `struct option' terminated by an element containing a name which is
+ zero.
- The field `has_arg' is:
- no_argument (or 0) if the option does not take an argument,
- required_argument (or 1) if the option requires an argument,
- optional_argument (or 2) if the option takes an optional argument.
+ The field `has_arg' is:
+ no_argument (or 0) if the option does not take an argument,
+ required_argument (or 1) if the option requires an argument,
+ optional_argument (or 2) if the option takes an optional argument.
- If the field `flag' is not NULL, it points to a variable that is set
- to the value given in the field `val' when the option is found, but
- left unchanged if the option is not found.
+ If the field `flag' is not NULL, it points to a variable that is set
+ to the value given in the field `val' when the option is found, but
+ left unchanged if the option is not found.
- To have a long-named option do something other than set an `int' to
- a compiled-in constant, such as set a value from `optarg', set the
- option's `flag' field to zero and its `val' field to a nonzero
- value (the equivalent single-letter option character, if there is
- one). For long options that have a zero `flag' field, `getopt'
- returns the contents of the `val' field. */
+ To have a long-named option do something other than set an `int' to
+ a compiled-in constant, such as set a value from `optarg', set the
+ option's `flag' field to zero and its `val' field to a nonzero
+ value (the equivalent single-letter option character, if there is
+ one). For long options that have a zero `flag' field, `getopt'
+ returns the contents of the `val' field. */
-struct option
-{
+ struct option {
#if defined (STDC) && STDC
- const char *name;
+ const char *name;
#else
- char *name;
+ char *name;
#endif
- /* has_arg can't be an enum because some compilers complain about
- type mismatches in all the code that assumes it is an int. */
- int has_arg;
- int *flag;
- int val;
-};
+ /* has_arg can't be an enum because some compilers complain about
+ type mismatches in all the code that assumes it is an int. */
+ int has_arg;
+ int *flag;
+ int val;
+ };
-/* Names for the values of the `has_arg' field of `struct option'. */
+ /* Names for the values of the `has_arg' field of `struct option'. */
-#define no_argument 0
-#define required_argument 1
-#define optional_argument 2
+#define no_argument 0
+#define required_argument 1
+#define optional_argument 2
#if defined (STDC) && STDC
#ifdef GNU_LIBRARY
-/* Many other libraries have conflicting prototypes for getopt, with
- differences in the consts, in stdlib.h. To avoid compilation
- errors, only prototype getopt for the GNU C library. */
-extern int getopt (int argc, char *const *argv, const char *shortopts);
+ /* Many other libraries have conflicting prototypes for getopt, with
+ differences in the consts, in stdlib.h. To avoid compilation
+ errors, only prototype getopt for the GNU C library. */
+ extern int getopt(int argc, char *const *argv, const char *shortopts);
#else /* not GNU_LIBRARY */
-extern int getopt ();
+ extern int getopt();
#endif /* GNU_LIBRARY */
-extern int getopt_long (int argc, char *const *argv, const char *shortopts,
- const struct option *longopts, int *longind);
-extern int getopt_long_only (int argc, char *const *argv,
- const char *shortopts,
- const struct option *longopts, int *longind);
-
-/* Internal only. Users should not call this directly. */
-extern int _getopt_internal (int argc, char *const *argv,
- const char *shortopts,
- const struct option *longopts, int *longind,
- int long_only);
+ extern int getopt_long(int argc, char *const *argv, const char *shortopts,
+ const struct option *longopts, int *longind);
+ extern int getopt_long_only(int argc, char *const *argv,
+ const char *shortopts,
+ const struct option *longopts, int *longind);
+
+ /* Internal only. Users should not call this directly. */
+ extern int _getopt_internal(int argc, char *const *argv,
+ const char *shortopts,
+ const struct option *longopts, int *longind,
+ int long_only);
#else /* not STDC */
-extern int getopt ();
-extern int getopt_long ();
-extern int getopt_long_only ();
+ extern int getopt();
+ extern int getopt_long();
+ extern int getopt_long_only();
-extern int _getopt_internal ();
+ extern int _getopt_internal();
#endif /* STDC */
-#ifdef cplusplus
+#ifdef cplusplus
}
#endif
#include <stdlib.h>
#endif
-#ifndef NULL
+#ifndef NULL
#define NULL 0
#endif
int
-getopt_long (argc, argv, options, long_options, opt_index)
- int argc;
- char *const *argv;
- const char *options;
- const struct option *long_options;
- int *opt_index;
+getopt_long(argc, argv, options, long_options, opt_index)
+int argc;
+char *const *argv;
+const char *options;
+const struct option *long_options;
+int *opt_index;
{
- return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
+ return _getopt_internal(argc, argv, options, long_options, opt_index, 0);
}
/* Like getopt_long, but '-' as well as '--' can indicate a long option.
instead. */
int
-getopt_long_only (argc, argv, options, long_options, opt_index)
- int argc;
- char *const *argv;
- const char *options;
- const struct option *long_options;
- int *opt_index;
+getopt_long_only(argc, argv, options, long_options, opt_index)
+int argc;
+char *const *argv;
+const char *options;
+const struct option *long_options;
+int *opt_index;
{
- return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
+ return _getopt_internal(argc, argv, options, long_options, opt_index, 1);
}
-#endif /* Not ELIDE_CODE. */
+#endif /* Not ELIDE_CODE. */
\f
#ifdef TEST
#include <stdio.h>
int
-main (argc, argv)
- int argc;
- char **argv;
+main(argc, argv)
+int argc;
+char **argv;
{
- int c;
- int digit_optind = 0;
-
- while (1)
- {
- int this_option_optind = optind ? optind : 1;
- int option_index = 0;
- static struct option long_options[] =
- {
- {"add", 1, 0, 0},
- {"append", 0, 0, 0},
- {"delete", 1, 0, 0},
- {"verbose", 0, 0, 0},
- {"create", 0, 0, 0},
- {"file", 1, 0, 0},
- {0, 0, 0, 0}
- };
-
- c = getopt_long (argc, argv, "abc:d:0123456789",
- long_options, &option_index);
- if (c == -1)
- break;
-
- switch (c)
- {
- case 0:
- printf ("option %s", long_options[option_index].name);
- if (optarg)
- printf (" with arg %s", optarg);
- printf ("\n");
- break;
-
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case 'd':
- printf ("option d with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
+ int c;
+ int digit_optind = 0;
+
+ while(1) {
+ int this_option_optind = optind ? optind : 1;
+ int option_index = 0;
+ static struct option long_options[] = {
+ {"add", 1, 0, 0},
+ {"append", 0, 0, 0},
+ {"delete", 1, 0, 0},
+ {"verbose", 0, 0, 0},
+ {"create", 0, 0, 0},
+ {"file", 1, 0, 0},
+ {0, 0, 0, 0}
+ };
+
+ c = getopt_long(argc, argv, "abc:d:0123456789",
+ long_options, &option_index);
+
+ if(c == -1) {
+ break;
+ }
+
+ switch(c) {
+ case 0:
+ printf("option %s", long_options[option_index].name);
+
+ if(optarg) {
+ printf(" with arg %s", optarg);
+ }
+
+ printf("\n");
+ break;
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if(digit_optind != 0 && digit_optind != this_option_optind) {
+ printf("digits occur in two different argv-elements.\n");
+ }
+
+ digit_optind = this_option_optind;
+ printf("option %c\n", c);
+ break;
+
+ case 'a':
+ printf("option a\n");
+ break;
+
+ case 'b':
+ printf("option b\n");
+ break;
+
+ case 'c':
+ printf("option c with value `%s'\n", optarg);
+ break;
+
+ case 'd':
+ printf("option d with value `%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf("?? getopt returned character code 0%o ??\n", c);
+ }
}
- }
- if (optind < argc)
- {
- printf ("non-option ARGV-elements: ");
- while (optind < argc)
- printf ("%s ", argv[optind++]);
- printf ("\n");
- }
+ if(optind < argc) {
+ printf("non-option ARGV-elements: ");
- exit (0);
+ while(optind < argc) {
+ printf("%s ", argv[optind++]);
+ }
+
+ printf("\n");
+ }
+
+ exit(0);
}
#endif /* TEST */
/* Do we have something to do at all? */
- if(!edge_weight_tree->head)
+ if(!edge_weight_tree->head) {
return;
+ }
ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Running Kruskal's algorithm:");
for(node = edge_weight_tree->head; node; node = node->next) {
e = node->data;
+
if(e->from->status.reachable) {
e->from->status.visited = true;
break;
e->from->status.visited = true;
e->to->status.visited = true;
- if(e->connection)
+ if(e->connection) {
e->connection->status.mst = true;
+ }
- if(e->reverse->connection)
+ if(e->reverse->connection) {
e->reverse->connection->status.mst = true;
+ }
safe_edges++;
ifdebug(SCARY_THINGS) logger(LOG_DEBUG, " Adding edge %s - %s weight %d", e->from->name,
- e->to->name, e->weight);
+ e->to->name, e->weight);
if(skipped) {
skipped = false;
}
ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Done, counted %d nodes and %d safe edges.", nodes,
- safe_edges);
+ safe_edges);
}
/* Implementation of a simple breadth-first search algorithm.
/* Loop while todo_list is filled */
- for(from = todo_list->head; from; from = todonext) { /* "from" is the node from which we start */
+ for(from = todo_list->head; from; from = todonext) { /* "from" is the node from which we start */
n = from->data;
- for(to = n->edge_tree->head; to; to = to->next) { /* "to" is the edge connected to "from" */
+ for(to = n->edge_tree->head; to; to = to->next) { /* "to" is the edge connected to "from" */
e = to->data;
- if(!e->reverse)
+ if(!e->reverse) {
continue;
+ }
/* Situation:
- /
- /
+ /
+ /
----->(n)---e-->(e->to)
- \
- \
+ \
+ \
Where e is an edge, (n) and (e->to) are nodes.
n->address is set to the e->address of the edge left of n to n.
indirect = n->status.indirect || e->options & OPTION_INDIRECT;
if(e->to->status.visited
- && (!e->to->status.indirect || indirect))
+ && (!e->to->status.indirect || indirect)) {
continue;
+ }
// Only update nexthop the first time we visit this node.
- if(!e->to->status.visited)
+ if(!e->to->status.visited) {
e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
+ }
e->to->status.visited = true;
e->to->status.indirect = indirect;
e->to->via = indirect ? n->via : e->to;
e->to->options = e->options;
- if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN)
+ if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN) {
update_node_udp(e->to, &e->address);
+ }
list_insert_tail(todo_list, e->to);
}
if(n->status.reachable) {
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became reachable",
- n->name, n->hostname);
+ n->name, n->hostname);
} else {
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became unreachable",
- n->name, n->hostname);
+ n->name, n->hostname);
}
/* TODO: only clear status.validkey if node is unreachable? */
execute_script(n->status.reachable ? "host-up" : "host-down", envp);
xasprintf(&name,
- n->status.reachable ? "hosts/%s-up" : "hosts/%s-down",
- n->name);
+ n->status.reachable ? "hosts/%s-up" : "hosts/%s-down",
+ n->name);
execute_script(name, envp);
free(name);
free(address);
free(port);
- for(i = 0; i < 7; i++)
+ for(i = 0; i < 7; i++) {
free(envp[i]);
+ }
subnet_update(n, NULL, n->status.reachable);
/* Dump nodes and edges to a graphviz file.
-
+
The file can be converted to an image with
dot -Tpng graph_filename -o image_filename.png -Gconcentrate=true
*/
edge_t *e;
char *filename = NULL, *tmpname = NULL;
FILE *file, *pipe = NULL;
-
- if(!graph_changed || !get_config_string(lookup_config(config_tree, "GraphDumpFile"), &filename))
+
+ if(!graph_changed || !get_config_string(lookup_config(config_tree, "GraphDumpFile"), &filename)) {
return;
+ }
graph_changed = false;
ifdebug(PROTOCOL) logger(LOG_NOTICE, "Dumping graph");
-
+
if(filename[0] == '|') {
file = pipe = popen(filename + 1, "w");
} else {
}
fprintf(file, "digraph {\n");
-
+
/* dump all nodes first */
for(node = node_tree->head; node; node = node->next) {
n = node->data;
fprintf(file, " %s -> %s;\n", e->from->name, e->to->name);
}
- fprintf(file, "}\n");
-
+ fprintf(file, "}\n");
+
if(pipe) {
pclose(pipe);
} else {
#ifdef HAVE_MINGW
unlink(filename);
#endif
- if(rename(tmpname, filename))
+
+ if(rename(tmpname, filename)) {
logger(LOG_ERR, "Could not rename %s to %s: %s\n", tmpname, filename, strerror(errno));
+ }
+
free(tmpname);
}
#ifndef HAVE_STRUCT_IP
struct ip {
#if BYTE_ORDER == LITTLE_ENDIAN
- unsigned int ip_hl:4;
- unsigned int ip_v:4;
+ unsigned int ip_hl: 4;
+ unsigned int ip_v: 4;
#else
- unsigned int ip_v:4;
- unsigned int ip_hl:4;
+ unsigned int ip_v: 4;
+ unsigned int ip_hl: 4;
#endif
uint8_t ip_tos;
uint16_t ip_len;
- uint16_t ip_id;
+ uint16_t ip_id;
uint16_t ip_off;
#define IP_RF 0x8000
#define IP_DF 0x4000
uint8_t ip_p;
uint16_t ip_sum;
struct in_addr ip_src, ip_dst;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#endif
#ifndef IP_OFFMASK
#define icmp_radv icmp_dun.id_radv
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#endif
#endif
uint16_t u6_addr16[8];
uint32_t u6_addr32[4];
} in6_u;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#define s6_addr in6_u.u6_addr8
#define s6_addr16 in6_u.u6_addr16
#define s6_addr32 in6_u.u6_addr32
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#endif
#ifndef IN6_IS_ADDR_V4MAPPED
#define IN6_IS_ADDR_V4MAPPED(a) \
- ((((const uint32_t *) (a))[0] == 0) \
- && (((const uint32_t *) (a))[1] == 0) \
- && (((const uint32_t *) (a))[2] == htonl (0xffff)))
+ ((((const uint32_t *) (a))[0] == 0) \
+ && (((const uint32_t *) (a))[1] == 0) \
+ && (((const uint32_t *) (a))[2] == htonl (0xffff)))
#endif
#ifndef HAVE_STRUCT_IP6_HDR
} ip6_ctlun;
struct in6_addr ip6_src;
struct in6_addr ip6_dst;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#define ip6_vfc ip6_ctlun.ip6_un2_vfc
#define ip6_flow ip6_ctlun.ip6_un1.ip6_un1_flow
#define ip6_plen ip6_ctlun.ip6_un1.ip6_un1_plen
uint16_t icmp6_un_data16[2];
uint8_t icmp6_un_data8[4];
} icmp6_dataun;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#define ICMP6_DST_UNREACH_NOROUTE 0
#define ICMP6_DST_UNREACH 1
#define ICMP6_PACKET_TOO_BIG 2
struct nd_neighbor_solicit {
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define nd_ns_type nd_ns_hdr.icmp6_type
struct nd_opt_hdr {
uint8_t nd_opt_type;
uint8_t nd_opt_len;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
#endif
#endif
struct ifreq ifr;
bool t1q = false;
- if(!get_config_string(lookup_config(config_tree, "Device"), &device))
+ if(!get_config_string(lookup_config(config_tree, "Device"), &device)) {
device = xstrdup(DEFAULT_DEVICE);
+ }
if(!get_config_string(lookup_config(config_tree, "Interface"), &iface))
#ifdef HAVE_LINUX_IF_TUN_H
- if (netname != NULL)
+ if(netname != NULL) {
iface = xstrdup(netname);
+ }
+
#else
iface = xstrdup(strrchr(device, '/') ? strrchr(device, '/') + 1 : device);
#endif
device_type = DEVICE_TYPE_TUN;
device_info = "Linux tun/tap device (tun mode)";
} else {
- if (routing_mode == RMODE_ROUTER)
+ if(routing_mode == RMODE_ROUTER) {
overwrite_mac = true;
+ }
+
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
device_type = DEVICE_TYPE_TAP;
device_info = "Linux tun/tap device (tap mode)";
}
#ifdef IFF_ONE_QUEUE
+
/* Set IFF_ONE_QUEUE flag... */
- if(get_config_bool(lookup_config(config_tree, "IffOneQueue"), &t1q) && t1q)
+ if(get_config_bool(lookup_config(config_tree, "IffOneQueue"), &t1q) && t1q) {
ifr.ifr_flags |= IFF_ONE_QUEUE;
+ }
+
#endif
if(iface) {
} else
#endif
{
- if(routing_mode == RMODE_ROUTER)
+ if(routing_mode == RMODE_ROUTER) {
overwrite_mac = true;
+ }
+
device_info = "Linux ethertap device";
device_type = DEVICE_TYPE_ETHERTAP;
free(iface);
iface = xstrdup(strrchr(device, '/') ? strrchr(device, '/') + 1 : device);
}
- if(overwrite_mac && !ioctl(device_fd, SIOCGIFHWADDR, &ifr))
+ if(overwrite_mac && !ioctl(device_fd, SIOCGIFHWADDR, &ifr)) {
memcpy(mymac.x, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
+ }
logger(LOG_INFO, "%s is a %s", device, device_info);
static bool read_packet(vpn_packet_t *packet) {
int lenin;
-
+
switch(device_type) {
- case DEVICE_TYPE_TUN:
- lenin = read(device_fd, packet->data + 10, MTU - 10);
-
- if(lenin <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s",
- device_info, device, strerror(errno));
- return false;
- }
-
- memset(packet->data, 0, 12);
- packet->len = lenin + 10;
- break;
- case DEVICE_TYPE_TAP:
- lenin = read(device_fd, packet->data, MTU);
-
- if(lenin <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s",
- device_info, device, strerror(errno));
- return false;
- }
-
- packet->len = lenin;
- break;
- case DEVICE_TYPE_ETHERTAP:
- lenin = read(device_fd, packet->data - 2, MTU + 2);
-
- if(lenin <= 0) {
- logger(LOG_ERR, "Error while reading from %s %s: %s",
- device_info, device, strerror(errno));
- return false;
- }
-
- packet->len = lenin - 2;
- break;
+ case DEVICE_TYPE_TUN:
+ lenin = read(device_fd, packet->data + 10, MTU - 10);
+
+ if(lenin <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s",
+ device_info, device, strerror(errno));
+ return false;
+ }
+
+ memset(packet->data, 0, 12);
+ packet->len = lenin + 10;
+ break;
+
+ case DEVICE_TYPE_TAP:
+ lenin = read(device_fd, packet->data, MTU);
+
+ if(lenin <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s",
+ device_info, device, strerror(errno));
+ return false;
+ }
+
+ packet->len = lenin;
+ break;
+
+ case DEVICE_TYPE_ETHERTAP:
+ lenin = read(device_fd, packet->data - 2, MTU + 2);
+
+ if(lenin <= 0) {
+ logger(LOG_ERR, "Error while reading from %s %s: %s",
+ device_info, device, strerror(errno));
+ return false;
+ }
+
+ packet->len = lenin - 2;
+ break;
}
device_total_in += packet->len;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Read packet of %d bytes from %s", packet->len,
- device_info);
+ device_info);
return true;
}
static bool write_packet(vpn_packet_t *packet) {
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
- packet->len, device_info);
+ packet->len, device_info);
switch(device_type) {
- case DEVICE_TYPE_TUN:
- packet->data[10] = packet->data[11] = 0;
- if(write(device_fd, packet->data + 10, packet->len - 10) < 0) {
- logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
- strerror(errno));
- return false;
- }
- break;
- case DEVICE_TYPE_TAP:
- if(write(device_fd, packet->data, packet->len) < 0) {
- logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
- strerror(errno));
- return false;
- }
- break;
- case DEVICE_TYPE_ETHERTAP:
- memcpy(packet->data - 2, &packet->len, 2);
-
- if(write(device_fd, packet->data - 2, packet->len + 2) < 0) {
- logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
- strerror(errno));
- return false;
- }
- break;
+ case DEVICE_TYPE_TUN:
+ packet->data[10] = packet->data[11] = 0;
+
+ if(write(device_fd, packet->data + 10, packet->len - 10) < 0) {
+ logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
+ strerror(errno));
+ return false;
+ }
+
+ break;
+
+ case DEVICE_TYPE_TAP:
+ if(write(device_fd, packet->data, packet->len) < 0) {
+ logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
+ strerror(errno));
+ return false;
+ }
+
+ break;
+
+ case DEVICE_TYPE_ETHERTAP:
+ memcpy(packet->data - 2, &packet->len, 2);
+
+ if(write(device_fd, packet->data - 2, packet->len + 2) < 0) {
+ logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
+ strerror(errno));
+ return false;
+ }
+
+ break;
}
device_total_out += packet->len;
}
void list_free_node(list_t *list, list_node_t *node) {
- if(node->data && list->delete)
+ if(node->data && list->delete) {
list->delete(node->data);
+ }
free(node);
}
node->next = list->head;
list->head = node;
- if(node->next)
+ if(node->next) {
node->next->prev = node;
- else
+ } else {
list->tail = node;
+ }
list->count++;
node->prev = list->tail;
list->tail = node;
- if(node->prev)
+ if(node->prev) {
node->prev->next = node;
- else
+ } else {
list->head = node;
+ }
list->count++;
}
void list_unlink_node(list_t *list, list_node_t *node) {
- if(node->prev)
+ if(node->prev) {
node->prev->next = node->next;
- else
+ } else {
list->head = node->next;
+ }
- if(node->next)
+ if(node->next) {
node->next->prev = node->prev;
- else
+ } else {
list->tail = node->prev;
+ }
list->count--;
}
/* Head/tail lookup */
void *list_get_head(list_t *list) {
- if(list->head)
+ if(list->head) {
return list->head->data;
- else
+ } else {
return NULL;
+ }
}
void *list_get_tail(list_t *list) {
- if(list->tail)
+ if(list->tail) {
return list->tail->data;
- else
+ } else {
return NULL;
+ }
}
/* Fast list deletion */
for(node = list->head; node; node = next) {
next = node->next;
- if(node->data)
+
+ if(node->data) {
action(node->data);
+ }
}
}
/* (De)constructors */
-extern list_t *list_alloc(list_action_t) __attribute__ ((__malloc__));
+extern list_t *list_alloc(list_action_t) __attribute__((__malloc__));
extern void list_free(list_t *);
extern list_node_t *list_alloc_node(void);
extern void list_free_node(list_t *, list_node_t *);
void openlogger(const char *ident, logmode_t mode) {
logident = ident;
logmode = mode;
-
+
switch(mode) {
- case LOGMODE_STDERR:
- logpid = getpid();
- break;
- case LOGMODE_FILE:
- logpid = getpid();
- logfile = fopen(logfilename, "a");
- if(!logfile) {
- fprintf(stderr, "Could not open log file %s: %s\n", logfilename, strerror(errno));
- logmode = LOGMODE_NULL;
- }
- break;
- case LOGMODE_SYSLOG:
+ case LOGMODE_STDERR:
+ logpid = getpid();
+ break;
+
+ case LOGMODE_FILE:
+ logpid = getpid();
+ logfile = fopen(logfilename, "a");
+
+ if(!logfile) {
+ fprintf(stderr, "Could not open log file %s: %s\n", logfilename, strerror(errno));
+ logmode = LOGMODE_NULL;
+ }
+
+ break;
+
+ case LOGMODE_SYSLOG:
#ifdef HAVE_MINGW
- loghandle = RegisterEventSource(NULL, logident);
- if(!loghandle) {
- fprintf(stderr, "Could not open log handle!");
- logmode = LOGMODE_NULL;
- }
- break;
+ loghandle = RegisterEventSource(NULL, logident);
+
+ if(!loghandle) {
+ fprintf(stderr, "Could not open log handle!");
+ logmode = LOGMODE_NULL;
+ }
+
+ break;
#else
#ifdef HAVE_SYSLOG_H
- openlog(logident, LOG_CONS | LOG_PID, LOG_DAEMON);
- break;
+ openlog(logident, LOG_CONS | LOG_PID, LOG_DAEMON);
+ break;
#endif
#endif
- case LOGMODE_NULL:
- break;
+
+ case LOGMODE_NULL:
+ break;
}
}
void reopenlogger() {
- if(logmode != LOGMODE_FILE)
+ if(logmode != LOGMODE_FILE) {
return;
+ }
fflush(logfile);
FILE *newfile = fopen(logfilename, "a");
+
if(!newfile) {
logger(LOG_ERR, "Unable to reopen log file %s: %s", logfilename, strerror(errno));
return;
}
+
fclose(logfile);
logfile = newfile;
}
va_start(ap, format);
switch(logmode) {
- case LOGMODE_STDERR:
- vfprintf(stderr, format, ap);
- fprintf(stderr, "\n");
- fflush(stderr);
- break;
- case LOGMODE_FILE:
- now = time(NULL);
- strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now));
- fprintf(logfile, "%s %s[%ld]: ", timestr, logident, (long)logpid);
- vfprintf(logfile, format, ap);
- fprintf(logfile, "\n");
- fflush(logfile);
- break;
- case LOGMODE_SYSLOG:
+ case LOGMODE_STDERR:
+ vfprintf(stderr, format, ap);
+ fprintf(stderr, "\n");
+ fflush(stderr);
+ break;
+
+ case LOGMODE_FILE:
+ now = time(NULL);
+ strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now));
+ fprintf(logfile, "%s %s[%ld]: ", timestr, logident, (long)logpid);
+ vfprintf(logfile, format, ap);
+ fprintf(logfile, "\n");
+ fflush(logfile);
+ break;
+
+ case LOGMODE_SYSLOG:
#ifdef HAVE_MINGW
- {
- char message[4096];
- const char *messages[] = {message};
- vsnprintf(message, sizeof(message), format, ap);
- message[sizeof(message) - 1] = 0;
- ReportEvent(loghandle, priority, 0, 0, NULL, 1, 0, messages, NULL);
- }
+ {
+ char message[4096];
+ const char *messages[] = {message};
+ vsnprintf(message, sizeof(message), format, ap);
+ message[sizeof(message) - 1] = 0;
+ ReportEvent(loghandle, priority, 0, 0, NULL, 1, 0, messages, NULL);
+ }
+
#else
#ifdef HAVE_SYSLOG_H
#ifdef HAVE_VSYSLOG
- vsyslog(priority, format, ap);
+ vsyslog(priority, format, ap);
#else
- {
- char message[4096];
- vsnprintf(message, sizeof(message), format, ap);
- syslog(priority, "%s", message);
- }
+ {
+ char message[4096];
+ vsnprintf(message, sizeof(message), format, ap);
+ syslog(priority, "%s", message);
+ }
#endif
- break;
+ break;
#endif
#endif
- case LOGMODE_NULL:
- break;
+
+ case LOGMODE_NULL:
+ break;
}
va_end(ap);
void closelogger(void) {
switch(logmode) {
- case LOGMODE_FILE:
- fclose(logfile);
- break;
- case LOGMODE_SYSLOG:
+ case LOGMODE_FILE:
+ fclose(logfile);
+ break;
+
+ case LOGMODE_SYSLOG:
#ifdef HAVE_MINGW
- DeregisterEventSource(loghandle);
- break;
+ DeregisterEventSource(loghandle);
+ break;
#else
#ifdef HAVE_SYSLOG_H
- closelog();
- break;
+ closelog();
+ break;
#endif
#endif
- case LOGMODE_NULL:
- case LOGMODE_STDERR:
- break;
- break;
+
+ case LOGMODE_NULL:
+ case LOGMODE_STDERR:
+ break;
+ break;
}
}
*/
typedef enum debug_t {
- DEBUG_NOTHING = 0, /* Quiet mode, only show starting/stopping of the daemon */
+ DEBUG_NOTHING = 0, /* Quiet mode, only show starting/stopping of the daemon */
DEBUG_ALWAYS = 0,
- DEBUG_CONNECTIONS = 1, /* Show (dis)connects of other tinc daemons via TCP */
- DEBUG_ERROR = 2, /* Show error messages received from other hosts */
- DEBUG_STATUS = 2, /* Show status messages received from other hosts */
- DEBUG_PROTOCOL = 3, /* Show the requests that are sent/received */
- DEBUG_META = 4, /* Show contents of every request that is sent/received */
- DEBUG_TRAFFIC = 5, /* Show network traffic information */
- DEBUG_PACKET = 6, /* Show contents of each packet that is being sent/received */
- DEBUG_SCARY_THINGS = 10 /* You have been warned */
+ DEBUG_CONNECTIONS = 1, /* Show (dis)connects of other tinc daemons via TCP */
+ DEBUG_ERROR = 2, /* Show error messages received from other hosts */
+ DEBUG_STATUS = 2, /* Show status messages received from other hosts */
+ DEBUG_PROTOCOL = 3, /* Show the requests that are sent/received */
+ DEBUG_META = 4, /* Show contents of every request that is sent/received */
+ DEBUG_TRAFFIC = 5, /* Show network traffic information */
+ DEBUG_PACKET = 6, /* Show contents of each packet that is being sent/received */
+ DEBUG_SCARY_THINGS = 10 /* You have been warned */
} debug_t;
typedef enum logmode_t {
extern debug_t debug_level;
extern void openlogger(const char *, logmode_t);
extern void reopenlogger(void);
-extern void logger(int, const char *, ...) __attribute__ ((__format__(printf, 2, 3)));
+extern void logger(int, const char *, ...) __attribute__((__format__(printf, 2, 3)));
extern void closelogger(void);
#define ifdebug(l) if(debug_level >= DEBUG_##l)
int result;
ifdebug(META) logger(LOG_DEBUG, "Sending %d bytes of metadata to %s (%s)", length,
- c->name, c->hostname);
+ c->name, c->hostname);
- if(!c->outbuflen)
+ if(!c->outbuflen) {
c->last_flushed_time = now;
+ }
/* Find room in connection's buffer */
if(length + c->outbuflen > c->outbufsize) {
}
result = EVP_EncryptUpdate(c->outctx, (unsigned char *)c->outbuf + c->outbufstart + c->outbuflen,
- &outlen, (unsigned char *)buffer, length);
+ &outlen, (unsigned char *)buffer, length);
+
if(!result || outlen < length) {
logger(LOG_ERR, "Error while encrypting metadata to %s (%s): %s",
- c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
+ c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
return false;
} else if(outlen > length) {
logger(LOG_EMERG, "Encrypted data too long! Heap corrupted!");
abort();
}
+
c->outbuflen += outlen;
} else {
memcpy(c->outbuf + c->outbufstart + c->outbuflen, buffer, length);
bool flush_meta(connection_t *c) {
int result;
-
+
ifdebug(META) logger(LOG_DEBUG, "Flushing %d bytes to %s (%s)",
- c->outbuflen, c->name, c->hostname);
+ c->outbuflen, c->name, c->hostname);
while(c->outbuflen) {
result = send(c->socket, c->outbuf + c->outbufstart, c->outbuflen, 0);
+
if(result <= 0) {
if(!errno || errno == EPIPE) {
ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection closed by %s (%s)",
- c->name, c->hostname);
+ c->name, c->hostname);
} else if(errno == EINTR) {
continue;
} else if(sockwouldblock(sockerrno)) {
ifdebug(META) logger(LOG_DEBUG, "Flushing %d bytes to %s (%s) would block",
- c->outbuflen, c->name, c->hostname);
+ c->outbuflen, c->name, c->hostname);
return true;
} else {
logger(LOG_ERR, "Flushing meta data to %s (%s) failed: %s", c->name,
- c->hostname, sockstrerror(sockerrno));
+ c->hostname, sockstrerror(sockerrno));
}
return false;
for(node = connection_tree->head; node; node = node->next) {
c = node->data;
- if(c != from && c->status.active)
+ if(c != from && c->status.active) {
send_meta(c, buffer, length);
+ }
}
}
if(lenin <= 0) {
if(!lenin || !errno) {
ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection closed by %s (%s)",
- c->name, c->hostname);
- } else if(sockwouldblock(sockerrno))
+ c->name, c->hostname);
+ } else if(sockwouldblock(sockerrno)) {
return true;
- else
+ } else
logger(LOG_ERR, "Metadata socket read error for %s (%s): %s",
- c->name, c->hostname, sockstrerror(sockerrno));
+ c->name, c->hostname, sockstrerror(sockerrno));
return false;
}
if(c->allow_request == PROXY) {
reqlen = receive_proxy_meta(c, oldlen, lenin);
- if(reqlen < 0)
+
+ if(reqlen < 0) {
return false;
+ }
+
goto consume;
}
}
result = EVP_DecryptUpdate(c->inctx, (unsigned char *)inbuf, &lenout, (unsigned char *)c->buffer + oldlen, lenin);
+
if(!result || lenout != lenin) {
logger(LOG_ERR, "Error while decrypting metadata from %s (%s): %s",
- c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
+ c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
return false;
}
+
memcpy(c->buffer + oldlen, inbuf, lenin);
decrypted = true;
}
for(i = oldlen; i < c->buflen; i++) {
if(c->buffer[i] == '\n') {
- c->buffer[i] = '\0'; /* replace end-of-line by end-of-string so we can use sscanf */
+ c->buffer[i] = '\0'; /* replace end-of-line by end-of-string so we can use sscanf */
c->reqlen = reqlen = i + 1;
break;
}
}
- if(reqlen && !receive_request(c))
+ if(reqlen && !receive_request(c)) {
return false;
+ }
}
consume:
+
if(reqlen) {
c->buflen -= reqlen;
lenin -= reqlen - oldlen;
if(c->buflen >= MAXBUFSIZE) {
logger(LOG_ERR, "Metadata read buffer overflow for %s (%s)",
- c->name, c->hostname);
+ c->name, c->hostname);
return false;
}
//=============
#define TAP_CONTROL_CODE(request,method) \
- CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS)
+ CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS)
#define TAP_IOCTL_GET_MAC TAP_CONTROL_CODE (1, METHOD_BUFFERED)
#define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED)
if(!status) {
if(GetLastError() == ERROR_IO_PENDING) {
WaitForSingleObject(r_overlapped.hEvent, INFINITE);
- if(!GetOverlappedResult(device_handle, &r_overlapped, &len, FALSE))
+
+ if(!GetOverlappedResult(device_handle, &r_overlapped, &len, FALSE)) {
continue;
+ }
} else {
logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
+ device, strerror(errno));
errors++;
+
if(errors >= 10) {
EnterCriticalSection(&mutex);
running = false;
LeaveCriticalSection(&mutex);
}
+
usleep(1000000);
continue;
}
get_config_string(lookup_config(config_tree, "Device"), &device);
get_config_string(lookup_config(config_tree, "Interface"), &iface);
- if(device && iface)
+ if(device && iface) {
logger(LOG_WARNING, "Warning: both Device and Interface specified, results may not be as expected");
+ }
/* Open registry and look for network adapters */
return false;
}
- for (i = 0; ; i++) {
+ for(i = 0; ; i++) {
len = sizeof(adapterid);
- if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
+
+ if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL)) {
break;
+ }
/* Find out more about this adapter */
snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, adapterid);
- if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
+ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2)) {
continue;
+ }
len = sizeof(adaptername);
err = RegQueryValueEx(key2, "Name", 0, 0, (LPBYTE)adaptername, &len);
RegCloseKey(key2);
- if(err)
+ if(err) {
continue;
+ }
if(device) {
if(!strcmp(device, adapterid)) {
found = true;
break;
- } else
+ } else {
continue;
+ }
}
if(iface) {
if(!strcmp(iface, adaptername)) {
found = true;
break;
- } else
+ } else {
continue;
+ }
}
snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
+
if(device_handle != INVALID_HANDLE_VALUE) {
found = true;
break;
return false;
}
- if(!device)
+ if(!device) {
device = xstrdup(adapterid);
+ }
- if(!iface)
+ if(!iface) {
iface = xstrdup(adaptername);
+ }
/* Try to open the corresponding tap device */
snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);
device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
}
-
+
if(device_handle == INVALID_HANDLE_VALUE) {
logger(LOG_ERR, "%s (%s) is not a usable Windows tap device: %s", device, iface, winerror(GetLastError()));
return false;
static vpn_packet_t queue;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
- packet->len, device_info);
+ packet->len, device_info);
/* Check if there is something in progress */
if(queue.len) {
DWORD size;
BOOL success = GetOverlappedResult(device_handle, &w_overlapped, &size, FALSE);
+
if(success) {
ResetEvent(&w_overlapped);
queue.len = 0;
} else {
int err = GetLastError();
+
if(err != ERROR_IO_INCOMPLETE) {
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error completing previously queued write: %s", winerror(err));
ResetEvent(&w_overlapped);
if(!WriteFile(device_handle, queue.data, packet->len, &lenout, &w_overlapped)) {
int err = GetLastError();
+
if(err != ERROR_IO_PENDING) {
logger(LOG_ERR, "Error while writing to %s %s: %s", device_info, device, winerror(err));
return false;
}
+
// Write is being done asynchronously.
queue.len = packet->len;
} else {
host = xstrdup(device);
space = strchr(host, ' ');
+
if(!space) {
logger(LOG_ERR, "Port number required for %s", device_info);
free(host);
}
ai = str2addrinfo(host, port, SOCK_DGRAM);
+
if(!ai) {
free(host);
return false;
}
device_fd = socket(ai->ai_family, SOCK_DGRAM, IPPROTO_UDP);
+
if(device_fd < 0) {
logger(LOG_ERR, "Creating socket failed: %s", sockstrerror(sockerrno));
free(host);
switch(ai->ai_family) {
#ifdef IP_ADD_MEMBERSHIP
- case AF_INET: {
- struct ip_mreq mreq;
- struct sockaddr_in in;
- memcpy(&in, ai->ai_addr, sizeof(in));
- mreq.imr_multiaddr.s_addr = in.sin_addr.s_addr;
- mreq.imr_interface.s_addr = htonl(INADDR_ANY);
- if(setsockopt(device_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq, sizeof(mreq))) {
- logger(LOG_ERR, "Cannot join multicast group %s %s: %s", host, port, sockstrerror(sockerrno));
- closesocket(device_fd);
- free(host);
- return false;
- }
+
+ case AF_INET: {
+ struct ip_mreq mreq;
+ struct sockaddr_in in;
+ memcpy(&in, ai->ai_addr, sizeof(in));
+ mreq.imr_multiaddr.s_addr = in.sin_addr.s_addr;
+ mreq.imr_interface.s_addr = htonl(INADDR_ANY);
+
+ if(setsockopt(device_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq, sizeof(mreq))) {
+ logger(LOG_ERR, "Cannot join multicast group %s %s: %s", host, port, sockstrerror(sockerrno));
+ closesocket(device_fd);
+ free(host);
+ return false;
+ }
+
#ifdef IP_MULTICAST_LOOP
- setsockopt(device_fd, IPPROTO_IP, IP_MULTICAST_LOOP, (const void *)&one, sizeof(one));
+ setsockopt(device_fd, IPPROTO_IP, IP_MULTICAST_LOOP, (const void *)&one, sizeof(one));
#endif
#ifdef IP_MULTICAST_TTL
- setsockopt(device_fd, IPPROTO_IP, IP_MULTICAST_TTL, (void *)&ttl, sizeof(ttl));
+ setsockopt(device_fd, IPPROTO_IP, IP_MULTICAST_TTL, (void *)&ttl, sizeof(ttl));
#endif
- } break;
+ }
+ break;
#endif
#ifdef IPV6_JOIN_GROUP
- case AF_INET6: {
- struct ipv6_mreq mreq;
- struct sockaddr_in6 in6;
- memcpy(&in6, ai->ai_addr, sizeof(in6));
- memcpy(&mreq.ipv6mr_multiaddr, &in6.sin6_addr, sizeof(mreq.ipv6mr_multiaddr));
- mreq.ipv6mr_interface = in6.sin6_scope_id;
- if(setsockopt(device_fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (void *)&mreq, sizeof(mreq))) {
- logger(LOG_ERR, "Cannot join multicast group %s %s: %s", host, port, sockstrerror(sockerrno));
- closesocket(device_fd);
- free(host);
- return false;
- }
+
+ case AF_INET6: {
+ struct ipv6_mreq mreq;
+ struct sockaddr_in6 in6;
+ memcpy(&in6, ai->ai_addr, sizeof(in6));
+ memcpy(&mreq.ipv6mr_multiaddr, &in6.sin6_addr, sizeof(mreq.ipv6mr_multiaddr));
+ mreq.ipv6mr_interface = in6.sin6_scope_id;
+
+ if(setsockopt(device_fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (void *)&mreq, sizeof(mreq))) {
+ logger(LOG_ERR, "Cannot join multicast group %s %s: %s", host, port, sockstrerror(sockerrno));
+ closesocket(device_fd);
+ free(host);
+ return false;
+ }
+
#ifdef IPV6_MULTICAST_LOOP
- setsockopt(device_fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (const void *)&one, sizeof(one));
+ setsockopt(device_fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (const void *)&one, sizeof(one));
#endif
#ifdef IPV6_MULTICAST_HOPS
- setsockopt(device_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (void *)&ttl, sizeof(ttl));
+ setsockopt(device_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (void *)&ttl, sizeof(ttl));
#endif
- } break;
+ }
+ break;
#endif
-
- default:
- logger(LOG_ERR, "Multicast for address family %x unsupported", ai->ai_family);
- closesocket(device_fd);
- free(host);
- return false;
+
+ default:
+ logger(LOG_ERR, "Multicast for address family %x unsupported", ai->ai_family);
+ closesocket(device_fd);
+ free(host);
+ return false;
}
free(host);
free(device);
free(iface);
- if(ai)
+ if(ai) {
freeaddrinfo(ai);
+ }
}
static bool read_packet(vpn_packet_t *packet) {
if((lenin = recv(device_fd, (void *)packet->data, MTU, 0)) <= 0) {
logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
- device, strerror(errno));
+ device, strerror(errno));
return false;
}
device_total_in += packet->len;
ifdebug(TRAFFIC) logger(LOG_DEBUG, "Read packet of %d bytes from %s", packet->len,
- &