id
int64
4
16.3M
file_name
stringlengths
3
68
file_path
stringlengths
14
181
content
stringlengths
39
9.06M
size
int64
39
9.06M
language
stringclasses
1 value
extension
stringclasses
2 values
total_lines
int64
1
711k
avg_line_length
float64
3.18
138
max_line_length
int64
10
140
alphanum_fraction
float64
0.02
0.93
repo_name
stringlengths
7
69
repo_stars
int64
2
61.6k
repo_forks
int64
12
7.81k
repo_open_issues
int64
0
1.13k
repo_license
stringclasses
10 values
repo_extraction_date
stringclasses
657 values
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
1 class
exact_duplicates_redpajama
bool
1 class
exact_duplicates_githubcode
bool
2 classes
near_duplicates_stackv2
bool
1 class
near_duplicates_stackv1
bool
1 class
near_duplicates_redpajama
bool
1 class
near_duplicates_githubcode
bool
2 classes
16,062,472
pidfile.c
cleech_open-isns/pidfile.c
/* * write pidfile * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <unistd.h> #include <libisns/util.h> static void __update_pidfile(int fd) { char pidbuf[32]; snprintf(pidbuf, sizeof(pidbuf), "%u\n", getpid()); if (write(fd, pidbuf, strlen(pidbuf)) < 0) isns_fatal("Error writing pid file: %m\n"); close(fd); } static pid_t __read_pidfile(const char *filename) { char pidbuf[32]; FILE *fp; pid_t pid = -1; fp = fopen(filename, "r"); if (fp != NULL) { if (fgets(pidbuf, sizeof(pidbuf), fp)) pid = strtoul(pidbuf, NULL, 0); fclose(fp); } return pid; } void isns_write_pidfile(const char *filename) { int fd; pid_t pid; fd = open(filename, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd >= 0) { __update_pidfile(fd); return; } if (errno != EEXIST) isns_fatal("Error creating pid file %s: %m\n", filename); /* If the pid file is stale, remove it. * Not really needed in real life, but * highly convenient for debugging :) */ if ((pid = __read_pidfile(filename)) > 0 && kill(pid, 0) < 0 && errno == ESRCH) { isns_debug_general( "Removing stale PID file %s\n", filename); unlink(filename); } /* Try again */ fd = open(filename, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd < 0) isns_fatal("PID file exists; another daemon " "seems to be running\n"); __update_pidfile(fd); } void isns_update_pidfile(const char *filename) { int fd; fd = open(filename, O_WRONLY); if (fd < 0) { isns_fatal("Error opening pid file %s: %m\n", filename); } __update_pidfile(fd); } void isns_remove_pidfile(const char *filename) { unlink(filename); }
1,730
C
.c
82
18.865854
56
0.666667
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,475
objects.c
cleech_open-isns/objects.c
/* * iSNS object model * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include <libisns/isns.h> #include "objects.h" #include <libisns/source.h> #include "vendor.h" #include <libisns/attrs.h> #include <libisns/util.h> /* For relationship stuff - should go */ #include "db.h" static isns_object_template_t * isns_object_templates[] = { &isns_entity_template, &isns_portal_template, &isns_iscsi_node_template, &isns_fc_port_template, &isns_fc_node_template, &isns_iscsi_pg_template, &isns_dd_template, &isns_ddset_template, /* vendor-specific templates */ &isns_policy_template, NULL }; /* * Quick lookup of (key) tag to template */ #define MAX_QUICK_TAG 2100 static isns_object_template_t * isns_object_template_key_map[MAX_QUICK_TAG]; static isns_object_template_t * isns_object_template_any_map[MAX_QUICK_TAG]; static isns_object_template_t * isns_object_template_idx_map[MAX_QUICK_TAG]; static int isns_object_maps_inizialized = 0; static void __isns_object_maps_init(void) { isns_object_template_t *tmpl; uint32_t i, j, tag; isns_object_maps_inizialized = 1; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { if (tmpl->iot_vendor_specific) continue; tag = tmpl->iot_keys[0]; isns_assert(tag < MAX_QUICK_TAG); isns_object_template_key_map[tag] = tmpl; for (j = 0; j < tmpl->iot_num_attrs; ++j) { tag = tmpl->iot_attrs[j]; isns_assert(tag < MAX_QUICK_TAG); isns_object_template_any_map[tag] = tmpl; } if ((tag = tmpl->iot_index) != 0) isns_object_template_idx_map[tag] = tmpl; } } static void isns_object_maps_init(void) { if (!isns_object_maps_inizialized) __isns_object_maps_init(); } /* * Based on a given key attribute, find the corresponding * object type. */ isns_object_template_t * isns_object_template_find(uint32_t key_tag) { isns_object_template_t *tmpl; unsigned int i; isns_object_maps_init(); if (key_tag < MAX_QUICK_TAG) return isns_object_template_key_map[key_tag]; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { if (tmpl->iot_keys[0] == key_tag) return tmpl; } return NULL; } /* * Given a set of attributes, find the corresponding * object type. * Any attributes in the list in *addition to* the keys * attributes are ignored. */ isns_object_template_t * isns_object_template_for_key_attrs(const isns_attr_list_t *attrs) { isns_object_template_t *tmpl; const isns_attr_t *attr; unsigned int i; if (attrs->ial_count == 0) return NULL; attr = attrs->ial_data[0]; tmpl = isns_object_template_find(attr->ia_tag_id); if (tmpl == NULL) return NULL; /* * 5.6.4. * * Some objects are keyed by more than one object key attribute * value. For example, the Portal object is keyed by attribute * tags 16 and 17. When describing an object keyed by more than one * key attribute, every object key attribute of that object MUST be * listed sequentially by tag value in the message before non-key * attributes of that object and key attributes of the next object. * A group of key attributes of this kind is treated as a single * logical key attribute when identifying an object. */ for (i = 1; i < tmpl->iot_num_keys; ++i) { attr = attrs->ial_data[i]; if (attr->ia_tag_id != tmpl->iot_keys[i]) return NULL; } return tmpl; } isns_object_template_t * isns_object_template_for_tag(uint32_t tag) { isns_object_template_t *tmpl; unsigned int i, j; isns_object_maps_init(); if (tag < MAX_QUICK_TAG) return isns_object_template_any_map[tag]; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { for (j = 0; j < tmpl->iot_num_attrs; ++j) { if (tmpl->iot_attrs[j] == tag) return tmpl; } } return NULL; } isns_object_template_t * isns_object_template_for_index_tag(uint32_t tag) { isns_object_maps_init(); if (tag >= MAX_QUICK_TAG) return NULL; return isns_object_template_idx_map[tag]; } isns_object_template_t * isns_object_template_by_name(const char *name) { isns_object_template_t **pp, *tmpl; pp = isns_object_templates; while ((tmpl = *pp++) != NULL) { if (!strcasecmp(tmpl->iot_name, name)) return tmpl; } return NULL; } const char * isns_object_template_name(isns_object_template_t *tmpl) { if (!tmpl) return NULL; return tmpl->iot_name; } /* * Notify any listeners that the object has changed, * and mark it dirty. * dd_or_dds is used for DD_MEMBER_ADDED and * DD_MEMBER_REMOVED events, and refers to the * domain or domain set the object was added to or * removed from. */ void isns_mark_object(isns_object_t *obj, unsigned int how) { obj->ie_flags |= ISNS_OBJECT_DIRTY; obj->ie_mtime = time(NULL); obj->ie_scn_bits |= (1 << how); isns_object_event(obj, 0, NULL); } static void __isns_mark_object(isns_object_t *obj) { obj->ie_flags |= ISNS_OBJECT_DIRTY; obj->ie_mtime = time(NULL); } /* * Create an object given its object template */ isns_object_t * isns_create_object(isns_object_template_t *tmpl, const isns_attr_list_t *attrs, isns_object_t *parent) { isns_object_t *obj; unsigned int i; /* Enforce containment rules. */ if (parent) isns_assert(tmpl->iot_container == parent->ie_template); #ifdef notdef /* This check is somewhat costly: */ if (attrs && tmpl != isns_object_template_for_key_attrs(attrs)) return NULL; #endif obj = isns_calloc(1, sizeof(*obj)); obj->ie_users = 1; obj->ie_template = tmpl; isns_attr_list_init(&obj->ie_attrs); if (parent) isns_object_attach(obj, parent); if (attrs == NULL) { /* Make sure that all key attrs are instantiated * and in sequence. */ for (i = 0; i < tmpl->iot_num_keys; ++i) isns_attr_list_append_nil(&obj->ie_attrs, tmpl->iot_keys[i]); } else { /* We rely on the caller to ensure that * attributes are in proper sequence. */ isns_attr_list_copy(&obj->ie_attrs, attrs); } /* Just mark it dirty, but do not schedule a * SCN event. */ __isns_mark_object(obj); return obj; } /* * Obtain an additional reference on the object */ isns_object_t * isns_object_get(isns_object_t *obj) { if (obj) { isns_assert(obj->ie_users); obj->ie_users++; } return obj; } /* * Release a reference on the object */ void isns_object_release(isns_object_t *obj) { unsigned int i; isns_object_t *child; if (!obj) return; isns_assert(obj->ie_users); if (--(obj)->ie_users != 0) return; /* Must not have any live references to it */ isns_assert(obj->ie_references == 0); /* Must be detached from parent */ isns_assert(obj->ie_container == NULL); /* Release all children. We explicitly clear * ie_container because the destructor * checks for this (in order to catch * refcounting bugs) */ for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; child->ie_container = NULL; } isns_object_list_destroy(&obj->ie_children); isns_attr_list_destroy(&obj->ie_attrs); isns_bitvector_free(obj->ie_membership); isns_free(obj); } /* * Get the topmost container (ie Network Entity) * for the given object */ isns_object_t * isns_object_get_entity(isns_object_t *obj) { if (obj == NULL) return NULL; while (obj->ie_container) obj = obj->ie_container; if (!ISNS_IS_ENTITY(obj)) return NULL; return obj; } int isns_object_contains(const isns_object_t *ancestor, const isns_object_t *descendant) { while (descendant) { if (descendant == ancestor) return 1; descendant = descendant->ie_container; } return 0; } /* * Get all children of the specified type */ void isns_object_get_descendants(const isns_object_t *obj, isns_object_template_t *tmpl, isns_object_list_t *result) { isns_object_t *child; unsigned int i; for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; if (!tmpl || child->ie_template == tmpl) isns_object_list_append(result, child); } } /* * Attach an object to a new container */ int isns_object_attach(isns_object_t *obj, isns_object_t *parent) { isns_assert(obj->ie_container == NULL); if (parent) { /* Copy the owner (ie source) from the parent * object. * Make sure the parent object type is a valid * container for this object. */ if (parent->ie_template != obj->ie_template->iot_container) { isns_error("You are not allowed to add a %s object " "to a %s!\n", obj->ie_template->iot_name, parent->ie_template->iot_name); return 0; } obj->ie_flags = parent->ie_flags & ISNS_OBJECT_PRIVATE; isns_object_list_append(&parent->ie_children, obj); } obj->ie_container = parent; return 1; } int isns_object_is_valid_container(const isns_object_t *container, isns_object_template_t *child_type) { return child_type->iot_container == container->ie_template; } /* * Detach an object from its container */ int isns_object_detach(isns_object_t *obj) { isns_object_t *parent; /* Detach from parent */ if ((parent = obj->ie_container) != NULL) { int removed; obj->ie_container = NULL; removed = isns_object_list_remove( &parent->ie_children, obj); isns_assert(removed != 0); } return 0; } /* * Check the type of an object */ int isns_object_is(const isns_object_t *obj, isns_object_template_t *tmpl) { return obj->ie_template == tmpl; } int isns_object_is_iscsi_node(const isns_object_t *obj) { return ISNS_IS_ISCSI_NODE(obj); } int isns_object_is_fc_port(const isns_object_t *obj) { return ISNS_IS_FC_PORT(obj); } int isns_object_is_fc_node(const isns_object_t *obj) { return ISNS_IS_FC_NODE(obj); } int isns_object_is_portal(const isns_object_t *obj) { return ISNS_IS_PORTAL(obj); } int isns_object_is_pg(const isns_object_t *obj) { return ISNS_IS_PG(obj); } int isns_object_is_policy(const isns_object_t *obj) { return ISNS_IS_POLICY(obj); } /* * Match an object against a list of attributes. */ int isns_object_match(const isns_object_t *obj, const isns_attr_list_t *attrs) { isns_object_template_t *tmpl = obj->ie_template; isns_attr_t *self, *match; unsigned int i, j, from = 0; uint32_t tag; /* Fast path: try to compare in-order */ while (from < attrs->ial_count) { match = attrs->ial_data[from]; self = obj->ie_attrs.ial_data[from]; if (match->ia_tag_id != self->ia_tag_id) goto slow_path; if (!isns_attr_match(self, match)) return 0; from++; } return 1; slow_path: for (i = from; i < attrs->ial_count; ++i) { isns_attr_t *found = NULL; match = attrs->ial_data[i]; /* * 5.6.5.2 * A Message Key with zero-length TLV(s) is scoped to * every object of the type indicated by the zero-length * TLV(s) */ if (match->ia_value.iv_type == &isns_attr_type_nil) { tag = match->ia_tag_id; if (isns_object_attr_valid(tmpl, tag)) continue; return 0; } for (j = from; j < obj->ie_attrs.ial_count; ++j) { self = obj->ie_attrs.ial_data[j]; if (match->ia_tag_id == self->ia_tag_id) { found = self; break; } } if (found == NULL) return 0; if (!isns_attr_match(self, match)) return 0; } return 1; } /* * Find descendant object matching the given key */ isns_object_t * isns_object_find_descendant(isns_object_t *obj, const isns_attr_list_t *keys) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; isns_object_t *found; if (!isns_object_find_descendants(obj, NULL, keys, &list)) return NULL; found = isns_object_get(list.iol_data[0]); isns_object_list_destroy(&list); return found; } int isns_object_find_descendants(isns_object_t *obj, isns_object_template_t *tmpl, const isns_attr_list_t *keys, isns_object_list_t *result) { isns_object_t *child; unsigned int i; if ((tmpl == NULL || tmpl == obj->ie_template) && (keys == NULL || isns_object_match(obj, keys))) isns_object_list_append(result, obj); for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; isns_object_find_descendants(child, tmpl, keys, result); } return result->iol_count; } /* * Return the object's modification time stamp */ time_t isns_object_last_modified(const isns_object_t *obj) { return obj->ie_mtime; } /* * Set the SCN bitmap */ void isns_object_set_scn_mask(isns_object_t *obj, uint32_t bitmap) { obj->ie_scn_mask = bitmap; __isns_mark_object(obj); } /* * Debugging utility: print the object */ void isns_object_print(isns_object_t *obj, isns_print_fn_t *fn) { isns_attr_list_print(&obj->ie_attrs, fn); } /* * Return a string representing the object state */ const char * isns_object_state_string(unsigned int state) { switch (state) { case ISNS_OBJECT_STATE_LARVAL: return "larval"; case ISNS_OBJECT_STATE_MATURE: return "mature"; case ISNS_OBJECT_STATE_LIMBO: return "limbo"; case ISNS_OBJECT_STATE_DEAD: return "dead"; } return "UNKNOWN"; } /* * This is needed when deregistering an object. * Remove all attributes except the key and index attrs. */ void isns_object_prune_attrs(isns_object_t *obj) { isns_object_template_t *tmpl = obj->ie_template; uint32_t tags[16]; unsigned int i; isns_assert(tmpl->iot_num_keys + 1 <= 16); for (i = 0; i < tmpl->iot_num_keys; ++i) tags[i] = tmpl->iot_keys[i]; if (tmpl->iot_index) tags[i++] = tmpl->iot_index; isns_attr_list_prune(&obj->ie_attrs, tags, i); } /* * Convenience functions */ /* * Create a portal object. * For now, always assume TCP. */ isns_object_t * isns_create_portal(const isns_portal_info_t *info, isns_object_t *parent) { isns_object_t *obj; obj = isns_create_object(&isns_portal_template, NULL, parent); isns_portal_to_object(info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, obj); return obj; } /* * Extract all key attrs and place them * in the attribute list. */ int isns_object_extract_keys(const isns_object_t *obj, isns_attr_list_t *list) { isns_object_template_t *tmpl = obj->ie_template; const isns_attr_list_t *src = &obj->ie_attrs; unsigned int i; for (i = 0; i < tmpl->iot_num_keys; ++i) { isns_attr_t *attr; if (!isns_attr_list_get_attr(src, tmpl->iot_keys[i], &attr)) return 0; isns_attr_list_append_attr(list, attr); } return 1; } /* * Extract all attributes we are permitted to overwrite and place them * in the attribute list. */ int isns_object_extract_writable(const isns_object_t *obj, isns_attr_list_t *list) { const isns_attr_list_t *src = &obj->ie_attrs; unsigned int i; for (i = 0; i < src->ial_count; ++i) { isns_attr_t *attr = src->ial_data[i]; if (attr->ia_tag->it_readonly) continue; isns_attr_list_append_attr(list, attr); } return 1; } /* * Extract all attrs and place them * in the attribute list. We copy the attributes * as they appear inside the object; which allows * duplicate attributes (eg inside a discovery domain). */ int isns_object_extract_all(const isns_object_t *obj, isns_attr_list_t *list) { isns_attr_list_append_list(list, &obj->ie_attrs); return 1; } /* * Check if the given object is valid */ int isns_object_attr_valid(isns_object_template_t *tmpl, uint32_t tag) { const uint32_t *attr_tags = tmpl->iot_attrs; unsigned int i; for (i = 0; i < tmpl->iot_num_attrs; ++i) { if (*attr_tags == tag) return 1; ++attr_tags; } return 0; } /* * Set an object attribute */ static int __isns_object_set_attr(isns_object_t *obj, uint32_t tag, const isns_attr_type_t *type, const isns_value_t *value) { const isns_tag_type_t *tag_type; if (!isns_object_attr_valid(obj->ie_template, tag)) return 0; tag_type = isns_tag_type_by_id(tag); if (type != &isns_attr_type_nil && type != tag_type->it_type) { isns_warning("application bug: cannot set attr %s(id=%u, " "type=%s) to a value of type %s\n", tag_type->it_name, tag, tag_type->it_type->it_name, type->it_name); return 0; } isns_attr_list_update_value(&obj->ie_attrs, tag, tag_type, value); /* Timestamp updates should just be written out, but we * do not want to trigger SCN messages and such. */ if (tag != ISNS_TAG_TIMESTAMP) isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); else __isns_mark_object(obj); return 1; } /* * Copy an attribute to the object */ int isns_object_set_attr(isns_object_t *obj, isns_attr_t *attr) { isns_attr_list_t *list = &obj->ie_attrs; uint32_t tag = attr->ia_tag_id; /* If this attribute exists within the object, * and it cannot occur multiple times, replace it. */ if (!attr->ia_tag->it_multiple && isns_attr_list_replace_attr(list, attr)) goto done; /* It doesn't exist; make sure it's a valid * attribute. */ if (!isns_object_attr_valid(obj->ie_template, tag)) return 0; isns_attr_list_append_attr(list, attr); done: isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); return 1; } int isns_object_set_attrlist(isns_object_t *obj, const isns_attr_list_t *attrs) { unsigned int i; for (i = 0; i < attrs->ial_count; ++i) { isns_attr_t *attr = attrs->ial_data[i]; if (!isns_object_set_attr(obj, attr)) return 0; } isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); return 1; } /* * Untyped version of isns_object_set. * Any type checking must be done by the caller; * failure to do so will result in the end of the world. */ int isns_object_set_value(isns_object_t *obj, uint32_t tag, const void *data) { return isns_attr_list_update(&obj->ie_attrs, tag, data); } /* * Typed versions of isns_object_set */ int isns_object_set_nil(isns_object_t *obj, uint32_t tag) { return __isns_object_set_attr(obj, tag, &isns_attr_type_nil, NULL); } int isns_object_set_string(isns_object_t *obj, uint32_t tag, const char *value) { isns_value_t var = ISNS_VALUE_INIT(string, (char *) value); int rc; rc = __isns_object_set_attr(obj, tag, &isns_attr_type_string, &var); return rc; } int isns_object_set_uint32(isns_object_t *obj, uint32_t tag, uint32_t value) { isns_value_t var = ISNS_VALUE_INIT(uint32, value); return __isns_object_set_attr(obj, tag, &isns_attr_type_uint32, &var); } int isns_object_set_uint64(isns_object_t *obj, uint32_t tag, uint64_t value) { isns_value_t var = ISNS_VALUE_INIT(uint64, value); return __isns_object_set_attr(obj, tag, &isns_attr_type_uint64, &var); } int isns_object_set_ipaddr(isns_object_t *obj, uint32_t tag, const struct in6_addr *value) { isns_value_t var = ISNS_VALUE_INIT(ipaddr, *value); return __isns_object_set_attr(obj, tag, &isns_attr_type_ipaddr, &var); } /* * Query object attributes */ int isns_object_get_attr(const isns_object_t *obj, uint32_t tag, isns_attr_t **result) { return isns_attr_list_get_attr(&obj->ie_attrs, tag, result); } int isns_object_get_attrlist(isns_object_t *obj, isns_attr_list_t *result, const isns_attr_list_t *req_attrs) { isns_attr_list_t *attrs = &obj->ie_attrs; isns_attr_t *attr; unsigned int i; if (req_attrs == NULL) { /* Retrieve all attributes */ isns_attr_list_append_list(result, attrs); } else { for (i = 0; i < req_attrs->ial_count; ++i) { uint32_t tag = req_attrs->ial_data[i]->ia_tag_id; if (tag == obj->ie_template->iot_next_index) { /* FIXME: for now, we fake this value. * We need the DB object at this point * to find out what the next unused * index is. */ isns_attr_list_append_uint32(result, tag, 0); } else if (isns_attr_list_get_attr(attrs, tag, &attr)) isns_attr_list_append_attr(result, attr); } } return 1; } int isns_object_get_key_attrs(isns_object_t *obj, isns_attr_list_t *result) { isns_object_template_t *tmpl = obj->ie_template; isns_attr_list_t *attrs = &obj->ie_attrs; isns_attr_t *attr; unsigned int i; for (i = 0; i < tmpl->iot_num_keys; ++i) { uint32_t tag = tmpl->iot_keys[i]; if (!isns_attr_list_get_attr(attrs, tag, &attr)) { isns_error("%s: %s object is missing key attr %u\n", __FUNCTION__, tmpl->iot_name, tag); return 0; } isns_attr_list_append_attr(result, attr); } return 1; } int isns_object_get_string(const isns_object_t *obj, uint32_t tag, const char **result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_STRING(attr)) return 0; *result = attr->ia_value.iv_string; return 1; } int isns_object_get_ipaddr(const isns_object_t *obj, uint32_t tag, struct in6_addr *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_IPADDR(attr)) return 0; *result = attr->ia_value.iv_ipaddr; return 1; } int isns_object_get_uint32(const isns_object_t *obj, uint32_t tag, uint32_t *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_UINT32(attr)) return 0; *result = attr->ia_value.iv_uint32; return 1; } int isns_object_get_uint64(const isns_object_t *obj, uint32_t tag, uint64_t *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_UINT64(attr)) return 0; *result = attr->ia_value.iv_uint64; return 1; } int isns_object_get_opaque(const isns_object_t *obj, uint32_t tag, const void **ptr, size_t *len) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_OPAQUE(attr)) return 0; *ptr = attr->ia_value.iv_opaque.ptr; *len = attr->ia_value.iv_opaque.len; return 1; } int isns_object_delete_attr(isns_object_t *obj, uint32_t tag) { return isns_attr_list_remove_tag(&obj->ie_attrs, tag); } int isns_object_remove_member(isns_object_t *obj, const isns_attr_t *attr, const uint32_t *subordinate_tags) { return isns_attr_list_remove_member(&obj->ie_attrs, attr, subordinate_tags); } /* * Object list functions */ void isns_object_list_init(isns_object_list_t *list) { memset(list, 0, sizeof(*list)); } static inline void __isns_object_list_resize(isns_object_list_t *list, unsigned int count) { unsigned int max; max = (list->iol_count + 15) & ~15; if (count < max) return; count = (count + 15) & ~15; list->iol_data = isns_realloc(list->iol_data, count * sizeof(isns_object_t *)); if (!list->iol_data) isns_fatal("Out of memory!\n"); } void isns_object_list_append(isns_object_list_t *list, isns_object_t *obj) { __isns_object_list_resize(list, list->iol_count + 1); list->iol_data[list->iol_count++] = obj; obj->ie_users++; } void isns_object_list_append_list(isns_object_list_t *dst, const isns_object_list_t *src) { unsigned int i, j; __isns_object_list_resize(dst, dst->iol_count + src->iol_count); j = dst->iol_count; for (i = 0; i < src->iol_count; ++i, ++j) { isns_object_t *obj = src->iol_data[i]; dst->iol_data[j] = obj; obj->ie_users++; } dst->iol_count = j; } int isns_object_list_contains(const isns_object_list_t *list, isns_object_t *obj) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { if (obj == list->iol_data[i]) return 1; } return 0; } isns_object_t * isns_object_list_lookup(const isns_object_list_t *list, isns_object_template_t *tmpl, const isns_attr_list_t *keys) { unsigned int i; if (!tmpl && !keys) return NULL; if (!tmpl && !(tmpl = isns_object_template_for_key_attrs(keys))) return NULL; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template != tmpl) continue; if (keys && !isns_object_match(obj, keys)) continue; obj->ie_users++; return obj; } return NULL; } int isns_object_list_gang_lookup(const isns_object_list_t *list, isns_object_template_t *tmpl, const isns_attr_list_t *keys, isns_object_list_t *result) { unsigned int i; if (!tmpl && !keys) return ISNS_INVALID_QUERY; if (!tmpl && !(tmpl = isns_object_template_for_key_attrs(keys))) return ISNS_INVALID_QUERY; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template != tmpl) continue; if (keys && !isns_object_match(obj, keys)) continue; isns_object_list_append(result, obj); } return ISNS_SUCCESS; } void isns_object_list_destroy(isns_object_list_t *list) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_release(obj); } isns_free(list->iol_data); memset(list, 0, sizeof(*list)); } int isns_object_list_remove(isns_object_list_t *list, isns_object_t *tbr) { unsigned int i, last; last = list->iol_count - 1; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj == tbr) { list->iol_data[i] = list->iol_data[last]; list->iol_count--; isns_object_release(tbr); return 1; } } return 0; } static int isns_object_compare_id(const void *pa, const void *pb) { const isns_object_t *a = *(const isns_object_t **) pa; const isns_object_t *b = *(const isns_object_t **) pb; return (int) a->ie_index - (int) b->ie_index; } void isns_object_list_sort(isns_object_list_t *list) { if (list->iol_count == 0) return; qsort(list->iol_data, list->iol_count, sizeof(void *), isns_object_compare_id); } void isns_object_list_uniq(isns_object_list_t *list) { isns_object_t *prev = NULL, *this; unsigned int i, j; isns_object_list_sort(list); for (i = j = 0; i < list->iol_count; i++) { this = list->iol_data[i]; if (this != prev) list->iol_data[j++] = this; prev = this; } list->iol_count = j; } void isns_object_list_print(const isns_object_list_t *list, isns_print_fn_t *fn) { unsigned int i; if (list->iol_count == 0) { fn("(Object list empty)\n"); return; } for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj; obj = list->iol_data[i]; fn("object[%u] = <%s>\n", i, obj->ie_template->iot_name); isns_object_print(obj, fn); } } /* * Handle object references */ void isns_object_reference_set(isns_object_ref_t *ref, isns_object_t *obj) { isns_object_t *old; if (obj) { isns_assert(obj->ie_users); obj->ie_references++; obj->ie_users++; } if ((old = ref->obj) != NULL) { isns_assert(old->ie_references); old->ie_references--; isns_object_release(old); } ref->obj = obj; } void isns_object_reference_drop(isns_object_ref_t *ref) { isns_object_reference_set(ref, NULL); } /* * Helper function for portal/object conversion */ int isns_portal_from_object(isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, const isns_object_t *obj) { return isns_portal_from_attr_list(portal, addr_tag, port_tag, &obj->ie_attrs); } int isns_portal_to_object(const isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, isns_object_t *obj) { return isns_portal_to_attr_list(portal, addr_tag, port_tag, &obj->ie_attrs); } /* * Portal */ static uint32_t portal_attrs[] = { ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, ISNS_TAG_PORTAL_SYMBOLIC_NAME, ISNS_TAG_ESI_INTERVAL, ISNS_TAG_ESI_PORT, ISNS_TAG_PORTAL_INDEX, ISNS_TAG_SCN_PORT, ISNS_TAG_PORTAL_NEXT_INDEX, ISNS_TAG_PORTAL_SECURITY_BITMAP, ISNS_TAG_PORTAL_ISAKMP_PHASE_1, ISNS_TAG_PORTAL_ISAKMP_PHASE_2, ISNS_TAG_PORTAL_CERTIFICATE, }; static uint32_t portal_key_attrs[] = { ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, }; isns_object_template_t isns_portal_template = { .iot_name = "Portal", .iot_handle = ISNS_OBJECT_TYPE_PORTAL, .iot_attrs = portal_attrs, .iot_num_attrs = array_num_elements(portal_attrs), .iot_keys = portal_key_attrs, .iot_num_keys = array_num_elements(portal_key_attrs), .iot_index = ISNS_TAG_PORTAL_INDEX, .iot_next_index = ISNS_TAG_PORTAL_NEXT_INDEX, .iot_container = &isns_entity_template, };
27,440
C
.c
1,110
22.45045
80
0.690467
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,476
deregister.c
cleech_open-isns/deregister.c
/* * Handle iSNS Device Deregistration * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include "objects.h" #include <libisns/message.h> #include "security.h" #include <libisns/util.h> #include "db.h" extern isns_source_t * isns_server_source; /* * Create a registration, and set the source name */ static isns_simple_t * __isns_create_deregistration(isns_source_t *source, const isns_attr_list_t *attrs) { isns_simple_t *simp; simp = isns_simple_create(ISNS_DEVICE_DEREGISTER, source, NULL); if (simp && attrs) isns_attr_list_copy(&simp->is_operating_attrs, attrs); return simp; } isns_simple_t * isns_create_deregistration(isns_client_t *clnt, const isns_attr_list_t *attrs) { return __isns_create_deregistration(clnt->ic_source, attrs); } /* * Get the next object identified by the operating attrs. */ static int isns_deregistration_get_next_object(isns_db_t *db, struct isns_attr_list_scanner *st, isns_object_list_t *result) { isns_object_t *current; int status; status = isns_attr_list_scanner_next(st); if (status) return status; /* * 5.6.5.4. * Valid Operating Attributes for DevDereg * --------------------------------------- * Entity Identifier * Portal IP-Address & Portal TCP/UDP Port * Portal Index * iSCSI Name * iSCSI Index * FC Port Name WWPN * FC Node Name WWNN * * In other words, deregistration is restricted to Entity, * portal, and node */ if (st->tmpl != &isns_entity_template && st->tmpl != &isns_iscsi_node_template && st->tmpl != &isns_portal_template) return ISNS_INVALID_DEREGISTRATION; /* Only key attrs allowed */ if (st->attrs.ial_count) { /* MS Initiators send the Entity protocol along * with the Entity Identifier. */ isns_debug_protocol("Client included invalid operating attrs " "with %s:\n", st->tmpl->iot_name); isns_attr_list_print(&st->attrs, isns_debug_protocol); /* return ISNS_INVALID_DEREGISTRATION; */ } /* * 5.6.5.4 * Attempted deregistration of non-existing entries SHALL not * be considered an isns_error. */ current = isns_db_lookup(db, st->tmpl, &st->keys); if (current != NULL) { isns_object_list_append(result, current); isns_object_release(current); } return ISNS_SUCCESS; } /* * Extract the list of objects to be deregistered from * the list of operating attributes. */ static int isns_deregistration_get_objects(isns_simple_t *reg, isns_db_t *db, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, NULL, &reg->is_operating_attrs); state.index_acceptable = 1; state.source = reg->is_source; while (state.pos < state.orig_attrs.ial_count) { status = isns_deregistration_get_next_object(db, &state, result); if (status == 0) continue; /* Translate error codes */ if (status == ISNS_NO_SUCH_ENTRY) status = ISNS_SUCCESS; else if (status == ISNS_INVALID_REGISTRATION) status = ISNS_INVALID_DEREGISTRATION; break; } isns_attr_list_scanner_destroy(&state); return status; } /* * Process a deregistration * * Normally, you would expect that a deregistration removes the * object from the database, and that's the end of the story. * Unfortunately, someone added Discovery Domains to the protocol, * requiring _some_ information to survive as long as an object * is referenced by a discovery domain. Specifically, we need to * retain the relationship between key attributes (eg iscsi node * name) and the object index. * * Thus, deregistration consists of the following steps * - the object is removed from the database's global scope, * so that it's no longer visible to DB lookups. * * - the object is detached from its containing Network * Entity. * * - all attributes except the key attr(s) and the index * attribute are removed. */ int isns_process_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *reply = NULL; isns_db_t *db = srv->is_db; int status, dereg_status; unsigned int i; /* Get the objects to deregister */ status = isns_deregistration_get_objects(call, db, &objects); if (status != ISNS_SUCCESS) goto done; /* * 5.6.5.4 * * For messages that change the contents of the iSNS database, * the iSNS server MUST verify that the Source Attribute * identifies either a Control Node or a Storage Node that is * a part of the Network Entity containing the added, deleted, * or modified objects. */ /* * Implementation note: this can be implemented either by * explicitly checking the object's owner in isns_db_remove * (which is what we do right now), or by matching only * those objects that have the right owner anyway. * * The latter sounds like a better choice if the client * uses NIL attributes, because it limits the scope of * the operation; but then the RFC doesn't say whether * this kind of deregistration would be valid at all. */ /* Success: create a new simple message, and * send it in our reply. */ reply = __isns_create_deregistration(srv->is_source, NULL); if (reply == NULL) { status = ISNS_INTERNAL_ERROR; goto done; } dereg_status = ISNS_SUCCESS; for (i = 0; i < objects.iol_count; ++i) { isns_object_t *obj = objects.iol_data[i]; /* Policy: check that the client is permitted * to deregister this object */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, obj, call->is_function)) status = ISNS_SOURCE_UNAUTHORIZED; if (status == ISNS_SUCCESS) status = isns_db_remove(db, obj); if (status != ISNS_SUCCESS) { /* * 5.7.5.4 * * In the event of an error, this response message * contains the appropriate status code as well * as a list of objects from the original DevDereg * message that were not successfully deregistered * from the iSNS database. This list of objects * is contained in the Operating Attributes * of the DevDeregRsp message. Note that an * attempted deregistration of a non-existent * object does not constitute an isns_error, and * non-existent entries SHALL not be returned * in the DevDeregRsp message. */ /* * Implementation: right now this doesn't work * at all, because isns_msg_set_error will * discard the entire message except for the * status word. */ isns_debug_message("Failed to deregister object: %s (0x%04x)\n", isns_strerror(status), status); isns_object_extract_all(obj, &reply->is_operating_attrs); dereg_status = status; continue; } /* * 5.7.5.4 * If all Nodes and Portals associated with a Network * Entity are deregistered, then the Network Entity * SHALL also be removed. * [...] * If both the Portal and iSCSI Storage Node objects * associated with a Portal Group object are removed, * then that Portal Group object SHALL also be removed. * The Portal Group object SHALL remain registered * as long as either of its associated Portal or * iSCSI Storage Node objects remain registered. If a * deleted Storage Node or Portal object is subsequently * re-registered, then a relationship between the re- * registered object and an existing Portal or Storage * Node object registration, indicated by the PG object, * SHALL be restored. */ /* isns_db_remove takes care of removing dead entities, * and dead portal groups. */ } if (status == ISNS_SUCCESS) status = dereg_status; done: isns_object_list_destroy(&objects); *result = reply; return status; }
7,773
C
.c
243
29.135802
92
0.713505
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,477
error.c
cleech_open-isns/error.c
/* * iSNS error strings etc. * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <libisns/isns.h> const char * isns_strerror(enum isns_status status) { switch (status) { case ISNS_SUCCESS: return "Success"; case ISNS_UNKNOWN_ERROR: return "Unknown error"; case ISNS_MESSAGE_FORMAT_ERROR: return "Message format error"; case ISNS_INVALID_REGISTRATION: return "Invalid registration"; case ISNS_INVALID_QUERY: return "Invalid query"; case ISNS_SOURCE_UNKNOWN: return "Source unknown"; case ISNS_SOURCE_ABSENT: return "Source absent"; case ISNS_SOURCE_UNAUTHORIZED: return "Source unauthorized"; case ISNS_NO_SUCH_ENTRY: return "No such entry"; case ISNS_VERSION_NOT_SUPPORTED: return "Version not supported"; case ISNS_INTERNAL_ERROR: return "Internal error"; case ISNS_BUSY: return "Busy"; case ISNS_OPTION_NOT_UNDERSTOOD: return "Option not understood"; case ISNS_INVALID_UPDATE: return "Invalid update"; case ISNS_MESSAGE_NOT_SUPPORTED: return "Message not supported"; case ISNS_SCN_EVENT_REJECTED: return "SCN event rejected"; case ISNS_SCN_REGISTRATION_REJECTED: return "SCN registration rejected"; case ISNS_ATTRIBUTE_NOT_IMPLEMENTED: return "Attribute not implemented"; case ISNS_FC_DOMAIN_ID_NOT_AVAILABLE: return "FC domain id not available"; case ISNS_FC_DOMAIN_ID_NOT_ALLOCATED: return "FC domain id not allocated"; case ISNS_ESI_NOT_AVAILABLE: return "ESI not available"; case ISNS_INVALID_DEREGISTRATION: return "Invalid deregistration"; case ISNS_REGISTRATION_FEATURE_NOT_SUPPORTED: return "Registration feature not supported"; default: break; } return "Unknown iSNS status code"; }
1,695
C
.c
61
25.42623
56
0.771166
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,478
getnext.c
cleech_open-isns/getnext.c
/* * Handle iSNS DevGetNext * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include <libisns/message.h> #include "security.h" #include "objects.h" #include "db.h" #include <libisns/util.h> /* * Create a GetNext query, and set the source name */ static isns_simple_t * __isns_create_getnext(isns_source_t *source, const isns_attr_list_t *key, const isns_attr_list_t *scope) { isns_simple_t *simp; simp = isns_simple_create(ISNS_DEVICE_GET_NEXT, source, key); if (simp && scope) isns_attr_list_copy(&simp->is_operating_attrs, scope); return simp; } isns_simple_t * isns_create_getnext(isns_client_t *clnt, isns_object_template_t *tmpl, const isns_attr_list_t *scope) { isns_simple_t *simp; unsigned int i; simp = __isns_create_getnext(clnt->ic_source, NULL, scope); if (simp == NULL) return NULL; for (i = 0; i < tmpl->iot_num_keys; ++i) { isns_attr_list_append_nil(&simp->is_message_attrs, tmpl->iot_keys[i]); } return simp; } isns_simple_t * isns_create_getnext_followup(isns_client_t *clnt, const isns_simple_t *resp, const isns_attr_list_t *scope) { return __isns_create_getnext(clnt->ic_source, &resp->is_message_attrs, scope); } /* * Get the list of objects matching this query */ static int isns_getnext_get_object(isns_simple_t *qry, isns_db_t *db, isns_object_t **result) { isns_scope_t *scope; isns_attr_list_t *keys = &qry->is_message_attrs, match; isns_object_template_t *tmpl; unsigned int i; /* * 5.6.5.3. * The Message Key Attribute may be an Entity Identifier (EID), * iSCSI Name, iSCSI Index, Portal IP Address and TCP/UDP Port, * Portal Index, PG Index, FC Node Name WWNN, or FC Port Name * WWPN. * * Implementer's comment: In other words, it must be the * key attr(s) of a specific object type, or an index attribute. */ if ((tmpl = isns_object_template_for_key_attrs(keys)) != NULL) { if (keys->ial_count != tmpl->iot_num_keys) return ISNS_INVALID_QUERY; } else if (keys->ial_count == 1) { isns_attr_t *attr = keys->ial_data[0]; tmpl = isns_object_template_for_index_tag(attr->ia_tag_id); } if (tmpl == NULL) return ISNS_INVALID_QUERY; /* Verify whether the client is permitted to retrieve * objects of the given type. */ if (!isns_policy_validate_object_type(qry->is_policy, tmpl, qry->is_function)) return ISNS_SOURCE_UNAUTHORIZED; /* * 5.6.5.3. * The Operating Attributes can be used to specify the scope * of the DevGetNext request, and to specify the attributes of * the next object, which are to be returned in the DevGetNext * response message. All Operating Attributes MUST be attributes * of the object type identified by the Message Key. */ match = qry->is_operating_attrs; for (i = 0; i < match.ial_count; ++i) { isns_attr_t *attr = match.ial_data[i]; if (tmpl != isns_object_template_for_tag(attr->ia_tag_id)) return ISNS_INVALID_QUERY; } /* * 5.6.5.3. * Non-zero-length TLV attributes in the Operating Attributes * are used to scope the DevGetNext message. * [...] * Zero-length TLV attributes MUST be listed after non-zero-length * attributes in the Operating Attributes of the DevGetNext * request message. */ for (i = 0; i < match.ial_count; ++i) { if (ISNS_ATTR_IS_NIL(match.ial_data[i])) { match.ial_count = i; break; } } /* Get the scope for the originating node. */ scope = isns_scope_for_call(db, qry); *result = isns_scope_get_next(scope, tmpl, keys, &match); isns_scope_release(scope); if (*result == NULL) return ISNS_NO_SUCH_ENTRY; return ISNS_SUCCESS; } /* * Create a Query Response */ static isns_simple_t * isns_create_getnext_response(isns_source_t *source, const isns_simple_t *qry, isns_object_t *obj) { const isns_attr_list_t *req_attrs = NULL; isns_attr_list_t requested; isns_simple_t *resp; unsigned int i; resp = __isns_create_getnext(source, NULL, NULL); /* * 5.7.5.3. Device Get Next Response (DevGetNextRsp) * The Message Key Attribute field returns the object keys * for the next object after the Message Key Attribute in the * original DevGetNext message. * * Implementer's note: slightly convoluted English here. * I *think* this means the key attributes of the object * we matched. */ if (!isns_object_get_key_attrs(obj, &resp->is_message_attrs)) return NULL; /* * 5.7.5.3. * The Operating Attribute field returns the Operating Attributes * of the next object as requested in the original DevGetNext * message. The values of the Operating Attributes are those * associated with the object identified by the Message Key * Attribute field of the DevGetNextRsp message. * * Implementer's note: the RFC doesn't say clearly what to * do when the list of operating attributes does not * contain any NIL TLVs. Let's default to the same * behavior as elsewhere, and return all attributes * in this case. */ req_attrs = &qry->is_operating_attrs; for (i = 0; i < req_attrs->ial_count; ++i) { if (ISNS_ATTR_IS_NIL(req_attrs->ial_data[i])) break; } requested.ial_count = req_attrs->ial_count - i; requested.ial_data = req_attrs->ial_data + i; if (requested.ial_count) req_attrs = &requested; else req_attrs = NULL; isns_object_get_attrlist(obj, &resp->is_operating_attrs, req_attrs); return resp; } /* * Process a GetNext request */ int isns_process_getnext(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_object_t *obj = NULL; isns_db_t *db = srv->is_db; int status; /* Get the next object */ status = isns_getnext_get_object(call, db, &obj); if (status != ISNS_SUCCESS) goto done; /* If it's a virtual object, rebuild it */ if (obj->ie_rebuild) obj->ie_rebuild(obj, srv->is_db); /* Success: create a new simple message, and * send it in our reply. */ reply = isns_create_getnext_response(srv->is_source, call, obj); if (reply == NULL) status = ISNS_INTERNAL_ERROR; done: if (obj) isns_object_release(obj); *result = reply; return status; } /* * Parse the object in a getnext response */ int isns_getnext_response_get_object(isns_simple_t *qry, isns_object_t **result) { isns_object_template_t *tmpl; tmpl = isns_object_template_for_key_attrs(&qry->is_operating_attrs); if (tmpl == NULL) { isns_error("Cannot determine object type in GetNext response\n"); return ISNS_ATTRIBUTE_NOT_IMPLEMENTED; } *result = isns_create_object(tmpl, &qry->is_operating_attrs, NULL); return ISNS_SUCCESS; }
6,652
C
.c
226
27
85
0.707382
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,479
buffer.c
cleech_open-isns/buffer.c
/* * Buffer handling functions * * Copyright (C) 2003-2007, Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <err.h> #include <unistd.h> #include <netinet/in.h> /* ntohl&htonl */ #include <libisns/buffer.h> #include <libisns/util.h> /* htonll */ static int buf_drain(buf_t *bp); buf_t * buf_alloc(size_t size) { buf_t *bp; bp = isns_calloc(1, sizeof(*bp)); buf_init_empty(bp, size); return bp; } buf_t * buf_open(const char *filename, int flags) { static const unsigned int buflen = 4096; buf_t *bp; int oerr; if (!(bp = isns_calloc(1, sizeof(*bp) + buflen))) return NULL; buf_init(bp, (bp + 1), buflen); switch (flags & O_ACCMODE) { case O_RDONLY: bp->write_mode = 0; break; case O_WRONLY: bp->write_mode = 1; break; default: errno = EINVAL; goto failed; } if (!filename || !strcmp(filename, "-")) { bp->fd = dup(bp->write_mode? 1 : 0); } else { bp->fd = open(filename, flags, 0666); } if (bp->fd < 0) goto failed; return bp; failed: oerr = errno; isns_free(bp); errno = oerr; return NULL; } buf_t * buf_dup(const buf_t *src) { buf_t *bp; bp = buf_alloc(src->max_size); buf_put(bp, src->base + src->head, src->tail - src->head); bp->addr = src->addr; bp->addrlen = src->addrlen; return bp; } void buf_close(buf_t *bp) { if (bp->write_mode) buf_drain(bp); if (bp->fd >= 0) close(bp->fd); bp->fd = -1; isns_free(bp); } void buf_free(buf_t *bp) { if (!bp) return; if (bp->allocated) isns_free(bp->base); isns_free(bp); } void buf_list_free(buf_t *bp) { buf_t *next; while (bp) { next = bp->next; buf_free(bp); bp = next; } } void buf_init(buf_t *bp, void *mem, size_t len) { memset(bp, 0, sizeof(*bp)); bp->base = (unsigned char *) mem; bp->size = len; bp->max_size = len; bp->fd = -1; } void buf_init_empty(buf_t *bp, size_t len) { memset(bp, 0, sizeof(*bp)); bp->max_size = len; bp->fd = -1; } void buf_set(buf_t *bp, void *mem, size_t len) { buf_init(bp, mem, len); bp->tail = len; } void buf_clear(buf_t *bp) { bp->head = bp->tail = 0; } static int buf_fill(buf_t *bp) { int n; if (bp->head || bp->tail) buf_compact(bp); if (bp->write_mode || bp->fd < 0) return 0; n = read(bp->fd, bp->base + bp->tail, buf_tailroom(bp)); if (n < 0) { warn("read error"); return 0; } bp->tail += n; return n; } int buf_drain(buf_t *bp) { int n; if (!bp->write_mode || bp->fd < 0) return 0; n = write(bp->fd, bp->base + bp->head, buf_avail(bp)); if (n < 0) { warn("write error"); return 0; } bp->head += n; return n; } int __buf_resize(buf_t *bp, size_t new_size) { void *new_base; if (new_size > bp->max_size) return 0; isns_assert(bp->allocated || bp->base == NULL); new_size = (new_size + 127) & ~127; if (new_size > bp->max_size) new_size = bp->max_size; new_base = isns_realloc(bp->base, new_size); if (new_base == NULL) return 0; bp->base = new_base; bp->size = new_size; bp->allocated = 1; return new_size; } buf_t * buf_split(buf_t **to_split, size_t size) { buf_t *old = *to_split, *new; size_t avail; avail = buf_avail(old); if (size > avail) return NULL; if (size == avail) { *to_split = NULL; return old; } new = buf_alloc(size); buf_put(new, buf_head(old), size); buf_pull(old, size); return new; } int buf_seek(buf_t *bp, off_t offset) { if (bp->write_mode && !buf_drain(bp)) return 0; if (lseek(bp->fd, offset, SEEK_SET) < 0) { warn("cannot seek to offset %ld", (long) offset); return 0; } return 1; } int buf_get(buf_t *bp, void *mem, size_t len) { caddr_t dst = (caddr_t) mem; unsigned int total = len, copy; while (len) { if ((copy = buf_avail(bp)) > len) copy = len; if (copy == 0) { if (!buf_fill(bp)) return 0; continue; } if (dst) { memcpy(dst, bp->base + bp->head, copy); dst += copy; } bp->head += copy; len -= copy; } return total; } int buf_get32(buf_t *bp, uint32_t *vp) { if (!buf_get(bp, vp, 4)) return 0; *vp = ntohl(*vp); return 1; } int buf_get64(buf_t *bp, uint64_t *vp) { if (!buf_get(bp, vp, 8)) return 0; *vp = ntohll(*vp); return 1; } int buf_gets(buf_t *bp, char *stringbuf, size_t size) { uint32_t len, copy; if (size == 0) return 0; if (!buf_get32(bp, &len)) return 0; if ((copy = len) >= size) copy = size - 1; if (!buf_get(bp, stringbuf, copy)) return 0; stringbuf[copy] = '\0'; /* Pull remaining bytes */ if (copy != len && !buf_pull(bp, len - copy)) return 0; return copy + 1; } int buf_put(buf_t *bp, const void *mem, size_t len) { caddr_t src = (caddr_t) mem; unsigned int total = len, copy; while (len) { if ((copy = bp->size - bp->tail) > len) copy = len; if (copy == 0) { if (buf_drain(bp)) { buf_compact(bp); continue; } if (__buf_resize(bp, bp->tail + len)) { buf_compact(bp); continue; } return 0; } if (src) { memcpy(bp->base + bp->tail, src, copy); src += copy; } bp->tail += copy; len -= copy; } return total; } int buf_putc(buf_t *bp, int byte) { unsigned char c = byte; return buf_put(bp, &c, 1); } int buf_put32(buf_t *bp, uint32_t val) { val = htonl(val); if (!buf_put(bp, &val, 4)) return 0; return 1; } int buf_put64(buf_t *bp, uint64_t val) { val = htonll(val); return buf_put(bp, &val, 8); } int buf_puts(buf_t *bp, const char *sp) { uint32_t len = 0; if (sp) len = strlen(sp); return buf_put32(bp, len) && buf_put(bp, sp, len); } void buf_compact(buf_t *bp) { unsigned int count; if (bp->head == 0) return; count = bp->tail - bp->head; memmove(bp->base, bp->base + bp->head, count); bp->tail -= bp->head; bp->head = 0; } void buf_list_append(buf_t **list, buf_t *bp) { bp->next = NULL; while (*list) list = &(*list)->next; *list = bp; } int buf_truncate(buf_t *bp, size_t len) { if (bp->head + len > bp->tail) return 0; bp->tail = bp->head + len; return 1; }
5,975
C
.c
337
15.581602
62
0.616739
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,480
db-policy.c
cleech_open-isns/db-policy.c
/* * Use database as policy and keystore * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <sys/stat.h> #include <string.h> #include <unistd.h> #include "config.h" #ifdef WITH_SECURITY #include <openssl/pem.h> #include <openssl/err.h> #endif #include <libisns/isns.h> #include "security.h" #include "objects.h" #include "vendor.h" #include <libisns/util.h> /* * DB keystore */ typedef struct isns_db_keystore isns_db_keystore_t; struct isns_db_keystore { isns_keystore_t sd_base; isns_db_t * sd_db; isns_object_t * sd_control; }; /* * Look up the policy object given its SPI */ isns_object_t * __isns_db_keystore_lookup(isns_db_keystore_t *store, const char *name, size_t namelen) { isns_attr_list_t keys = ISNS_ATTR_LIST_INIT; char namebuf[256]; if (namelen >= sizeof(namebuf)) return NULL; memcpy(namebuf, name, namelen); namebuf[namelen] = '\0'; isns_attr_list_append_string(&keys, OPENISNS_TAG_POLICY_SPI, namebuf); return isns_db_lookup(store->sd_db, NULL, &keys); } /* * Load a DSA key from the DB store */ static EVP_PKEY * __isns_db_keystore_find(isns_keystore_t *store_base, const char *name, size_t namelen) { #ifdef WITH_SECURITY isns_db_keystore_t *store = (isns_db_keystore_t *) store_base; isns_object_t *obj; const void *key_data; size_t key_size; obj = __isns_db_keystore_lookup(store, name, namelen); if (obj == NULL) return NULL; if (!isns_object_get_opaque(obj, OPENISNS_TAG_POLICY_KEY, &key_data, &key_size)) return NULL; return isns_dsa_decode_public(key_data, key_size); #else return NULL; #endif } /* * Retrieve policy from database */ static void __isns_db_keystore_copy_policy_string(isns_object_t *obj, uint32_t tag, char **var) { const char *value; if (!isns_object_get_string(obj, tag, &value)) return; isns_assign_string(var, value); } static void __isns_db_keystore_copy_policy_strings(isns_object_t *obj, uint32_t tag, struct string_array *array) { isns_attr_list_t *attrs = &obj->ie_attrs; unsigned int i; for (i = 0; i < attrs->ial_count; ++i) { isns_attr_t *attr = attrs->ial_data[i]; if (attr->ia_tag_id != tag || !ISNS_ATTR_IS_STRING(attr)) continue; isns_string_array_append(array, attr->ia_value.iv_string); } } static isns_policy_t * __isns_db_keystore_get_policy(isns_keystore_t *store_base, const char *name, size_t namelen) { isns_db_keystore_t *store = (isns_db_keystore_t *) store_base; isns_policy_t *policy; isns_object_t *obj; uint32_t intval; obj = __isns_db_keystore_lookup(store, name, namelen); if (obj == NULL) return NULL; policy = __isns_policy_alloc(name, namelen); /* retrieve policy bits from object */ #if 0 __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_SOURCE_NAME, &policy->ip_source); #endif __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_ENTITY, &policy->ip_entity); __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_DEFAULT_DD, &policy->ip_dd_default); __isns_db_keystore_copy_policy_strings(obj, OPENISNS_TAG_POLICY_NODE_NAME, &policy->ip_node_names); if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_OBJECT_TYPE, &intval)) policy->ip_object_types = intval; if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_NODE_TYPE, &intval)) policy->ip_node_types = intval; if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_FUNCTIONS, &intval)) policy->ip_functions = intval; return policy; } void __isns_db_keystore_change_notify(const isns_db_event_t *ev, void *handle) { isns_db_keystore_t *store = handle; isns_object_t *obj = ev->ie_object; if (isns_object_get_entity(obj) == store->sd_control) { isns_debug_auth("DB keystore: policy data was modified\n"); store->sd_base.ic_generation++; } } isns_keystore_t * isns_create_db_keystore(isns_db_t *db) { isns_db_keystore_t *store; isns_object_t *entity; isns_debug_auth("Creating DB keystore\n"); if (!(entity = isns_db_get_control(db))) { isns_error("Could not create control entity in database\n"); return NULL; } isns_debug_auth("Control entity is 0x%08x\n", entity->ie_index); store = isns_calloc(1, sizeof(*store)); store->sd_base.ic_name = "database key store"; store->sd_base.ic_find = __isns_db_keystore_find; store->sd_base.ic_get_policy = __isns_db_keystore_get_policy; store->sd_control = entity; store->sd_db = db; isns_register_callback(__isns_db_keystore_change_notify, store); return (isns_keystore_t *) store; }
4,495
C
.c
159
26.106918
75
0.715413
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,481
security.c
cleech_open-isns/security.c
/* * Security functions for iSNS * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include "config.h" #include <libisns/isns.h> #include "security.h" #include <libisns/source.h> #include <libisns/util.h> #ifdef WITH_SECURITY #if OPENSSL_VERSION_NUMBER < 0x10100000L #define EVP_PKEY_base_id(o) ((o)->type) #endif /* * Allocate a security peer */ static isns_principal_t * isns_create_principal(const char *spi, size_t spi_len, EVP_PKEY *pk) { char keydesc[32]; isns_principal_t *peer; peer = isns_calloc(1, sizeof(*peer)); peer->is_users = 1; if (spi) { peer->is_name = isns_malloc(spi_len + 1); memcpy(peer->is_name, spi, spi_len); peer->is_name[spi_len] = '\0'; peer->is_namelen = spi_len; } peer->is_key = pk; if (pk) { const char *algo; switch (EVP_PKEY_base_id(pk)) { case EVP_PKEY_DSA: algo = "DSA"; break; case EVP_PKEY_RSA: algo = "RSA"; break; default: algo = "unknown"; break; } snprintf(keydesc, sizeof(keydesc), " (%s/%u)", algo, EVP_PKEY_bits(pk)); } isns_debug_auth("Created security principal \"%s\"%s\n", peer->is_name, keydesc); return peer; } static void isns_principal_set_key(isns_principal_t *princ, EVP_PKEY *key) { if (princ->is_key == key) return; if (princ->is_key) EVP_PKEY_free(princ->is_key); princ->is_key = key; } void isns_principal_free(isns_principal_t *peer) { if (!peer) return; isns_assert(peer->is_users); if (--(peer->is_users)) return; if (peer->is_name) isns_free(peer->is_name); if (peer->is_key) EVP_PKEY_free(peer->is_key); isns_policy_release(peer->is_policy); isns_free(peer); } /* * Set the principal's name */ void isns_principal_set_name(isns_principal_t *princ, const char *spi) { isns_assign_string(&princ->is_name, spi); isns_debug_auth("Setting principal name to \"%s\"\n", spi); } const char * isns_principal_name(const isns_principal_t *princ) { return princ->is_name; } /* * Cache policy in the principal object. */ void isns_principal_set_policy(isns_principal_t *princ, isns_policy_t *policy) { if (policy) policy->ip_users++; isns_policy_release(princ->is_policy); princ->is_policy = policy; } /* * Key management functions for a security context. */ isns_principal_t * isns_security_load_privkey(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; isns_debug_auth("Loading private %s key from %s\n", ctx->is_name, filename); if (!ctx->is_load_private) return NULL; if (!(pkey = ctx->is_load_private(ctx, filename))) { isns_error("Unable to load private %s key from %s\n", ctx->is_name, filename); return NULL; } return isns_create_principal(NULL, 0, pkey); } isns_principal_t * isns_security_load_pubkey(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; isns_debug_auth("Loading public %s key from %s\n", ctx->is_name, filename); if (!ctx->is_load_public) return NULL; if (!(pkey = ctx->is_load_public(ctx, filename))) { isns_error("Unable to load public %s key from %s\n", ctx->is_name, filename); return NULL; } return isns_create_principal(NULL, 0, pkey); } void isns_security_set_identity(isns_security_t *ctx, isns_principal_t *princ) { if (princ) princ->is_users++; if (ctx->is_self) isns_principal_free(ctx->is_self); ctx->is_self = princ; } void isns_add_principal(isns_security_t *ctx, isns_principal_t *princ) { if (princ) princ->is_users++; princ->is_next = ctx->is_peers; ctx->is_peers = princ; } isns_principal_t * isns_get_principal(isns_security_t *ctx, const char *spi, size_t spi_len) { isns_principal_t *princ; isns_policy_t *policy; isns_keystore_t *ks; EVP_PKEY *pk; ks = ctx->is_peer_keys; for (princ = ctx->is_peers; princ; princ = princ->is_next) { /* In a client socket, we set the (expected) * public key of the peer through * isns_security_set_peer_key, which will * just put it on the peers list. * This key usually has no name. */ if (princ->is_name == NULL) { princ->is_users++; return princ; } if (spi_len == princ->is_namelen && !memcmp(princ->is_name, spi, spi_len)) { /* Check whether the cached key and policy * might be stale. */ if (ks && ks->ic_generation != princ->is_generation) { pk = ks->ic_find(ks, spi, spi_len); if (pk == NULL) { isns_debug_auth("Unable to refresh key " "for principal %.*s - probably deleted\n", spi_len, spi); return NULL; } isns_debug_auth("Refresh key for principal %.*s\n", spi_len, spi); isns_principal_set_key(princ, pk); princ->is_users++; goto refresh_policy; } princ->is_users++; return princ; } } if ((ks = ctx->is_peer_keys) == NULL) return NULL; if (!(pk = ks->ic_find(ks, spi, spi_len))) return NULL; princ = isns_create_principal(spi, spi_len, pk); /* Add it to the list */ princ->is_next = ctx->is_peers; ctx->is_peers = princ; princ->is_users++; /* Bind the policy for this peer */ refresh_policy: if (!ks->ic_get_policy || !(policy = ks->ic_get_policy(ks, spi, spi_len))) policy = isns_policy_default(spi, spi_len); /* If no entity is set, use the SPI */ if (policy->ip_entity == NULL) isns_assign_string(&policy->ip_entity, policy->ip_name); /* If the list of permitted node names is empty, * default to the standard pattern derived from * the reversed entity name */ if (policy->ip_node_names.count == 0) { char *pattern; pattern = isns_build_source_pattern(policy->ip_entity); if (pattern != NULL) isns_string_array_append(&policy->ip_node_names, pattern); isns_free(pattern); } isns_principal_set_policy(princ, policy); isns_policy_release(policy); /* Remember the keystore generation number */ princ->is_generation = ks->ic_generation; return princ; } /* * Create a keystore for a security context. * Key stores let the server side retrieve the * keys associated with a given SPI. * * For now, we support just simple key stores, * but this could be extended to support * URLs such as ldaps://ldap.example.com */ isns_keystore_t * isns_create_keystore(const char *spec) { if (*spec != '/') return NULL; return isns_create_simple_keystore(spec); } /* * Attach the keystore to the security context */ void isns_security_set_keystore(isns_security_t *ctx, isns_keystore_t *ks) { ctx->is_peer_keys = ks; } /* * Check that the client supplied time stamp is within a * certain window. */ static int isns_security_check_timestamp(isns_security_t *ctx, isns_principal_t *peer, uint64_t timestamp) { int64_t delta; /* The time stamp must not be earlier than timestamp_jitter * before the last message received. */ if (peer->is_timestamp) { delta = timestamp - peer->is_timestamp; if (delta < -(int64_t) ctx->is_timestamp_jitter) return 0; } /* We allow the client's clock to diverge from ours, within * certain limits. */ if (ctx->is_replay_window != 0) { time_t now = time(NULL); delta = timestamp - now; if (delta < 0) delta = -delta; if (delta > ctx->is_replay_window) return 0; } peer->is_timestamp = timestamp; return 1; } int isns_security_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *bp, struct isns_authblk *auth) { if (!ctx->is_sign) { isns_debug_auth("isns_security_sign: auth context without " "sign handler.\n"); return 0; } if (!ctx->is_sign(ctx, peer, bp, auth)) { isns_debug_auth("Failed to sign message, spi=%s\n", peer->is_name); return 0; } return 1; } int isns_security_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *bp, struct isns_authblk *auth) { if (!isns_security_check_timestamp(ctx, peer, auth->iab_timestamp)) { isns_debug_auth("Possible replay attack (bad timestamp) " "from spi=%s\n", peer->is_name); return 0; } if (!ctx->is_verify) { isns_debug_auth("isns_security_verify: auth context without " "verify handler.\n"); return 0; } if (!ctx->is_verify(ctx, peer, bp, auth)) { isns_debug_auth("Failed to authenticate message, spi=%s\n", peer->is_name); return 0; } return 1; } /* * Initialize security services. */ int isns_security_init(void) { if (!isns_config.ic_dsa.param_file) { isns_error("No DSA parameter file - please edit configuration\n"); return 0; } if (!isns_dsa_init_params(isns_config.ic_dsa.param_file)) return 0; if (!isns_config.ic_auth_key_file) { isns_error("No AuthKey specified; please edit configuration\n"); return 0; } if (!isns_dsa_init_key(isns_config.ic_auth_key_file)) return 0; return 1; } #else /* WITH_SECURITY */ static void isns_no_security(void) { static int complain = 0; if (complain++ < 5) isns_error("iSNS authentication disabled in this build\n"); } int isns_security_init(void) { isns_no_security(); return 0; } isns_keystore_t * isns_create_keystore(const char *spec) { isns_no_security(); return NULL; } void isns_security_set_keystore(isns_security_t *ctx, isns_keystore_t *ks) { isns_no_security(); } void isns_principal_free(isns_principal_t *peer) { } isns_principal_t * isns_get_principal(isns_security_t *ctx, const char *spi, size_t spi_len) { return NULL; } const char * isns_principal_name(const isns_principal_t *princ) { return NULL; } #endif /* WITH_SECURITY */
9,320
C
.c
376
22.398936
73
0.68983
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,482
storage-node.c
cleech_open-isns/storage-node.c
/* * iSNS object model - storage node * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include <libisns/isns.h> #include "objects.h" #include <libisns/util.h> isns_object_t * isns_create_storage_node(const char *name, uint32_t type, isns_object_t *parent) { isns_object_t *obj; if (parent && !ISNS_IS_ENTITY(parent)) { isns_warning("Invalid container type \"%s\" for storage node: " "should be \"%s\"\n", parent->ie_template->iot_name, isns_entity_template.iot_name); return NULL; } obj = isns_create_object(&isns_iscsi_node_template, NULL, parent); isns_object_set_string(obj, ISNS_TAG_ISCSI_NAME, name); isns_object_set_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, type); return obj; } isns_object_t * isns_create_storage_node2(const isns_source_t *source, uint32_t type, isns_object_t *parent) { isns_attr_t *name_attr; isns_object_t *obj; if (parent && !ISNS_IS_ENTITY(parent)) { isns_warning("Invalid container type \"%s\" for storage node: " "should be \"%s\"\n", parent->ie_template->iot_name, isns_entity_template.iot_name); return NULL; } if ((name_attr = isns_source_attr(source)) == NULL) { isns_warning("No source attribute\n"); return NULL; } if (name_attr->ia_tag_id == ISNS_TAG_ISCSI_NAME) { obj = isns_create_object(&isns_iscsi_node_template, NULL, parent); isns_attr_list_update_attr(&obj->ie_attrs, name_attr); isns_object_set_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, type); } else { /* No iFCP yet, sorry */ isns_warning("%s: source tag type %u not supported\n", __FUNCTION__); return NULL; } return obj; } isns_object_t * isns_create_iscsi_initiator(const char *name, isns_object_t *parent) { return isns_create_storage_node(name, 1 << ISNS_ISCSI_NODE_TYPE_INITIATOR, parent); } isns_object_t * isns_create_iscsi_target(const char *name, isns_object_t *parent) { return isns_create_storage_node(name, 1 << ISNS_ISCSI_NODE_TYPE_TARGET, parent); } const char * isns_storage_node_name(const isns_object_t *node) { const isns_attr_t *attr; if (node->ie_attrs.ial_count == 0) return NULL; attr = node->ie_attrs.ial_data[0]; if (attr->ia_value.iv_type != &isns_attr_type_string) return NULL; switch (attr->ia_tag_id) { case ISNS_TAG_ISCSI_NAME: case ISNS_TAG_FC_PORT_NAME_WWPN: return attr->ia_value.iv_string; } return 0; } isns_attr_t * isns_storage_node_key_attr(const isns_object_t *node) { if (node->ie_attrs.ial_count == 0) return NULL; return node->ie_attrs.ial_data[0]; } static uint32_t iscsi_node_attrs[] = { ISNS_TAG_ISCSI_NAME, ISNS_TAG_ISCSI_NODE_TYPE, ISNS_TAG_ISCSI_ALIAS, ISNS_TAG_ISCSI_SCN_BITMAP, ISNS_TAG_ISCSI_NODE_INDEX, ISNS_TAG_WWNN_TOKEN, ISNS_TAG_ISCSI_AUTHMETHOD, /* RFC 4171 lists a "iSCSI node certificate" * as an option attribute of an iSCSI * storage node, but doesn't define it anywhere * in the spec. */ }; static uint32_t iscsi_node_key_attrs[] = { ISNS_TAG_ISCSI_NAME, }; isns_object_template_t isns_iscsi_node_template = { .iot_name = "iSCSI Storage Node", .iot_handle = ISNS_OBJECT_TYPE_NODE, .iot_attrs = iscsi_node_attrs, .iot_num_attrs = array_num_elements(iscsi_node_attrs), .iot_keys = iscsi_node_key_attrs, .iot_num_keys = array_num_elements(iscsi_node_key_attrs), .iot_index = ISNS_TAG_ISCSI_NODE_INDEX, .iot_next_index = ISNS_TAG_ISCSI_NODE_NEXT_INDEX, .iot_container = &isns_entity_template, }; static uint32_t fc_port_attrs[] = { ISNS_TAG_FC_PORT_NAME_WWPN, ISNS_TAG_PORT_ID, ISNS_TAG_FC_PORT_TYPE, ISNS_TAG_SYMBOLIC_PORT_NAME, ISNS_TAG_FABRIC_PORT_NAME, ISNS_TAG_HARD_ADDRESS, ISNS_TAG_PORT_IP_ADDRESS, ISNS_TAG_CLASS_OF_SERVICE, ISNS_TAG_FC4_TYPES, ISNS_TAG_FC4_DESCRIPTOR, ISNS_TAG_FC4_FEATURES, ISNS_TAG_IFCP_SCN_BITMAP, ISNS_TAG_PORT_ROLE, ISNS_TAG_PERMANENT_PORT_NAME, }; static uint32_t fc_port_key_attrs[] = { ISNS_TAG_FC_PORT_NAME_WWPN, }; isns_object_template_t isns_fc_port_template = { .iot_name = "iFCP Port", .iot_handle = ISNS_OBJECT_TYPE_FC_PORT, .iot_attrs = fc_port_attrs, .iot_num_attrs = array_num_elements(fc_port_attrs), .iot_keys = fc_port_key_attrs, .iot_num_keys = array_num_elements(fc_port_key_attrs), .iot_container = &isns_entity_template, }; static uint32_t fc_node_attrs[] = { ISNS_TAG_FC_NODE_NAME_WWNN, ISNS_TAG_SYMBOLIC_NODE_NAME, ISNS_TAG_NODE_IP_ADDRESS, ISNS_TAG_NODE_IPA, ISNS_TAG_PROXY_ISCSI_NAME, }; static uint32_t fc_node_key_attrs[] = { ISNS_TAG_FC_NODE_NAME_WWNN, }; isns_object_template_t isns_fc_node_template = { .iot_name = "iFCP Device Node", .iot_handle = ISNS_OBJECT_TYPE_FC_NODE, .iot_attrs = fc_node_attrs, .iot_num_attrs = array_num_elements(fc_node_attrs), .iot_keys = fc_node_key_attrs, .iot_num_keys = array_num_elements(fc_node_key_attrs), .iot_container = &isns_fc_port_template, };
4,884
C
.c
175
25.668571
68
0.71273
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,483
local.c
cleech_open-isns/local.c
/* * Local iSNS registration * * Copyright (C) 2007 Olaf Kirch <[email protected]> * * The way isnsdd communicates with local services (initiator, * target) is via a file and signals. That sounds rather * awkward, but it's a lot simpler to add to these services * than another socket based communication mechanism I guess. * * The file format is simple: * <object> owner=<owner> * <object> owner=<owner> * ... * * <owner> identifies the service owning these entries. * This is a service name, such as iscsid, tgtd, isnsdd, * optionally followed by a colon and a PID. This allows * removal of all entries created by one service in one go. * * <object> is the description of one iSNS object, using the * syntax used by all other open-isns apps. */ #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <limits.h> #include "config.h" #include <libisns/isns.h> #include "security.h" #include <libisns/util.h> #include <libisns/isns-proto.h> #include <libisns/paths.h> #include <libisns/attrs.h> #include <libisns/util.h> typedef int __isns_local_registry_cb_fn_t(const char *line, int argc, char **argv, void *user_data); /* * Build the owner=<svcname>:<pid> tag */ static const char * __isns_local_registry_make_owner(const char *svcname, pid_t pid) { static char owner[128]; if (pid == 0) { return svcname; } snprintf(owner, sizeof(owner), "%s:%u", svcname, pid); return owner; } /* * Read the registry file, match each entry against the given owner=<foo> tag, * and invoke the callback function. * This is used for both reading the registry, and rewriting it. */ static int __isns_local_registry_read(const char *match_owner, __isns_local_registry_cb_fn_t handle_matching, __isns_local_registry_cb_fn_t handle_nonmatching, void *user_data) { const char *filename = isns_config.ic_local_registry_file; char *line, *copy = NULL; FILE *fp; int rv = 0, owner_len; if (!(fp = fopen(filename, "r"))) { if (errno == ENOENT) { isns_debug_state("Unable to open %s: %m\n", filename); return 1; } isns_error("Unable to open %s: %m\n", filename); return 0; } owner_len = match_owner? strlen(match_owner) : 0; while ((line = parser_get_next_line(fp)) != NULL) { __isns_local_registry_cb_fn_t *cb; char *argv[256], *owner; int argc = 0; isns_assign_string(&copy, line); argc = isns_attr_list_split(line, argv, 255); if (argc <= 0) continue; /* Last attr should be owner */ if (strncasecmp(argv[argc-1], "owner=", 6)) { isns_error("%s: syntax error (missing owner field)\n", filename); goto out; } owner = argv[argc-1] + 6; if (!strncasecmp(owner, match_owner, owner_len) && (owner[owner_len] == '\0' || owner[owner_len] == ':')) cb = handle_matching; else cb = handle_nonmatching; if (cb && !cb(copy, argc, argv, user_data)) goto out; } rv = 1; out: free(copy); fclose(fp); return rv; } /* * Open and lock the registry file for writing. Returns an * open stream and the name of the lock file. * Follow up with _finish_write when done. */ static FILE * __isns_local_registry_open_write(char **lock_name) { char *lock_path; size_t capacity; FILE *fp; int fd, retry; capacity = strlen(isns_config.ic_local_registry_file) + 6; lock_path = isns_malloc(capacity); if (!lock_path) isns_fatal("Out of memory"); snprintf(lock_path, capacity, "%s.lock", isns_config.ic_local_registry_file); for (retry = 0; retry < 5; ++retry) { fd = open(lock_path, O_RDWR|O_CREAT|O_EXCL, 0644); if (fd >= 0) break; if (errno != EEXIST) { isns_error("Unable to create %s: %m\n", lock_path); isns_free(lock_path); return NULL; } isns_error("Cannot lock %s - retry in 1 sec\n", isns_config.ic_local_registry_file); sleep(1); } if (!(fp = fdopen(fd, "w"))) { isns_error("fdopen failed: %m\n"); close(fd); isns_free(lock_path); return NULL; } isns_free(*lock_name); *lock_name = lock_path; return fp; } /* * We're done with (re)writing the registry. Commit the changes, * or discard them. * Also frees the lock_name returned by registry_open_write. */ static int __isns_local_registry_finish_write(FILE *fp, char *lock_name, int commit) { int rv = 1; fclose(fp); if (!commit) { if (unlink(lock_name)) isns_error("Failed to unlink %s: %m\n", lock_name); } else if (rename(lock_name, isns_config.ic_local_registry_file)) { isns_error("Failed to rename %s to %s: %m\n", lock_name, isns_config.ic_local_registry_file); rv = 0; } free(lock_name); return rv; } /* * Get the entity name for this service */ static char * __isns_local_registry_entity_name(const char *owner) { static char namebuf[1024]; snprintf(namebuf, sizeof(namebuf), "%s:%s", isns_config.ic_entity_name, owner); return namebuf; } /* * Callback function which builds an iSNS object from the * list of attr=tag values. */ static int __isns_local_registry_load_object(const char *line, int argc, char **argv, void *user_data) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_object_list_t *list = user_data; isns_object_t *obj, *entity = NULL; for (; argc > 0; --argc) { char *attr = argv[argc-1]; if (!strncasecmp(attr, "owner=", 6)) { char *eid = __isns_local_registry_entity_name(attr + 6); ISNS_QUICK_ATTR_LIST_DECLARE(key_attrs, ISNS_TAG_ENTITY_IDENTIFIER, string, eid); if (entity) { isns_error("Duplicate owner entry in registry\n"); continue; } isns_attr_print(&key_attrs.iqa_attr, isns_print_stdout); entity = isns_object_list_lookup(list, &isns_entity_template, &key_attrs.iqa_list); if (entity != NULL) continue; isns_debug_state("Creating fake entity %s\n", eid); entity = isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, eid); isns_object_list_append(list, entity); } else { break; } } isns_attr_list_parser_init(&state, NULL); if (!isns_parse_attrs(argc, argv, &attrs, &state)) { isns_error("Unable to parse attrs\n"); isns_attr_list_destroy(&attrs); return 0; } obj = isns_create_object(isns_attr_list_parser_context(&state), &attrs, entity); isns_attr_list_destroy(&attrs); if (obj == NULL) { isns_error("Unable to create object\n"); return 0; } isns_object_list_append(list, obj); return 1; } /* * Callback function that simply writes out the line as-is */ static int __isns_local_registry_rewrite_object(const char *line, int argc, char **argv, void *user_data) { FILE *ofp = user_data; fprintf(ofp, "%s\n", line); return 1; } /* * Load all objects owner by a specific service from the local registry. * If the svcname starts with "!", all entries except those matching this * particular service are returned. */ int isns_local_registry_load(const char *svcname, pid_t pid, isns_object_list_t *objs) { __isns_local_registry_cb_fn_t *if_matching = NULL, *if_nonmatching = NULL; if (svcname == NULL) { isns_error("%s: no svcname given\n", __FUNCTION__); return 0; } if (*svcname == '!') { if_nonmatching = __isns_local_registry_load_object; svcname++; } else { if_matching = __isns_local_registry_load_object; } return __isns_local_registry_read( __isns_local_registry_make_owner(svcname, pid), if_matching, if_nonmatching, objs); } /* * Store the given list of objects in the registry. * This replaces all objects previously registered by this service. */ int isns_local_registry_store(const char *svcname, pid_t pid, const isns_object_list_t *objs) { const char *owner = __isns_local_registry_make_owner(svcname, pid); char *lock_name = NULL; FILE *ofp; if (!(ofp = __isns_local_registry_open_write(&lock_name))) { isns_error("%s: could not open registry for writing\n", __FUNCTION__); return 0; } /* First, purge all entries previously belonging to this owner */ if (!__isns_local_registry_read(owner, NULL, __isns_local_registry_rewrite_object, ofp)) goto failed; if (objs) { unsigned int i; for (i = 0; i < objs->iol_count; ++i) { isns_object_t *obj = objs->iol_data[i]; char *argv[256]; int i, argc; argc = isns_print_attrs(obj, argv, 256); for (i = 0; i < argc; ++i) fprintf(ofp, "%s ", argv[i]); fprintf(ofp, "owner=%s\n", owner); } } return __isns_local_registry_finish_write(ofp, lock_name, 1); failed: isns_error("%s: error rewriting registry file\n", __FUNCTION__); __isns_local_registry_finish_write(ofp, lock_name, 0); return 0; } /* * Purge the local registry of all objects owned by the * given service. */ int isns_local_registry_purge(const char *svcname, pid_t pid) { return isns_local_registry_store(svcname, pid, NULL); }
8,810
C
.c
315
25.463492
89
0.686671
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,484
util.c
cleech_open-isns/util.c
/* * util.c * * Misc utility functions * * Copyright (C) 2006, 2007 Olaf Kirch <[email protected]> */ #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <err.h> #include <errno.h> #include <libisns/util.h> unsigned long parse_size(const char *arg) { unsigned long mult = 1, ret; char *s; ret = strtol(arg, &s, 0); switch (*s++) { case 'g': case 'G': mult = 1024 * 1024 * 1024; break; case 'm': case 'M': mult = 1024 * 1024; break; case 'k': case 'K': mult = 1024; break; case '\0': return ret; default: bad: err(1, "parse_size: unknown unit in \"%s\"", arg); } if (*s != '\0') goto bad; return mult * ret; } char * print_size(unsigned long size) { static char unit[] = "-kMG"; static char buffer[64]; unsigned int power = 0; while (size && !(size % 1024) && power < sizeof(unit)) { size /= 1024; power++; } if (!power) { snprintf(buffer, sizeof(buffer), "%lu", size); } else { snprintf(buffer, sizeof(buffer), "%lu%c", size, unit[power]); } return buffer; } unsigned int parse_count(const char *arg) { unsigned long ret; char *s; ret = strtoul(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"", arg); return ret; } int parse_int(const char *arg) { long ret; char *s; ret = strtol(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"", arg); return ret; } long long parse_longlong(const char *arg) { long long ret; char *s; ret = strtoll(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"", arg); return ret; } double parse_double(const char *arg) { double ret; char *s; ret = strtod(arg, &s); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"", arg); return ret; } unsigned int parse_timeout(const char *arg) { unsigned int v, ret = 0; char *s; do { v = strtoul(arg, &s, 10); switch (*s) { case '\0': ret += v; break; case 'd': v *= 24; case 'h': v *= 60; case 'm': v *= 60; case 's': ret += v; ++s; break; default: errx(1, "parse_timeout: unexpected character in \"%s\"\n", arg); } arg = s; } while (*arg); return ret; } void isns_string_array_append(struct string_array *array, const char *val) { if (!(array->count % 32)) { array->list = isns_realloc(array->list, (array->count + 32) * sizeof(val)); } array->list[array->count++] = val? isns_strdup(val) : NULL; } void isns_string_array_destroy(struct string_array *array) { unsigned int i; for (i = 0; i < array->count; ++i) isns_free(array->list[i]); isns_free(array->list); memset(array, 0, sizeof(*array)); } void isns_assign_string(char **var, const char *val) { char *s = NULL; if (val && !(s = isns_strdup(val))) errx(1, "out of memory"); if (*var) isns_free(*var); *var = s; } /* * Recursively create a directory */ int isns_mkdir_recursive(const char *pathname) { const char *orig_pathname = pathname; char *squirrel[64]; char *copy = NULL, *s; int ns = 0; if (!pathname || !strcmp(pathname, ".")) return 0; while (1) { if (mkdir(pathname, 0755) >= 0) { if (ns == 0) break; *squirrel[--ns] = '/'; continue; } if (errno == EEXIST) goto good; if (errno != ENOENT) goto bad; if (copy == NULL) { copy = isns_strdup(pathname); pathname = copy; } s = strrchr(copy, '/'); while (s > copy && s[-1] == '/') --s; *s = '\0'; isns_assert(ns < 64); squirrel[ns++] = s; if (s == copy) goto bad; } good: if (copy) isns_free(copy); errno = 0; return 0; bad: if (copy) isns_free(copy); perror(orig_pathname); return -1; } /* * This one differs from POSIX dirname; it does not * modify its argument */ const char * isns_dirname(const char *pathname) { static char buffer[4096]; char *s; strcpy(buffer, pathname); if ((s = strrchr(buffer, '/')) != NULL) { *s = '\0'; return buffer; } return "."; }
4,084
C
.c
218
15.866972
69
0.598534
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,486
socket.h
cleech_open-isns/socket.h
/* * iSNS network code * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_SOCKET_H #define ISNS_SOCKET_H #include <libisns/isns.h> #include <libisns/buffer.h> #include <libisns/message.h> struct isns_partial_msg { isns_message_t imp_base; uint32_t imp_flags; uint32_t imp_first_seq; uint32_t imp_last_seq; unsigned int imp_pdu_count; unsigned int imp_msg_size; buf_t * imp_chain; struct_cmsgcred_t imp_credbuf; }; #define imp_users imp_base.im_users #define imp_list imp_base.im_list #define imp_xid imp_base.im_xid #define imp_header imp_base.im_header #define imp_addr imp_base.im_addr #define imp_addrlen imp_base.im_addrlen #define imp_header imp_base.im_header #define imp_payload imp_base.im_payload #define imp_security imp_base.im_security #define imp_creds imp_base.im_creds enum { ISNS_SOCK_LISTENING, ISNS_SOCK_CONNECTING, ISNS_SOCK_IDLE, ISNS_SOCK_FAILED, ISNS_SOCK_DISCONNECTED, ISNS_SOCK_DEAD, }; /* Helper class */ struct __isns_socket_addr { struct sockaddr_storage addr; socklen_t addrlen; struct addrinfo * list; }; struct isns_socket { isns_list_t is_list; int is_desc; int is_type; unsigned int is_client : 1, is_autoclose : 1, is_disconnect_fatal : 1, is_report_failure : 1, is_destroy : 1; unsigned int is_users; int is_poll_mask; int is_state; isns_security_t * is_security; struct __isns_socket_addr is_src, is_dst; unsigned int is_retrans_timeout; /* If we're past this time, is_timeout() is called. */ struct timeval is_deadline; buf_t * is_recv_buf; buf_t * is_xmit_buf; size_t is_queue_size; isns_message_queue_t is_partial; isns_message_queue_t is_complete; isns_message_queue_t is_pending; void (*is_poll_in)(isns_socket_t *); void (*is_poll_out)(isns_socket_t *); void (*is_poll_hup)(isns_socket_t *); void (*is_poll_err)(isns_socket_t *); void (*is_timeout)(isns_socket_t *); void (*is_error)(isns_socket_t *, int); }; extern int isns_socket_submit(isns_socket_t *, isns_message_t *, long); #endif /* ISNS_SOCKET_H */
2,114
C
.c
78
24.974359
56
0.710253
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,487
security.h
cleech_open-isns/security.h
/* * Security functions for iSNS * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_SECURITY_H #define ISNS_SECURITY_H #ifdef WITH_SECURITY #include <openssl/evp.h> #else typedef void EVP_PKEY; #endif #include <libisns/buffer.h> #include <libisns/util.h> /* * Security context */ struct isns_security { const char * is_name; unsigned int is_type; unsigned int is_replay_window; unsigned int is_timestamp_jitter; /* Our own key and identity */ isns_principal_t * is_self; /* Key store for peer keys */ isns_principal_t * is_peers; isns_keystore_t * is_peer_keys; EVP_PKEY * (*is_load_private)(isns_security_t *ctx, const char *filename); EVP_PKEY * (*is_load_public)(isns_security_t *ctx, const char *filename); int (*is_verify)(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *); int (*is_sign)(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *); }; struct isns_principal { unsigned int is_users; isns_principal_t * is_next; char * is_name; unsigned int is_namelen; EVP_PKEY * is_key; unsigned int is_generation; uint64_t is_timestamp; isns_policy_t * is_policy; }; struct isns_policy { unsigned int ip_users; unsigned int ip_gen; /* SPI */ char * ip_name; /* The client's entity name. This is usually * the FQDN. */ char * ip_entity; /* Bitmap of functions the client is * permitted to call. */ unsigned int ip_functions; /* Bitmap of object types the client is * permitted to register (uses iot_handle) */ unsigned int ip_object_types; /* Names of storage nodes the client is permitted * to register. */ struct string_array ip_node_names; /* Storage node types the client is permitted * to read or modify. */ unsigned int ip_node_types; /* The client's default Discovery Domain */ char * ip_dd_default; }; #define ISNS_PERMISSION_READ 0x01 #define ISNS_PERMISSION_WRITE 0x02 #define ISNS_ACCESS(t, p) ((p) << (2 * (t))) #define ISNS_ACCESS_W(t) ISNS_ACCESS(t, ISNS_PERMISSION_WRITE) #define ISNS_ACCESS_R(t) ISNS_ACCESS(t, ISNS_PERMISSION_READ) #define ISNS_ACCESS_RW(t) ISNS_ACCESS(t, ISNS_PERMISSION_READ|ISNS_PERMISSION_WRITE) #define ISNS_DEFAULT_OBJECT_ACCESS \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_ENTITY) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_NODE) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_FC_PORT) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_FC_NODE) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_PORTAL) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_PG) | \ ISNS_ACCESS_R(ISNS_OBJECT_TYPE_DD) struct isns_keystore { char * ic_name; unsigned int ic_generation; EVP_PKEY * (*ic_find)(isns_keystore_t *, const char *, size_t); isns_policy_t * (*ic_get_policy)(isns_keystore_t *, const char *, size_t); }; extern isns_principal_t * isns_get_principal(isns_security_t *, const char *, size_t); extern int isns_security_sign(isns_security_t *, isns_principal_t *, buf_t *, struct isns_authblk *); extern int isns_security_verify(isns_security_t *, isns_principal_t *, buf_t *, struct isns_authblk *); extern int isns_security_protected_entity(isns_security_t *, const char *); extern isns_keystore_t * isns_create_keystore(const char *); extern isns_keystore_t * isns_create_simple_keystore(const char *); extern isns_keystore_t * isns_create_db_keystore(isns_db_t *); extern int isns_authblock_encode(buf_t *, const struct isns_authblk *); extern int isns_authblock_decode(buf_t *, struct isns_authblk *); extern isns_policy_t * __isns_policy_alloc(const char *, size_t); extern isns_policy_t * isns_policy_bind(const isns_message_t *); extern void isns_principal_set_policy(isns_principal_t *, isns_policy_t *); extern void isns_policy_release(isns_policy_t *); extern int isns_policy_validate_function(const isns_policy_t *, const isns_message_t *); extern int isns_policy_validate_source(const isns_policy_t *, const isns_source_t *); extern int isns_policy_validate_object_access(const isns_policy_t *, const isns_source_t *, const isns_object_t *, unsigned int); extern int isns_policy_validate_object_update(const isns_policy_t *, const isns_source_t *, const isns_object_t *, const isns_attr_list_t *, unsigned int); extern int isns_policy_validate_object_creation(const isns_policy_t *, const isns_source_t *, isns_object_template_t *, const isns_attr_list_t *, const isns_attr_list_t *, unsigned int); extern int isns_policy_validate_object_type(const isns_policy_t *, isns_object_template_t *, unsigned int function); extern int isns_policy_validate_node_type(const isns_policy_t *, uint32_t type); extern int isns_policy_validate_entity(const isns_policy_t *, const char *); extern int isns_policy_validate_node_name(const isns_policy_t *, const char *); extern int isns_policy_validate_scn_bitmap(const isns_policy_t *, uint32_t); extern const char * isns_policy_default_entity(const isns_policy_t *); extern isns_policy_t * isns_policy_default(const char *, size_t); extern isns_policy_t * isns_policy_server(void); extern EVP_PKEY * isns_dsa_decode_public(const void *, size_t); extern int isns_dsa_encode_public(EVP_PKEY *, void **, size_t *); extern EVP_PKEY * isns_dsa_load_public(const char *); extern int isns_dsa_store_private(const char *, EVP_PKEY *); extern EVP_PKEY * isns_dsa_generate_key(void); extern int isns_dsa_init_params(const char *); extern int isns_dsa_init_key(const char *); #endif /* ISNS_SECURITY_H */
5,676
C
.c
159
32.836478
84
0.704297
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,488
domain.c
cleech_open-isns/domain.c
/* * iSNS object model - discovery domain specific code * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include <libisns/isns.h> #include "objects.h" #include <libisns/util.h> static int __isns_default_dd_rebuild(isns_object_t *obj, isns_db_t *db) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; unsigned int i; isns_object_prune_attrs(obj); isns_db_get_domainless(db, &isns_iscsi_node_template, &list); for (i = 0; i < list.iol_count; ++i) { isns_object_t *node = list.iol_data[i]; const char *name; uint32_t type; if (!isns_object_get_uint32(node, ISNS_TAG_ISCSI_NODE_TYPE, &type)) continue; if (type & ISNS_ISCSI_CONTROL_MASK) continue; if (!isns_object_get_string(node, ISNS_TAG_ISCSI_NAME, &name)) continue; isns_object_set_string(obj, ISNS_TAG_DD_MEMBER_ISCSI_NAME, name); } return ISNS_SUCCESS; } /* * Create the default domain */ isns_object_t * isns_create_default_domain(void) { isns_object_t *obj; obj = isns_create_object(&isns_dd_template, NULL, NULL); if (!obj) return NULL; isns_object_set_uint32(obj, ISNS_TAG_DD_ID, 0); obj->ie_rebuild = __isns_default_dd_rebuild; return obj; } /* * Check object type */ int isns_object_is_dd(const isns_object_t *obj) { return ISNS_IS_DD(obj); } int isns_object_is_ddset(const isns_object_t *obj) { return ISNS_IS_DDSET(obj); } /* * Keep track of DD membership through a bit vector */ int isns_object_mark_membership(isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) obj->ie_membership = isns_bitvector_alloc(); return isns_bitvector_set_bit(obj->ie_membership, id); } int isns_object_test_membership(const isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) return 0; return isns_bitvector_test_bit(obj->ie_membership, id); } int isns_object_clear_membership(isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) return 0; return isns_bitvector_clear_bit(obj->ie_membership, id); } /* * Check whether the two objects share a discovery domain, * and if so, return the DD_ID. * Returns -1 otherwise. */ int isns_object_test_visibility(const isns_object_t *a, const isns_object_t *b) { /* The admin can tell isnsd to put all nodes which are *not* * in any discovery domain, into the so-called default domain */ if (isns_config.ic_use_default_domain && a->ie_template == b->ie_template && isns_bitvector_is_empty(a->ie_membership) && isns_bitvector_is_empty(b->ie_membership)) return 1; return isns_bitvector_intersect(a->ie_membership, b->ie_membership, NULL) >= 0; } /* * Return all visible nodes and portals */ static int __isns_object_vis_callback(uint32_t dd_id, void *ptr) { isns_object_list_t *list = ptr; /* Get all active members */ isns_dd_get_members(dd_id, list, 1); return 0; } void isns_object_get_visible(const isns_object_t *obj, isns_db_t *db, isns_object_list_t *result) { if (isns_bitvector_is_empty(obj->ie_membership)) { /* Get all other nodes not in any DD */ if (isns_config.ic_use_default_domain) isns_db_get_domainless(db, obj->ie_template, result); return; } isns_bitvector_foreach(obj->ie_membership, __isns_object_vis_callback, result); } /* * Object templates */ static uint32_t discovery_domain_attrs[] = { ISNS_TAG_DD_ID, ISNS_TAG_DD_SYMBOLIC_NAME, ISNS_TAG_DD_MEMBER_ISCSI_INDEX, ISNS_TAG_DD_MEMBER_ISCSI_NAME, ISNS_TAG_DD_MEMBER_FC_PORT_NAME, ISNS_TAG_DD_MEMBER_PORTAL_INDEX, ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR, ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT, ISNS_TAG_DD_FEATURES, }; static uint32_t discovery_domain_key_attrs[] = { ISNS_TAG_DD_ID, }; isns_object_template_t isns_dd_template = { .iot_name = "Discovery Domain", .iot_handle = ISNS_OBJECT_TYPE_DD, .iot_attrs = discovery_domain_attrs, .iot_num_attrs = array_num_elements(discovery_domain_attrs), .iot_keys = discovery_domain_key_attrs, .iot_num_keys = array_num_elements(discovery_domain_key_attrs), .iot_index = ISNS_TAG_DD_ID, .iot_next_index = ISNS_TAG_DD_NEXT_ID, }; static uint32_t dd_set_attrs[] = { ISNS_TAG_DD_SET_ID, ISNS_TAG_DD_SET_SYMBOLIC_NAME, ISNS_TAG_DD_SET_STATUS, }; static uint32_t dd_set_key_attrs[] = { ISNS_TAG_DD_SET_ID, }; isns_object_template_t isns_ddset_template = { .iot_name = "Discovery Domain Set", .iot_handle = ISNS_OBJECT_TYPE_DDSET, .iot_attrs = dd_set_attrs, .iot_num_attrs = array_num_elements(dd_set_attrs), .iot_keys = dd_set_key_attrs, .iot_num_keys = array_num_elements(dd_set_key_attrs), .iot_next_index = ISNS_TAG_DD_SET_NEXT_ID, };
4,619
C
.c
178
23.803371
80
0.716844
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,489
scn.c
cleech_open-isns/scn.c
/* * Handle SCN registration/deregistration/events * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include "objects.h" #include <libisns/message.h> #include "security.h" #include <libisns/util.h> #include "db.h" typedef struct isns_scn isns_scn_t; typedef struct isns_scn_funnel isns_scn_funnel_t; struct isns_scn { isns_scn_t * scn_next; char * scn_name; isns_object_t * scn_entity; isns_object_t * scn_owner; isns_attr_t * scn_attr; isns_simple_t * scn_message; isns_simple_t * scn_pending; unsigned int scn_retries; time_t scn_timeout; uint16_t scn_xid; time_t scn_last_update; isns_scn_funnel_t * scn_current_funnel; isns_scn_funnel_t * scn_funnels; }; struct isns_scn_funnel { isns_scn_funnel_t * scn_next; isns_portal_info_t scn_portal; isns_socket_t * scn_socket; unsigned int scn_bad; }; static isns_server_t * isns_scn_server = NULL; static isns_scn_t * isns_scn_list; static isns_scn_t * isns_scn_create_scn(isns_object_t *, uint32_t, isns_db_t *); static void isns_scn_delete_scn(isns_object_t *); static isns_scn_t * isns_scn_setup(isns_scn_t *, isns_object_t *); static void isns_scn_callback(const isns_db_event_t *, void *); static void isns_scn_free(isns_scn_t *); /* * Initialize SCN machinery */ void isns_scn_init(isns_server_t *srv) { isns_db_t *db = srv->is_db; isns_object_list_t nodes = ISNS_OBJECT_LIST_INIT; isns_scn_t **tail; unsigned int i; isns_scn_server = srv; isns_register_callback(isns_scn_callback, db); /* Recover SCN state. */ isns_db_gang_lookup(db, &isns_iscsi_node_template, NULL, &nodes); #ifdef notyet isns_db_gang_lookup(db, &isns_fc_node_template, NULL, &nodes); #endif tail = &isns_scn_list; for (i = 0; i < nodes.iol_count; ++i) { isns_object_t *node = nodes.iol_data[i]; isns_scn_t *scn; if (!node->ie_scn_mask) continue; isns_debug_state("Recovering SCN state for %s %u\n", node->ie_template->iot_name, node->ie_index); scn = isns_scn_setup(NULL, node); if (scn) { *tail = scn; tail = &scn->scn_next; } } } /* * Support for SCNRegister calls */ isns_simple_t * isns_create_scn_registration2(isns_client_t *clnt, unsigned int bitmap, isns_source_t *source) { isns_simple_t *call; if (!source) source = clnt->ic_source; call = isns_simple_create(ISNS_SCN_REGISTER, source, NULL); if (call) { isns_attr_list_append_attr(&call->is_message_attrs, isns_source_attr(source)); isns_attr_list_append_uint32(&call->is_operating_attrs, ISNS_TAG_ISCSI_SCN_BITMAP, bitmap); } return call; } isns_simple_t * isns_create_scn_registration(isns_client_t *clnt, unsigned int bitmap) { return isns_create_scn_registration2(clnt, bitmap, clnt->ic_source); } /* * Create an SCN */ isns_simple_t * isns_create_scn(isns_source_t *source, isns_attr_t *nodeattr, isns_attr_t *tsattr) { isns_simple_t *call; call = isns_simple_create(ISNS_STATE_CHANGE_NOTIFICATION, source, NULL); if (call && nodeattr) isns_attr_list_append_attr(&call->is_message_attrs, nodeattr); if (call && tsattr) isns_attr_list_append_attr(&call->is_message_attrs, tsattr); return call; } static void isns_scn_add_event(isns_simple_t *call, uint32_t scn_bits, const isns_object_t *obj, const isns_object_t *dd) { isns_attr_list_t *attrs = &call->is_message_attrs; isns_attr_list_append_uint32(attrs, ISNS_TAG_ISCSI_SCN_BITMAP, scn_bits); isns_object_extract_keys(obj, attrs); if (dd) isns_object_extract_keys(dd, attrs); } /* * Process a SCN registration */ int isns_process_scn_register(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_attr_t *attr; isns_object_t *node = NULL; uint32_t scn_bitmap; isns_scn_t *scn; int status = ISNS_SUCCESS; /* * 5.6.5.5 * The SCNReg request PDU Payload contains a Source Attribute, a Message * Key Attribute, and an Operating Attribute. Valid Message Key * Attributes for a SCNReg are shown below: * * Valid Message Key Attributes for SCNReg * --------------------------------------- * iSCSI Name * FC Port Name WWPN */ if (keys->ial_count != 1 || attrs->ial_count != 1) return ISNS_SCN_REGISTRATION_REJECTED; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_NAME && attr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) return ISNS_SCN_REGISTRATION_REJECTED; /* Look up the storage node for this source. If it does * not exist, reject the message. */ node = isns_db_lookup(db, NULL, keys); if (node == NULL) return ISNS_SOURCE_UNKNOWN; /* * Policy: verify that the client is permitted * to access this entity. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow monitoring of * this object type. */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, node, call->is_function)) goto unauthorized; /* * 5.6.5.5 * The SCN Bitmap is the only operating attribute of this message * [...] * Control Nodes MAY conduct registrations for management SCNs; * iSNS clients that are not supporting Control Nodes MUST NOT * conduct registrations for management SCNs. * * Implementer's note: for iFCP sources, we should check for * ISNS_TAG_IFCP_SCN_BITMAP. */ attr = attrs->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_SCN_BITMAP || !ISNS_ATTR_IS_UINT32(attr)) goto rejected; scn_bitmap = attr->ia_value.iv_uint32; if (!isns_policy_validate_scn_bitmap(call->is_policy, scn_bitmap)) goto unauthorized; /* * 5.6.5.5 * If no SCN Port fields of any Portals of the Storage Node are * registered to receive SCN messages, then the SCNReg message SHALL * be rejected with Status Code 17 (SCN Registration Rejected). */ if (!(scn = isns_scn_create_scn(node, scn_bitmap, db))) goto rejected; *result = isns_simple_create(ISNS_SCN_REGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: if (node) isns_object_release(node); return status; rejected: status = ISNS_SCN_REGISTRATION_REJECTED; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Process a SCNDereg message */ int isns_process_scn_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_attr_list_t *keys = &call->is_message_attrs; isns_db_t *db = srv->is_db; isns_attr_t *attr; isns_object_t *node = NULL; int status = ISNS_SUCCESS; /* * 5.6.5.6 * The SCNDereg request message PDU Payload contains a Source Attribute * and Message Key Attribute(s). Valid Message Key Attributes for a * SCNDereg are shown below: * * Valid Message Key Attributes for SCNDereg * ----------------------------------------- * iSCSI Name * FC Port Name WWPN * * There are no Operating Attributes in the SCNDereg message. */ if (keys->ial_count != 1) return ISNS_SCN_REGISTRATION_REJECTED; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_NAME && attr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) return ISNS_SCN_REGISTRATION_REJECTED; /* Look up the storage node for this source. If it does * not exist, reject the message. */ /* * Look up the storage node for this source. If it does * not exist call this success. * * Implementor's comment: the specification is unclear * on how to handle the case where a SCN deregistration * is received when there are no registrations. It * seems like SUCCESS is better than INVALID_DEREGISTRATION */ node = isns_db_lookup(db, NULL, keys); if (node == NULL) { *result = isns_simple_create(ISNS_SCN_DEREGISTER, srv->is_source, NULL); return ISNS_SUCCESS; } /* * Policy: verify that the client is permitted * to access this entity. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow monitoring of * this object type. */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, node, call->is_function)) goto unauthorized; isns_object_set_scn_mask(node, 0); isns_scn_delete_scn(node); *result = isns_simple_create(ISNS_SCN_DEREGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: if (node) isns_object_release(node); return status; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Set up the SCN object. */ static isns_scn_t * isns_scn_setup(isns_scn_t *scn, isns_object_t *node) { isns_object_list_t portals = ISNS_OBJECT_LIST_INIT; isns_object_t *entity; unsigned int i; entity = isns_object_get_entity(node); if (entity == NULL || !isns_object_find_descendants(entity, &isns_portal_template, NULL, &portals)) return NULL; for (i = 0; i < portals.iol_count; ++i) { isns_object_t *portal = portals.iol_data[i]; isns_portal_info_t info; isns_scn_funnel_t *funnel; /* Extract address and SCN port from portal */ if (!isns_portal_from_object(&info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_SCN_PORT, portal)) continue; /* We know where to send our notifications! */ if (scn == NULL) { isns_attr_t *attr; if (!isns_object_get_attr(node, ISNS_TAG_ISCSI_NAME, &attr) && !isns_object_get_attr(node, ISNS_TAG_FC_PORT_NAME_WWPN, &attr)) { isns_error("Attempt to set up SCN for strange node type\n"); return NULL; } scn = isns_calloc(1, sizeof(*scn)); scn->scn_entity = isns_object_get(entity); scn->scn_owner = isns_object_get(node); scn->scn_attr = isns_attr_get(attr); scn->scn_name = isns_strdup(attr->ia_value.iv_string); } funnel = isns_calloc(1, sizeof(*funnel)); funnel->scn_portal = info; funnel->scn_next = scn->scn_funnels; scn->scn_funnels = funnel; } isns_object_list_destroy(&portals); return scn; } /* * See if an SCN object exists for the given target; * if it doesn't, then create one. */ static isns_scn_t * isns_scn_create_scn(isns_object_t *node, uint32_t bitmap, isns_db_t *db) { isns_scn_t *scn; for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_owner == node) goto done; } /* Not found - create it */ scn = isns_scn_setup(NULL, node); if (scn == NULL) return NULL; scn->scn_next = isns_scn_list; isns_scn_list = scn; done: /* We're all set - update the bitmap */ isns_object_set_scn_mask(node, bitmap); return scn; } static void isns_scn_delete_scn(isns_object_t *node) { isns_scn_t *scn, **pos; pos = &isns_scn_list; while ((scn = *pos) != NULL) { if (scn->scn_owner == node) { isns_debug_scn("Deregistering SCN for node %u\n", node->ie_index); *pos = scn->scn_next; isns_scn_free(scn); return; } pos = &scn->scn_next; } } static void isns_scn_release_funnels(isns_scn_t *scn) { isns_scn_funnel_t *funnel; while ((funnel = scn->scn_funnels) != NULL) { scn->scn_funnels = funnel->scn_next; if (funnel->scn_socket) isns_socket_free(funnel->scn_socket); isns_free(funnel); } } static void isns_scn_free(isns_scn_t *scn) { isns_scn_release_funnels(scn); isns_object_release(scn->scn_owner); isns_object_release(scn->scn_entity); isns_attr_release(scn->scn_attr); isns_free(scn->scn_name); isns_free(scn); } /* * Check whether we should send an event to the target */ static inline int isns_scn_match(isns_scn_t *scn, uint32_t event, const isns_object_t *node, uint32_t node_type) { if (event == 0) return 0; if (node->ie_scn_mask & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK) return event | ISNS_SCN_MANAGEMENT_REGISTRATION_MASK; #if 0 /* This is a normal (non-control) node. Check whether the object * is in the scope of this client. */ if (!isns_object_in_scope(scn->scn_owner, node)) return 0; #endif if (node->ie_scn_mask & ISNS_SCN_TARGET_AND_SELF_ONLY_MASK) { if (node != scn->scn_owner && !(node_type & ISNS_ISCSI_TARGET_MASK)) return 0; } if (node->ie_scn_mask & ISNS_SCN_INITIATOR_AND_SELF_ONLY_MASK) { if (node != scn->scn_owner && !(node_type & ISNS_ISCSI_INITIATOR_MASK)) return 0; } return event; } /* * Helper to create time stamp attr */ static isns_attr_t * isns_create_timestamp_attr(void) { isns_value_t value = ISNS_VALUE_INIT(uint64, time(NULL)); return isns_attr_alloc(ISNS_TAG_TIMESTAMP, NULL, &value); } /* * This function is invoked whenever someone changes the * database. * * SCNs are another area where the RFC is fabulously wishy washy. * It is not entirely clear when DD/DDS information should be * included in a management SCN - one *reasonable* interpretation * would be that this happens for DDReg/DDDereg/DDSReg/DDSDereg * events only. But some sections make it sound as if DD * information is included for all management SCNs. */ void isns_scn_callback(const isns_db_event_t *ev, void *ptr) { isns_object_t *obj = ev->ie_object; isns_scn_t *scn, **pos; isns_attr_t *timestamp; uint32_t node_type; /* Never send out notifications for policy objects and the like. */ if (obj->ie_flags & ISNS_OBJECT_PRIVATE) return; /* When an entity is nuked, remove all SCNs to nodes * that registered from there */ if (ISNS_IS_ENTITY(obj) && (ev->ie_bits & ISNS_SCN_OBJECT_REMOVED_MASK)) { pos = &isns_scn_list; while ((scn = *pos) != NULL) { if (scn->scn_entity != obj) { pos = &scn->scn_next; continue; } isns_debug_scn("Deleting SCN registration for %s\n", scn->scn_name); *pos = scn->scn_next; isns_scn_free(scn); } return; } /* For now we handle iSCSI nodes only. Maybe later we'll * do iFC nodes as well. */ if (!ISNS_IS_ISCSI_NODE(obj)) return; if (!isns_object_get_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, &node_type)) return; if (ev->ie_recipient) { isns_object_t *dst = ev->ie_recipient; isns_debug_scn("SCN unicast <%s %u, %s> -> %s %u\n", obj->ie_template->iot_name, obj->ie_index, isns_event_string(ev->ie_bits), dst->ie_template->iot_name, dst->ie_index); } else { isns_debug_scn("SCN multicast <%s %u, %s>\n", obj->ie_template->iot_name, obj->ie_index, isns_event_string(ev->ie_bits)); } timestamp = isns_create_timestamp_attr(); pos = &isns_scn_list; while ((scn = *pos) != NULL) { unsigned int scn_bits, management; isns_object_t *recipient, *dd = NULL; isns_simple_t *call; recipient = scn->scn_owner; /* Check if the node has gone away completely. */ if (recipient->ie_scn_mask == 0) { *pos = scn->scn_next; isns_scn_free(scn); continue; } if (recipient->ie_container == NULL) { isns_warning("Internal bug - SCN recipient without container\n"); /* Clear the bitmask and loop over - this will remove it */ recipient->ie_scn_mask = 0; continue; } /* See if portals were added/removed. * This does not catch updates that modified *just* * the SCN port */ if (recipient->ie_container->ie_mtime != scn->scn_last_update) { /* Rebuild the list of SCN portals */ isns_scn_release_funnels(scn); scn->scn_last_update = 0; } pos = &scn->scn_next; /* Check for unicast events (triggered for DD addition/removal). * For unicast events, we do not mask the SCN bits, so that * clients who have registered for non-management events * will see the membership events for their DDs nevertheless. */ if (ev->ie_recipient == NULL) { scn_bits = ev->ie_bits & recipient->ie_scn_mask; if (scn_bits == 0) continue; /* Management SCNs should not be delivered to nodes * that have not registered for them. */ if ((ev->ie_bits & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK) && !(recipient->ie_scn_mask & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK)) continue; } else if (recipient == ev->ie_recipient) { scn_bits = ev->ie_bits; } else { /* No match, skip this recipient */ continue; } if (scn->scn_last_update == 0) { scn->scn_last_update = recipient->ie_container->ie_mtime; isns_scn_setup(scn, recipient); } /* We check for SCN capable portals when processing * the SCN registration. But the portals may go away * in the meantime. */ if (scn->scn_funnels == NULL) continue; /* Check SCN bitmask. This will modify the event bits. */ scn_bits = isns_scn_match(scn, scn_bits, obj, node_type); if (scn_bits == 0) continue; management = !!(scn_bits & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK); /* * 2.2.3 * A regular SCN registration indicates that the * Discovery Domain Service SHALL be used to control the * distribution of SCN messages. Receipt of regular * SCNs is limited to the discovery domains in which * the SCN-triggering event takes place. Regular SCNs * do not contain information about discovery domains. * * Implementer's note: We override check for unicast events. * The reason is that DDDereg will sever the * relationship, and we would never send an SCN for that * event. */ if (!management && !ev->ie_recipient) { if (!isns_object_test_visibility(obj, recipient)) continue; } isns_debug_scn("preparing to send SCN to %s\n", scn->scn_name); if ((call = scn->scn_message) == NULL) { call = isns_create_scn(isns_scn_server->is_source, scn->scn_attr, timestamp); if (call == NULL) continue; scn->scn_message = call; } /* * If the SCN is a Management SCN, then the SCN message * SHALL also list the DD_ID and/or DDS_ID of the * Discovery Domains and Discovery Domain Sets (if any) * that caused the change in state for that Storage Node. * These additional attributes (i.e., DD_ID and/or DDS_ID) * shall immediately follow the iSCSI Name or FC Port * Name and precede the next SCN bitmap for the next * notification message (if any). */ if (management && ev->ie_trigger) dd = ev->ie_trigger; isns_scn_add_event(call, scn_bits, obj, dd); } isns_attr_release(timestamp); } /* * Obtain a socket to talk to this guy. * Not entirely trivial - this can be both an established * (incoming) connection, or one that we should establish. * * Note, we do not support transmission on the incoming * connection yet. */ static isns_socket_t * isns_scn_get_socket(isns_scn_t *scn) { isns_scn_funnel_t *f, *best = NULL; isns_socket_t *sock; unsigned int worst = 0, loops = 0, nfunnels; char *ps; /* Keep it simple for now */ if ((f = scn->scn_current_funnel) != NULL && f->scn_socket) { if (!f->scn_bad) return f->scn_socket; /* Oops, we've seen timeouts on this socket. */ isns_socket_free(f->scn_socket); f->scn_socket = NULL; } again: nfunnels = 0; for (f = scn->scn_funnels; f; f = f->scn_next) { unsigned int badness = f->scn_bad; if (!best || badness < best->scn_bad) best = f; if (badness > worst) worst = badness; nfunnels++; } if (!best) return NULL; sock = isns_connect_to_portal(&best->scn_portal); if (sock == NULL) { /* Make sure we try each funnel exactly once */ best->scn_bad = worst + 1; if (++loops < nfunnels) goto again; return NULL; } /* Set the security context */ isns_socket_set_security_ctx(sock, isns_default_security_context(1)); ps = isns_portal_string(&best->scn_portal); isns_debug_scn("SCN: %s using portal %s\n", scn->scn_name, ps); scn->scn_current_funnel = best; best->scn_socket = sock; return sock; } /* * This is the callback function invoked when the SCN message reply * comes in, or when the message timed out. */ static void isns_process_scn_response(uint32_t xid, int status, isns_simple_t *msg) { isns_scn_t *scn; if (msg == NULL) { isns_debug_scn("SCN timed out\n"); return; } isns_debug_scn("Received an SCN response\n"); for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_pending && scn->scn_xid == xid) { isns_debug_scn("SCN: %s acknowledged notification\n", scn->scn_name); isns_simple_free(scn->scn_pending); scn->scn_pending = NULL; if (scn->scn_current_funnel) scn->scn_current_funnel->scn_bad = 0; } } } /* * Transmit all pending SCN messages * * 2.9.2 * If a Network Entity has multiple Portals with registered SCN UDP Ports, * then SCN messages SHALL be delivered to each Portal registered to * receive such messages. * * FIXME: we should make this timer based just as the ESI code. */ time_t isns_scn_transmit_all(void) { time_t now = time(NULL), next_timeout; isns_scn_t *scn; for (scn = isns_scn_list; scn; scn = scn->scn_next) { isns_simple_t *call; isns_socket_t *sock; /* We do not allow more than one outstanding * notification for now. */ if ((call = scn->scn_pending) != NULL) { if (scn->scn_timeout > now) continue; scn->scn_current_funnel->scn_bad++; if (--(scn->scn_retries)) goto retry; isns_warning("SCN for %s timed out\n", scn->scn_name); isns_simple_free(call); scn->scn_pending = NULL; } if ((call = scn->scn_message) == NULL) continue; isns_debug_scn("SCN: transmit pending message for %s\n", scn->scn_name); scn->scn_retries = isns_config.ic_scn_retries; scn->scn_pending = call; scn->scn_message = NULL; retry: if ((sock = isns_scn_get_socket(scn)) == NULL) { /* Sorry, no can do. */ isns_warning("SCN for %s dropped - no portal\n", scn->scn_name); scn->scn_pending = NULL; isns_simple_free(call); continue; } isns_simple_transmit(sock, call, NULL, isns_config.ic_scn_timeout, isns_process_scn_response); scn->scn_xid = call->is_xid; scn->scn_timeout = now + isns_config.ic_scn_timeout; } next_timeout = now + 3600; for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_pending && scn->scn_timeout < next_timeout) next_timeout = scn->scn_timeout; } return next_timeout; } /* * Process an incoming State Change Notification */ int isns_process_scn(isns_server_t *srv, isns_simple_t *call, isns_simple_t **reply) { isns_attr_list_t *list = &call->is_message_attrs; isns_attr_t *dstattr, *tsattr; const char *dst_name; unsigned int i; /* The first attribute is the destination, and should match * our source name. Don't bother checking. The second is the * time stamp. */ if (list->ial_count < 2) goto rejected; dstattr = list->ial_data[0]; if (dstattr->ia_tag_id != ISNS_TAG_ISCSI_NAME && dstattr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) goto rejected; if (!ISNS_ATTR_IS_STRING(dstattr)) goto rejected; dst_name = dstattr->ia_value.iv_string; tsattr = list->ial_data[1]; if (tsattr->ia_tag_id != ISNS_TAG_TIMESTAMP) return ISNS_SCN_EVENT_REJECTED; for (i = 2; i < list->ial_count; ) { isns_object_template_t *tmpl; isns_attr_t *bmattr, *srcattr; const char *node_name; uint32_t bitmap; if (i + 1 >= list->ial_count) goto rejected; bmattr = list->ial_data[i++]; srcattr = list->ial_data[i++]; /* Validate that bitmap and node type match */ switch (bmattr->ia_tag_id) { case ISNS_TAG_ISCSI_SCN_BITMAP: if (srcattr->ia_tag_id != ISNS_TAG_ISCSI_NAME) goto rejected; tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_IFCP_SCN_BITMAP: if (srcattr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) goto rejected; tmpl = &isns_fc_port_template; break; default: goto rejected; } /* Skip over and DD_ID or DDS_ID attrs */ while (i < list->ial_count) { isns_attr_t *ddattr = list->ial_data[i]; if (ddattr->ia_tag_id == ISNS_TAG_ISCSI_SCN_BITMAP || ddattr->ia_tag_id == ISNS_TAG_IFCP_SCN_BITMAP) break; ++i; } if (!ISNS_ATTR_IS_UINT32(bmattr)) goto rejected; bitmap = bmattr->ia_value.iv_uint32; if (!ISNS_ATTR_IS_STRING(srcattr)) goto rejected; node_name = srcattr->ia_value.iv_string; if (srv->is_scn_callback) srv->is_scn_callback(srv->is_db, bitmap, tmpl, node_name, dst_name); } /* * 5.7.5.8. SCN Response (SCNRsp) * The SCNRsp response contains the SCN Destination Attribute * representing the Node identifier that received the SCN. */ *reply = isns_create_scn(srv->is_source, list->ial_data[0], NULL); return ISNS_SUCCESS; rejected: return ISNS_SCN_EVENT_REJECTED; }
24,225
C
.c
810
27.103704
96
0.686335
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,493
pki.c
cleech_open-isns/pki.c
/* * PKI related functions * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <sys/stat.h> #include <string.h> #include <unistd.h> #include <limits.h> #include "config.h" #ifdef WITH_SECURITY #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #endif #include <fcntl.h> #include <libisns/isns.h> #include "security.h" #include <libisns/util.h> #ifdef WITH_SECURITY /* versions prior to 9.6.8 didn't seem to have these */ #if OPENSSL_VERSION_NUMBER < 0x00906080L # define EVP_MD_CTX_init(c) do { } while (0) # define EVP_MD_CTX_cleanup(c) do { } while (0) #endif #if OPENSSL_VERSION_NUMBER < 0x00906070L # define i2d_DSA_PUBKEY i2d_DSA_PUBKEY_backwards static int i2d_DSA_PUBKEY_backwards(DSA *, unsigned char **); #endif /* OpenSSL 1.1 made a lot of structures opaque, so we need to * define the 1.1 wrappers in previous versions. */ #if OPENSSL_VERSION_NUMBER < 0x10100000L #define EVP_PKEY_base_id(o) ((o)->type) #define EVP_PKEY_get0_DSA(o) ((o)->pkey.dsa) static EVP_MD_CTX *EVP_MD_CTX_new(void) { EVP_MD_CTX *ctx = OPENSSL_malloc(sizeof(EVP_MD_CTX)); EVP_MD_CTX_init(ctx); return ctx; } static void EVP_MD_CTX_free(EVP_MD_CTX *ctx) { EVP_MD_CTX_cleanup(ctx); OPENSSL_free(ctx); } void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key) { if (pub_key != NULL) *pub_key = d->pub_key; if (priv_key != NULL) *priv_key = d->priv_key; } BN_GENCB *BN_GENCB_new(void) { return OPENSSL_malloc(sizeof(BN_GENCB)); } void BN_GENCB_free(BN_GENCB *cb) { OPENSSL_free(cb); } #else /* EVP_dss1 is now gone completely, so just use EVP_sha1 instead. */ #define EVP_dss1 EVP_sha1 #endif static int isns_openssl_init = 0; static int isns_dsasig_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *); static int isns_dsasig_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *); static EVP_PKEY *isns_dsasig_load_private_pem(isns_security_t *ctx, const char *filename); static EVP_PKEY *isns_dsasig_load_public_pem(isns_security_t *ctx, const char *filename); static DSA * isns_dsa_load_params(const char *); /* * Create a DSA security context */ isns_security_t * isns_create_dsa_context(void) { isns_security_t *ctx; if (!isns_openssl_init) { ERR_load_crypto_strings(); #if OPENSSL_API_COMPAT < 0x10100000L OpenSSL_add_all_algorithms(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); #else OPENSSL_init_crypto(); #endif isns_openssl_init = 1; } ctx = isns_calloc(1, sizeof(*ctx)); ctx->is_name = "DSA"; ctx->is_type = ISNS_AUTH_TYPE_SHA1_DSA; ctx->is_replay_window = isns_config.ic_auth.replay_window; ctx->is_timestamp_jitter = isns_config.ic_auth.timestamp_jitter; ctx->is_verify = isns_dsasig_verify; ctx->is_sign = isns_dsasig_sign; ctx->is_load_private = isns_dsasig_load_private_pem; ctx->is_load_public = isns_dsasig_load_public_pem; isns_debug_auth("Created DSA authentication context\n"); return ctx; } /* * DSA signature generation and verification */ static void isns_message_digest(EVP_MD_CTX *md, const buf_t *pdu, const struct isns_authblk *blk) { uint64_t stamp; EVP_DigestUpdate(md, buf_head(pdu), buf_avail(pdu)); /* The RFC doesn't say which pieces of the * message should be hashed. * We make an educated guess. */ stamp = htonll(blk->iab_timestamp); EVP_DigestUpdate(md, &stamp, sizeof(stamp)); } static void isns_dsasig_report_errors(const char *msg, isns_print_fn_t *fn) { unsigned long code; fn("%s - OpenSSL errors follow:\n", msg); while ((code = ERR_get_error()) != 0) fn("> %s: %s\n", ERR_func_error_string(code), ERR_reason_error_string(code)); } int isns_dsasig_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *blk) { static unsigned char signature[1024]; unsigned int sig_len = sizeof(signature); EVP_MD_CTX *md_ctx; EVP_PKEY *pkey; const BIGNUM *priv_key = NULL; int err; if ((pkey = peer->is_key) == NULL) return 0; if (EVP_PKEY_base_id(pkey) != EVP_PKEY_DSA) { isns_debug_message( "Incompatible public key (spi=%s)\n", peer->is_name); return 0; } if (EVP_PKEY_size(pkey) > sizeof(signature)) { isns_error("isns_dsasig_sign: signature buffer too small\n"); return 0; } DSA_get0_key(EVP_PKEY_get0_DSA(pkey), NULL, &priv_key); if (priv_key == NULL) { isns_error("isns_dsasig_sign: oops, seems to be a public key\n"); return 0; } isns_debug_auth("Signing messages with spi=%s, DSA/%u\n", peer->is_name, EVP_PKEY_bits(pkey)); md_ctx = EVP_MD_CTX_new(); EVP_SignInit(md_ctx, EVP_dss1()); isns_message_digest(md_ctx, pdu, blk); err = EVP_SignFinal(md_ctx, signature, &sig_len, pkey); EVP_MD_CTX_free(md_ctx); if (err == 0) { isns_dsasig_report_errors("EVP_SignFinal failed", isns_error); return 0; } blk->iab_sig = signature; blk->iab_sig_len = sig_len; return 1; } int isns_dsasig_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *blk) { EVP_MD_CTX *md_ctx; EVP_PKEY *pkey; int err; if ((pkey = peer->is_key) == NULL) return 0; if (EVP_PKEY_base_id(pkey) != EVP_PKEY_DSA) { isns_debug_message( "Incompatible public key (spi=%s)\n", peer->is_name); return 0; } md_ctx = EVP_MD_CTX_new(); EVP_VerifyInit(md_ctx, EVP_dss1()); isns_message_digest(md_ctx, pdu, blk); err = EVP_VerifyFinal(md_ctx, blk->iab_sig, blk->iab_sig_len, pkey); EVP_MD_CTX_free(md_ctx); if (err == 0) { isns_debug_auth("*** Incorrect signature ***\n"); return 0; } if (err < 0) { isns_dsasig_report_errors("EVP_VerifyFinal failed", isns_error); return 0; } isns_debug_message("Good signature from %s\n", peer->is_name?: "<server>"); return 1; } EVP_PKEY * isns_dsasig_load_private_pem(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; FILE *fp; if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open DSA keyfile %s: %m\n", filename); return 0; } pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL); fclose(fp); return pkey; } EVP_PKEY * isns_dsasig_load_public_pem(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; FILE *fp; if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open DSA keyfile %s: %m\n", filename); return 0; } pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (pkey == NULL) { isns_dsasig_report_errors("Error loading DSA public key", isns_error); } fclose(fp); return pkey; } EVP_PKEY * isns_dsa_decode_public(const void *ptr, size_t len) { const unsigned char *der = ptr; EVP_PKEY *evp; DSA *dsa; /* Assigning ptr to a temporary variable avoids a silly * compiled warning about type-punning. */ dsa = d2i_DSA_PUBKEY(NULL, &der, len); if (dsa == NULL) return NULL; evp = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp, dsa); return evp; } int isns_dsa_encode_public(EVP_PKEY *pkey, void **ptr, size_t *len) { int bytes; *ptr = NULL; bytes = i2d_DSA_PUBKEY(EVP_PKEY_get0_DSA(pkey), (unsigned char **) ptr); if (bytes < 0) return 0; *len = bytes; return 1; } EVP_PKEY * isns_dsa_load_public(const char *name) { return isns_dsasig_load_public_pem(NULL, name); } int isns_dsa_store_private(const char *name, EVP_PKEY *key) { FILE *fp; int rv, fd; if ((fd = open(name, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) { isns_error("Cannot save DSA key to %s: %m\n", name); return 0; } if (!(fp = fdopen(fd, "w"))) { isns_error("fdopen(%s): %m\n", name); close(fd); return 0; } rv = PEM_write_PrivateKey(fp, key, NULL, NULL, 0, 0, NULL); fclose(fp); if (rv == 0) isns_dsasig_report_errors("Failed to store private key", isns_error); return rv; } int isns_dsa_store_public(const char *name, EVP_PKEY *key) { FILE *fp; int rv; if (!(fp = fopen(name, "w"))) { isns_error("Unable to open %s: %m\n", name); return 0; } rv = PEM_write_PUBKEY(fp, key); fclose(fp); if (rv == 0) isns_dsasig_report_errors("Failed to store public key", isns_error); return rv; } /* * DSA key generation */ EVP_PKEY * isns_dsa_generate_key(void) { EVP_PKEY *pkey; DSA *dsa = NULL; if (!(dsa = isns_dsa_load_params(isns_config.ic_dsa.param_file))) goto failed; if (!DSA_generate_key(dsa)) { isns_dsasig_report_errors("Failed to generate DSA key", isns_error); goto failed; } pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(pkey, dsa); return pkey; failed: if (dsa) DSA_free(dsa); return NULL; } DSA * isns_dsa_load_params(const char *filename) { FILE *fp; DSA *dsa; if (!filename) { isns_error("Cannot generate key - no DSA parameter file\n"); return NULL; } if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open %s: %m\n", filename); return NULL; } dsa = PEM_read_DSAparams(fp, NULL, NULL, NULL); fclose(fp); if (dsa == NULL) { isns_dsasig_report_errors("Error loading DSA parameters", isns_error); } return dsa; } static void isns_dsa_param_gen_callback(int stage, int index, void *dummy) { if (stage == 0) write(1, "+", 1); else if (stage == 1) write(1, ".", 1); else if (stage == 2) write(1, "/", 1); } int isns_dsa_init_params(const char *filename) { FILE *fp; DSA *dsa; #if OPENSSL_VERSION_NUMBER >= 0x10002000L BN_GENCB *cb; #endif const int dsa_key_bits = 1024; if (access(filename, R_OK) == 0) return 1; isns_mkdir_recursive(isns_dirname(filename)); if (!(fp = fopen(filename, "w"))) { isns_error("Unable to open %s: %m\n", filename); return 0; } isns_notice("Generating DSA parameters; this may take a while\n"); #if OPENSSL_VERSION_NUMBER >= 0x10002000L cb = BN_GENCB_new(); BN_GENCB_set(cb, (int (*)(int, int, BN_GENCB *)) isns_dsa_param_gen_callback, NULL); dsa = DSA_new(); if (!DSA_generate_parameters_ex(dsa, dsa_key_bits, NULL, 0, NULL, NULL, cb)) { DSA_free(dsa); dsa = NULL; } BN_GENCB_free(cb); #else dsa = DSA_generate_parameters(dsa_key_bits, NULL, 0, NULL, NULL, isns_dsa_param_gen_callback, NULL); #endif write(1, "\n", 1); if (dsa == NULL) { isns_dsasig_report_errors("Error generating DSA parameters", isns_error); fclose(fp); return 0; } if (!PEM_write_DSAparams(fp, dsa)) { isns_dsasig_report_errors("Error writing DSA parameters", isns_error); DSA_free(dsa); fclose(fp); return 0; } DSA_free(dsa); fclose(fp); return 1; } /* * Make sure the authentication key is present. */ int isns_dsa_init_key(const char *filename) { char pubkey_path[1024]; EVP_PKEY *pkey; isns_mkdir_recursive(isns_dirname(filename)); snprintf(pubkey_path, sizeof(pubkey_path), "%s.pub", filename); if (access(filename, R_OK) == 0 && access(pubkey_path, R_OK) == 0) return 1; if (!(pkey = isns_dsa_generate_key())) { isns_error("Failed to generate AuthKey\n"); return 0; } if (!isns_dsa_store_private(filename, pkey)) { isns_error("Unable to write private key to %s\n", filename); return 0; } isns_notice("Stored private key in %s\n", filename); if (!isns_dsa_store_public(pubkey_path, pkey)) { isns_error("Unable to write public key to %s\n", pubkey_path); return 0; } isns_notice("Stored private key in %s\n", pubkey_path); return 1; } /* * Simple keystore - this is a flat directory, with * public key files using the SPI as their name. */ typedef struct isns_simple_keystore isns_simple_keystore_t; struct isns_simple_keystore { isns_keystore_t sc_base; char * sc_dirpath; }; /* * Load a DSA key from the cert store * In fact, this will load RSA keys as well. */ static EVP_PKEY * __isns_simple_keystore_find(isns_keystore_t *store_base, const char *name, size_t namelen) { isns_simple_keystore_t *store = (isns_simple_keystore_t *) store_base; char *pathname; size_t capacity; EVP_PKEY *result; /* Refuse to open key files with names * that refer to parent directories */ if (memchr(name, '/', namelen) || name[0] == '.') return NULL; capacity = strlen(store->sc_dirpath) + 2 + namelen; pathname = isns_malloc(capacity); if (!pathname) isns_fatal("Out of memory."); snprintf(pathname, capacity, "%s/%.*s", store->sc_dirpath, (int) namelen, name); if (access(pathname, R_OK) < 0) { isns_free(pathname); return NULL; } result = isns_dsasig_load_public_pem(NULL, pathname); isns_free(pathname); return result; } isns_keystore_t * isns_create_simple_keystore(const char *dirname) { isns_simple_keystore_t *store; store = isns_calloc(1, sizeof(*store)); store->sc_base.ic_name = "simple key store"; store->sc_base.ic_find = __isns_simple_keystore_find; store->sc_dirpath = isns_strdup(dirname); return (isns_keystore_t *) store; } #if OPENSSL_VERSION_NUMBER < 0x00906070L #undef i2d_DSA_PUBKEY int i2d_DSA_PUBKEY_backwards(DSA *dsa, unsigned char **ptr) { unsigned char *buf; int len; len = i2d_DSA_PUBKEY(dsa, NULL); if (len < 0) return 0; *ptr = buf = OPENSSL_malloc(len); return i2d_DSA_PUBKEY(dsa, &buf); } #endif #endif /* WITH_SECURITY */
13,060
C
.c
514
23.060311
85
0.68629
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,494
bitvector.c
cleech_open-isns/bitvector.c
/* * Handle bit vector as a run length encoded array of * 32bit words. * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <libisns/isns.h> #include <libisns/util.h> struct isns_bitvector { unsigned int ib_count; uint32_t * ib_words; }; void isns_bitvector_init(isns_bitvector_t *bv) { memset(bv, 0, sizeof(*bv)); } void isns_bitvector_destroy(isns_bitvector_t *bv) { isns_free(bv->ib_words); memset(bv, 0, sizeof(*bv)); } isns_bitvector_t * isns_bitvector_alloc(void) { return isns_calloc(1, sizeof(isns_bitvector_t)); } void isns_bitvector_free(isns_bitvector_t *bv) { if (bv) { isns_free(bv->ib_words); memset(bv, 0xa5, sizeof(*bv)); isns_free(bv); } } /* * Helper function to locate bit */ uint32_t * __isns_bitvector_find_word(const isns_bitvector_t *bv, unsigned int bit) { uint32_t *wp, *end; if (bv->ib_words == NULL) return NULL; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = wp[0]; rlen = wp[1]; isns_assert(!(base % 32)); if (base <= bit && bit < base + rlen * 32) return wp + 2 + ((bit - base) / 32); wp += 2 + rlen; isns_assert(wp <= end); } return NULL; } /* * Insert words in the middle of the array */ static inline void __isns_bitvector_insert_words(isns_bitvector_t *bv, unsigned int offset, unsigned int count) { bv->ib_words = isns_realloc(bv->ib_words, (bv->ib_count + count) * sizeof(uint32_t)); /* If we insert in the middle, shift out the tail * to make room for the new range. */ isns_assert(offset <= bv->ib_count); if (offset < bv->ib_count) { memmove(bv->ib_words + offset + count, bv->ib_words + offset, (bv->ib_count - offset) * sizeof(uint32_t)); } memset(bv->ib_words + offset, 0, count * sizeof(uint32_t)); bv->ib_count += count; } /* * Insert a new range */ static inline uint32_t * __isns_bitvector_insert_range(isns_bitvector_t *bv, unsigned int offset, unsigned int base) { uint32_t *pos; __isns_bitvector_insert_words(bv, offset, 3); pos = bv->ib_words + offset; *pos++ = base & ~31; *pos++ = 1; return pos; } /* * Extend an existing range * @offset marks the beginning of the existing range. */ static inline uint32_t * __isns_bitvector_extend_range(isns_bitvector_t *bv, unsigned int offset, unsigned int count) { uint32_t *pos, rlen; /* Find the end of the range */ pos = bv->ib_words + offset; rlen = pos[1]; __isns_bitvector_insert_words(bv, offset + 2 + rlen, count); pos = bv->ib_words + offset; pos[1] += count; /* Return pointer to the last word of the new range. */ return pos + 2 + rlen + count - 1; } /* * Find a suitable range for insertion */ static uint32_t * __isns_bitvector_find_insert_word(isns_bitvector_t *bv, unsigned int bit) { uint32_t *wp, *end; if (bv->ib_words == NULL) return __isns_bitvector_insert_range(bv, 0, bit); wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen, distance; base = wp[0]; rlen = wp[1]; isns_assert(!(base % 32)); if (bit < base) { return __isns_bitvector_insert_range(bv, wp - bv->ib_words, bit); } distance = (bit - base) / 32; if (distance < rlen) { /* This bit is within range */ return wp + 2 + distance; } /* Is it efficient to extend this range? * The break even point is if we have to add * 3 words to extend the range, because a new * range would be at least that much. */ if (distance + 1 <= rlen + 3) { return __isns_bitvector_extend_range(bv, wp - bv->ib_words, distance + 1 - rlen); } wp += 2 + rlen; isns_assert(wp <= end); } /* No suitable range found. Append one at the end */ return __isns_bitvector_insert_range(bv, bv->ib_count, bit); } /* * After clearing a bit, check if the bitvector can be * compacted. */ static void __isns_bitvector_compact(isns_bitvector_t *bv) { uint32_t *src, *dst, *end; unsigned int dst_base = 0, dst_len = 0; if (bv->ib_words == NULL) return; src = dst = bv->ib_words; end = src + bv->ib_count; while (src < end) { unsigned int base, rlen; base = *src++; rlen = *src++; /* Consume leading NUL words */ while (rlen && *src == 0) { base += 32; src++; rlen--; } /* Consume trailing NUL words */ while (rlen && src[rlen-1] == 0) rlen--; if (rlen != 0) { if (dst_len && dst_base + 32 * dst_len == base) { /* We can extend the previous run */ } else { /* New run. Close off the previous one, * if we had one. */ if (dst_len != 0) { dst[0] = dst_base; dst[1] = dst_len; dst += 2 + dst_len; } dst_base = base; dst_len = 0; } while (rlen--) dst[2 + dst_len++] = *src++; } isns_assert(src <= end); } if (dst_len != 0) { dst[0] = dst_base; dst[1] = dst_len; dst += 2 + dst_len; } bv->ib_count = dst - bv->ib_words; if (bv->ib_count == 0) isns_bitvector_destroy(bv); } /* * Test the value of a single bit */ int isns_bitvector_test_bit(const isns_bitvector_t *bv, unsigned int bit) { const uint32_t *pos; uint32_t mask; pos = __isns_bitvector_find_word(bv, bit); if (pos == NULL) return 0; mask = 1 << (bit % 32); return !!(*pos & mask); } int isns_bitvector_clear_bit(isns_bitvector_t *bv, unsigned int bit) { uint32_t *pos, oldval, mask; pos = __isns_bitvector_find_word(bv, bit); if (pos == NULL) return 0; mask = 1 << (bit % 32); oldval = *pos; *pos &= ~mask; __isns_bitvector_compact(bv); return !!(oldval & mask); } int isns_bitvector_set_bit(isns_bitvector_t *bv, unsigned int bit) { uint32_t *pos, oldval = 0, mask; mask = 1 << (bit % 32); pos = __isns_bitvector_find_insert_word(bv, bit); if (pos != NULL) { oldval = *pos; *pos |= mask; return !!(oldval & mask); } return 0; } int isns_bitvector_is_empty(const isns_bitvector_t *bv) { uint32_t *wp, *end; if (bv == NULL || bv->ib_count == 0) return 1; /* In theory, we should never have a non-compacted * empty bitvector, as the only way to get one * is through clear_bit. * Better safe than sorry... */ wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int rlen; rlen = wp[1]; wp += 2; while (rlen--) { if (*wp++) return 0; } isns_assert(wp <= end); } return 1; } int isns_bitvector_intersect(const isns_bitvector_t *a, const isns_bitvector_t *b, isns_bitvector_t *result) { const uint32_t *runa, *runb, *enda, *endb; const uint32_t *wpa = NULL, *wpb = NULL; uint32_t bita = 0, lena = 0, bitb = 0, lenb = 0; int found = -1; if (a == NULL || b == NULL) return -1; /* Returning the intersect is not implemented yet. */ isns_assert(result == NULL); runa = a->ib_words; enda = runa + a->ib_count; runb = b->ib_words; endb = runb + b->ib_count; while (1) { unsigned int skip; if (lena == 0) { next_a: if (runa >= enda) break; bita = *runa++; lena = *runa++; wpa = runa; runa += lena; lena *= 32; } if (lenb == 0) { next_b: if (runb >= endb) break; bitb = *runb++; lenb = *runb++; wpb = runb; runb += lenb; lenb *= 32; } if (bita < bitb) { skip = bitb - bita; /* range A ends before range B starts. * Proceed to next run in vector A. */ if (skip >= lena) goto next_a; bita += skip; lena -= skip; wpa += skip / 32; } else if (bitb < bita) { skip = bita - bitb; /* range B ends before range A starts. * Proceed to next run in vector B. */ if (skip >= lenb) goto next_b; bitb += skip; lenb -= skip; wpb += skip / 32; } isns_assert(bita == bitb); while (lena && lenb) { uint32_t intersect; intersect = *wpa & *wpb; if (!intersect) goto next_word; /* Find the bit */ if (found < 0) { uint32_t mask = intersect; found = bita; while (!(mask & 1)) { found++; mask >>= 1; } } if (result == NULL) return found; /* Append to result vector */ /* FIXME: TBD */ next_word: bita += 32; lena -= 32; wpa++; bitb += 32; lenb -= 32; wpb++; } } return found; } /* * Iterate over the bit vector */ void isns_bitvector_foreach(const isns_bitvector_t *bv, int (*cb)(uint32_t, void *), void *user_data) { uint32_t *wp, *end; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = wp[0]; rlen = wp[1]; wp += 2; while (rlen--) { uint32_t mask, word; word = *wp++; for (mask = 1; mask; mask <<= 1, ++base) { if (word & mask) cb(base, user_data); } } isns_assert(wp <= end); } } void isns_bitvector_dump(const isns_bitvector_t *bv, isns_print_fn_t *fn) { uint32_t *wp, *end; fn("Bit Vector %p (%u words):", bv, bv->ib_count); wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = wp[0]; rlen = wp[1]; wp += 2; fn(" <%u:", base); while (rlen--) fn(" 0x%x", *wp++); fn(">"); isns_assert(wp <= end); } if (bv->ib_count == 0) fn("<empty>"); fn("\n"); } static inline void __isns_bitvector_print_next(uint32_t first, uint32_t last, isns_print_fn_t *fn) { switch (last - first) { case 0: return; case 1: fn(", %u", last); break; default: fn("-%u", last); break; } } void isns_bitvector_print(const isns_bitvector_t *bv, isns_print_fn_t *fn) { uint32_t *wp, *end, first = 0, next = 0; const char *sepa = ""; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = wp[0]; rlen = wp[1]; wp += 2; while (rlen--) { uint32_t mask, word; word = *wp++; for (mask = 1; mask; mask <<= 1, ++base) { if (word & mask) { if (next++) continue; fn("%s%u", sepa, base); sepa = ", "; first = base; next = base + 1; } else { if (next) __isns_bitvector_print_next(first, next - 1, fn); first = next = 0; } } } isns_assert(wp <= end); } if (next) __isns_bitvector_print_next(first, next - 1, fn); if (*sepa == '\0') fn("<empty>"); fn("\n"); } #ifdef TEST int main(void) { isns_bitvector_t a, b; int i; isns_bitvector_init(&a); isns_bitvector_set_bit(&a, 0); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 1); isns_bitvector_set_bit(&a, 16); isns_bitvector_set_bit(&a, 32); isns_bitvector_set_bit(&a, 64); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 8192); isns_bitvector_set_bit(&a, 8196); isns_bitvector_set_bit(&a, 8194); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 2052); isns_bitvector_set_bit(&a, 2049); isns_bitvector_set_bit(&a, 2051); isns_bitvector_set_bit(&a, 2050); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); for (i = 127; i >= 0; --i) isns_bitvector_set_bit(&a, i); isns_bitvector_dump(&a, isns_print_stdout); printf("[Compacting]\n"); __isns_bitvector_compact(&a); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); for (i = 0; i < 128; ++i) isns_bitvector_set_bit(&a, i); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); isns_bitvector_init(&b); isns_bitvector_set_bit(&a, 0); isns_bitvector_set_bit(&a, 77); isns_bitvector_set_bit(&a, 249); isns_bitvector_set_bit(&a, 102); isns_bitvector_set_bit(&b, 1); isns_bitvector_set_bit(&b, 76); isns_bitvector_set_bit(&b, 250); isns_bitvector_set_bit(&b, 102); i = isns_bitvector_intersect(&a, &b, NULL); if (i != 102) fprintf(stderr, "*** BAD: Intersect should return 102 (got %d)! ***\n", i); else printf("Intersect okay: %d\n", i); isns_bitvector_destroy(&a); isns_bitvector_destroy(&b); isns_bitvector_init(&a); isns_bitvector_set_bit(&a, 0); isns_bitvector_set_bit(&a, 1); isns_bitvector_clear_bit(&a, 1); isns_bitvector_clear_bit(&a, 0); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); return 0; } #endif
12,259
C
.c
531
20.301318
77
0.623977
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,495
objects.h
cleech_open-isns/objects.h
/* * iSNS object model * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_OBJECTS_H #define ISNS_OBJECTS_H #include <libisns/isns.h> #include <libisns/attrs.h> enum isns_object_id { ISNS_OBJECT_TYPE_ENTITY = 1, ISNS_OBJECT_TYPE_NODE, ISNS_OBJECT_TYPE_PORTAL, ISNS_OBJECT_TYPE_PG, ISNS_OBJECT_TYPE_DD, ISNS_OBJECT_TYPE_DDSET, ISNS_OBJECT_TYPE_POLICY, ISNS_OBJECT_TYPE_FC_PORT, ISNS_OBJECT_TYPE_FC_NODE, __ISNS_OBJECT_TYPE_MAX }; struct isns_object_template { const char * iot_name; unsigned int iot_handle; /* internal handle */ unsigned int iot_num_attrs; unsigned int iot_num_keys; uint32_t * iot_attrs; uint32_t * iot_keys; uint32_t iot_index; uint32_t iot_next_index; isns_object_template_t *iot_container; unsigned int iot_relation_type; isns_relation_t * (*iot_build_relation)(isns_db_t *, isns_object_t *, const isns_object_list_t *); unsigned int iot_vendor_specific : 1; }; struct isns_object { /* There are two kinds of users of an object * - Temporary references that result from the * object being examined; being on a list, * etc. The main purpose of these references * is to make sure the object doesn't go away * while being used. * * These are accounted for by ie_users. * * - Permanent references that result from the * object being references by other objects * (usually relations) such as a Portal Group, * or a Discovery Domain. * * These are accounted for by ie_references. * * The main purpose of these references is to * model some of the weirder life cycle states * described in RFC 4171. * * Every reference via ie_references implies a * reference via ie_users. */ unsigned int ie_users; unsigned int ie_references; uint32_t ie_index; unsigned int ie_state; unsigned int ie_flags; time_t ie_mtime; uint32_t ie_scn_mask; /* Events this node listens for */ uint32_t ie_scn_bits; /* Current event bits */ isns_attr_list_t ie_attrs; isns_object_t * ie_container; uint32_t ie_container_idx; isns_object_template_t *ie_template; isns_relation_t * ie_relation; isns_object_list_t ie_children; /* Bit vector describing DD membership */ isns_bitvector_t * ie_membership; /* Support for virtual objects */ int (*ie_rebuild)(isns_object_t *, isns_db_t *); }; typedef struct isns_object_ref { isns_object_t * obj; } isns_object_ref_t; enum { ISNS_RELATION_NONE = 0, ISNS_RELATION_PORTAL_GROUP, }; struct isns_relation { unsigned int ir_type; unsigned int ir_users; isns_object_t * ir_object; isns_object_ref_t ir_subordinate[2]; }; typedef struct isns_relation_soup isns_relation_soup_t; typedef struct isns_relation_list isns_relation_list_t; struct isns_relation_list { unsigned int irl_count; isns_relation_t ** irl_data; }; #define ISNS_RELATION_LIST_INIT { .irl_count = 0, .irl_data = NULL } #define ISNS_OBJECT_DIRTY 0x0001 #define ISNS_OBJECT_PRIVATE 0x0002 #define ISNS_OBJECT_DEAD 0x0004 enum { ISNS_OBJECT_STATE_LARVAL, ISNS_OBJECT_STATE_MATURE, ISNS_OBJECT_STATE_LIMBO, ISNS_OBJECT_STATE_DEAD, }; extern int isns_object_remove_member(isns_object_t *obj, const isns_attr_t *attr, const uint32_t *subordinate_tags); extern void isns_object_reference_set(isns_object_ref_t *ref, isns_object_t *obj); extern void isns_object_reference_drop(isns_object_ref_t *ref); extern const char *isns_object_state_string(unsigned int); extern isns_object_template_t *isns_object_template_by_name(const char *); extern int isns_object_is_valid_container(const isns_object_t *, isns_object_template_t *); extern void isns_object_set_scn_mask(isns_object_t *, uint32_t); extern isns_object_t *isns_create_default_domain(void); /* * Helper macros for object type check */ #define __ISNS_OBJECT_TYPE_CHECK(obj, type) \ ((obj)->ie_template == &isns_##type##_template) #define ISNS_IS_ENTITY(obj) __ISNS_OBJECT_TYPE_CHECK(obj, entity) #define ISNS_IS_ISCSI_NODE(obj) __ISNS_OBJECT_TYPE_CHECK(obj, iscsi_node) #define ISNS_IS_FC_PORT(obj) __ISNS_OBJECT_TYPE_CHECK(obj, fc_port) #define ISNS_IS_FC_NODE(obj) __ISNS_OBJECT_TYPE_CHECK(obj, fc_node) #define ISNS_IS_PORTAL(obj) __ISNS_OBJECT_TYPE_CHECK(obj, portal) #define ISNS_IS_PG(obj) __ISNS_OBJECT_TYPE_CHECK(obj, iscsi_pg) #define ISNS_IS_POLICY(obj) __ISNS_OBJECT_TYPE_CHECK(obj, policy) #define ISNS_IS_DD(obj) __ISNS_OBJECT_TYPE_CHECK(obj, dd) #define ISNS_IS_DDSET(obj) __ISNS_OBJECT_TYPE_CHECK(obj, ddset) #endif /* ISNS_OBJECTS_H */
4,510
C
.c
136
30.955882
74
0.736297
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,496
slp.c
cleech_open-isns/slp.c
/* * SLP registration and query of iSNS * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include "config.h" #include <stdlib.h> #ifdef HAVE_SLP_H # include <slp.h> #endif #include <libisns/isns.h> #include <libisns/util.h> #include "internal.h" #define ISNS_SLP_SERVICE_NAME "iscsi:sms" /* * RFC 4018 says we would use scope initiator-scope-list. * But don't we want targets to find the iSNS server, too? */ #define ISNS_SLP_SCOPE "initiator-scope-list" #ifdef WITH_SLP struct isns_slp_url_state { SLPError slp_err; char * slp_url; }; static void isns_slp_report(SLPHandle handle, SLPError err, void *cookie) { *(SLPError *) cookie = err; } /* * Register a service with SLP */ int isns_slp_register(const char *url) { SLPError err, callbackerr; SLPHandle handle = NULL; err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return 0; } err = SLPReg(handle, url, SLP_LIFETIME_MAXIMUM, ISNS_SLP_SCOPE, "(description=iSNS Server),(protocols=isns)", SLP_TRUE, isns_slp_report, &callbackerr); SLPClose(handle); if (err == SLP_OK) err = callbackerr; if (err != SLP_OK) { isns_error("Failed to register with SLP (err %d)\n", err); return 0; } return 1; } /* * DeRegister a service */ int isns_slp_unregister(const char *url) { SLPError err, callbackerr; SLPHandle handle = NULL; isns_debug_general("SLP: Unregistering \"%s\"\n", url); err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return 0; } err = SLPDereg(handle, url, isns_slp_report, &callbackerr); SLPClose(handle); if (err == SLP_OK) err = callbackerr; if (err != SLP_OK) { isns_error("Failed to deregister with SLP (err %d)\n", err); return 0; } return 1; } /* * Find an iSNS server through SLP */ static SLPBoolean isns_slp_url_callback(SLPHandle handle, const char *url, unsigned short lifetime, SLPError err, void *cookie) { struct isns_slp_url_state *sp = cookie; SLPSrvURL *parsed_url = NULL; int want_more = SLP_TRUE; char buffer[1024]; if (err != SLP_OK && err != SLP_LAST_CALL) return SLP_FALSE; if (!url) goto out; isns_debug_general("SLP: Found URL \"%s\"\n", url); err = SLPParseSrvURL(url, &parsed_url); if (err != SLP_OK) { isns_error("Error parsing SLP service URL \"%s\"\n", url); goto out; } if (parsed_url->s_pcNetFamily && parsed_url->s_pcNetFamily[0] && strcasecmp(parsed_url->s_pcNetFamily, "ip")) { isns_error("Ignoring SLP service URL \"%s\"\n", url); goto out; } if (parsed_url->s_iPort) { snprintf(buffer, sizeof(buffer), "%s:%u", parsed_url->s_pcHost, parsed_url->s_iPort); isns_assign_string(&sp->slp_url, buffer); } else { isns_assign_string(&sp->slp_url, parsed_url->s_pcHost); } want_more = SLP_FALSE; out: if (parsed_url) SLPFree(parsed_url); sp->slp_err = SLP_OK; return want_more; } /* * Locate the iSNS server using SLP. * This is not really an instantaneous process. Maybe we could * speed this up by using a cache. */ char * isns_slp_find(void) { static struct isns_slp_url_state state; SLPHandle handle = NULL; SLPError err; if (state.slp_url) return state.slp_url; isns_debug_general("Using SLP to locate iSNS server\n"); err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return NULL; } err = SLPFindSrvs(handle, ISNS_SLP_SERVICE_NAME, NULL, "(protocols=isns)", isns_slp_url_callback, &state); SLPClose(handle); if (err == SLP_OK) err = state.slp_err; if (err != SLP_OK) { isns_error("Failed to find service in SLP (err %d)\n", err); return NULL; } if (state.slp_url == NULL) { isns_error("Service %s not registered with SLP\n", ISNS_SLP_SERVICE_NAME); return NULL; } isns_debug_general("Using iSNS server at %s\n", state.slp_url); return state.slp_url; } #else /* WITH_SLP */ int isns_slp_register(const char *url) { isns_error("SLP support disabled in this build\n"); return 0; } int isns_slp_unregister(const char *url) { isns_error("SLP support disabled in this build\n"); return 0; } char * isns_slp_find(void) { isns_error("SLP support disabled in this build\n"); return NULL; } #endif /* WITH_SLP */ char * isns_slp_build_url(uint16_t port) { char buffer[1024]; if (port) snprintf(buffer, sizeof(buffer), "service:%s://%s:%u", ISNS_SLP_SERVICE_NAME, isns_config.ic_host_name, port); else snprintf(buffer, sizeof(buffer), "service:%s://%s", ISNS_SLP_SERVICE_NAME, isns_config.ic_host_name); return isns_strdup(buffer); }
4,713
C
.c
197
21.543147
64
0.687989
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,497
config.c
cleech_open-isns/config.c
/* * Config file reader * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <libisns/isns.h> #include <libisns/util.h> #include <libisns/paths.h> /* * iSNS configuration */ struct isns_config isns_config = { /* Security parameters */ .ic_security = -1, .ic_auth_key_file = ISNS_ETCDIR "/auth_key", .ic_server_key_file = ISNS_ETCDIR "/server_key.pub", .ic_client_keystore = "DB:", .ic_control_socket = ISNS_RUNDIR "/isnsctl", .ic_pidfile = ISNS_RUNDIR "/isnsd.pid", .ic_local_registry_file = ISNS_DEFAULT_LOCAL_REGISTRY, .ic_control_name = "isns.control", .ic_control_key_file = ISNS_ETCDIR "/control.key", .ic_registration_period = 3600, /* 1 hour */ .ic_scn_timeout = 60, .ic_scn_retries = 3, .ic_esi_max_interval = 600, /* 10 minutes */ .ic_esi_min_interval = 60, /* 1 minute */ .ic_esi_retries = 3, .ic_auth = { .replay_window = 300, /* 5 min clock skew */ .timestamp_jitter = 1, /* 1 sec timestamp jitter */ .allow_unknown_peers = 1, }, .ic_network = { .max_sockets = 1024, .connect_timeout = 5, .reconnect_timeout = 10, .call_timeout = 60, .udp_retrans_timeout = 10, .tcp_retrans_timeout = 60, .idle_timeout = 300, }, .ic_dsa = { .param_file = ISNS_ETCDIR "/dsa.params", }, }; /* * Default string values need to be dup'ed, * so that later assignment does't try to free * these strings. */ static inline void __isns_config_defaults(void) { static int defaults_init = 1; if (!defaults_init) return; #define DUP(member) \ if (isns_config.member) \ isns_config.member = isns_strdup(isns_config.member) DUP(ic_source_name); DUP(ic_database); DUP(ic_server_name); DUP(ic_bind_address); DUP(ic_auth_key_file); DUP(ic_server_key_file); DUP(ic_client_keystore); DUP(ic_control_socket); DUP(ic_pidfile); DUP(ic_control_name); DUP(ic_control_key_file); DUP(ic_local_registry_file); DUP(ic_dsa.param_file); #undef DUP defaults_init = 0; } /* * read initiator name from supplied filename */ int isns_read_initiatorname(const char *filename) { FILE *fp; char *name, *pos; if ((fp = fopen(filename, "r")) == NULL) { perror(filename); return -1; } while ((pos = parser_get_next_line(fp)) != NULL) { pos[strcspn(pos, "#")] = '\0'; if (!(name = parser_get_next_word(&pos))) continue; if (strcmp(name, "InitiatorName")) continue; if (pos[0] == '=') pos++; if (!strncmp(pos, "iqn.", 4)) isns_assign_string(&isns_config.ic_source_name, pos); } fclose(fp); return 0; } /* * Read the iSNS configuration file */ int isns_read_config(const char *filename) { FILE *fp; char *name, *pos; __isns_config_defaults(); if ((fp = fopen(filename, "r")) == NULL) { perror(filename); return -1; } while ((pos = parser_get_next_line(fp)) != NULL) { pos[strcspn(pos, "#")] = '\0'; if (!(name = parser_get_next_word(&pos))) continue; isns_config_set(name, pos); } fclose(fp); /* Massage the config file */ if (isns_config.ic_security < 0) { /* By default, we will enable authentication * whenever we find our private key, and * the server's public key. */ if (access(isns_config.ic_auth_key_file, R_OK) == 0 && access(isns_config.ic_server_key_file, R_OK) == 0) isns_config.ic_security = 1; else isns_config.ic_security = 0; } return 0; } int isns_config_set(const char *name, char *pos) { char *value; value = parser_get_rest_of_line(&pos); if (value) while (isspace(*value) || *value == '=') ++value; if (!strcasecmp(name, "HostName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_host_name, value); } else if (!strcasecmp(name, "SourceName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_source_name, value); } else if (!strcasecmp(name, "AuthName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_auth_name, value); } else if (!strcasecmp(name, "IQNPrefix")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_iqn_prefix, value); } else if (!strcasecmp(name, "Database")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_database, value); } else if (!strcasecmp(name, "ServerAddress")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_server_name, value); } else if (!strcasecmp(name, "BindAddress")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_bind_address, value); } else if (!strcasecmp(name, "ControlSocket")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_socket, value); } else if (!strcasecmp(name, "PIDFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_pidfile, value); } else if (!strcasecmp(name, "LocalRegistry")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_local_registry_file, value); } else if (!strcasecmp(name, "RegistrationPeriod")) { if (!value) goto no_value; isns_config.ic_registration_period = parse_timeout(value); } else if (!strcasecmp(name, "SCNTimeout")) { if (!value) goto no_value; isns_config.ic_scn_timeout = parse_timeout(value); } else if (!strcasecmp(name, "SCNRetries")) { if (!value) goto no_value; isns_config.ic_scn_retries = parse_int(value); } else if (!strcasecmp(name, "SCNCallout")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_scn_callout, value); } else if (!strcasecmp(name, "ESIMinInterval")) { if (!value) goto no_value; isns_config.ic_esi_min_interval = parse_timeout(value); } else if (!strcasecmp(name, "ESIMaxInterval")) { if (!value) goto no_value; isns_config.ic_esi_max_interval = parse_timeout(value); } else if (!strcasecmp(name, "ESIRetries")) { if (!value) goto no_value; isns_config.ic_esi_retries = parse_int(value); } else if (!strcasecmp(name, "DefaultDiscoveryDomain")) { if (!value) goto no_value; isns_config.ic_use_default_domain = parse_int(value); } else if (!strcasecmp(name, "SLPRegister")) { if (!value) goto no_value; isns_config.ic_slp_register = parse_int(value); } else if (!strcasecmp(name, "Security")) { if (!value) goto no_value; isns_config.ic_security = parse_int(value); } else if (!strcasecmp(name, "AuthKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_auth_key_file, value); } else if (!strcasecmp(name, "ServerKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_server_key_file, value); } else if (!strcasecmp(name, "ClientKeyStore") || !strcasecmp(name, "KeyStore")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_client_keystore, value); } else if (!strcasecmp(name, "Control.SourceName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_name, value); } else if (!strcasecmp(name, "Control.AuthKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_key_file, value); } else if (!strcasecmp(name, "Auth.ReplayWindow")) { if (!value) goto no_value; isns_config.ic_auth.replay_window = parse_timeout(value); } else if (!strcasecmp(name, "Auth.TimestampJitter")) { if (!value) goto no_value; isns_config.ic_auth.timestamp_jitter = parse_timeout(value); } else if (!strcasecmp(name, "Network.MaxSockets")) { if (!value) goto no_value; isns_config.ic_network.max_sockets = parse_timeout(value); } else if (!strcasecmp(name, "Network.ConnectTimeout")) { if (!value) goto no_value; isns_config.ic_network.connect_timeout = parse_timeout(value); } else if (!strcasecmp(name, "Network.ReconnectTimeout")) { if (!value) goto no_value; isns_config.ic_network.reconnect_timeout = parse_timeout(value); } else if (!strcasecmp(name, "Network.CallTimeout")) { if (!value) goto no_value; isns_config.ic_network.call_timeout = parse_timeout(value); } else { fprintf(stderr, "Unknown config item %s=%s\n", name, value); } return 0; no_value: fprintf(stderr, "*** Missing value in configuration assignment for %s ***\n", name); return -1; }
8,163
C
.c
282
26.326241
66
0.679317
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,498
dd.c
cleech_open-isns/dd.c
/* * Handle DD registration/deregistration * * Discovery domains are weird, even in the context of * iSNS. For one thing, all other objects have unique * attributes; DDs attributes can appear several times. * They should really have made each DD member an object * in its own right. * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include "objects.h" #include <libisns/message.h> #include "security.h" #include <libisns/util.h> #include "db.h" #define DD_DEBUG enum { ISNS_DD_MEMBER_ISCSI_NODE = 1, ISNS_DD_MEMBER_IFCP_NODE, ISNS_DD_MEMBER_PORTAL, }; /* Must be zero/one: */ enum { NOTIFY_MEMBER_ADDED = 0, NOTIFY_MEMBER_REMOVED = 1 }; typedef struct isns_dd isns_dd_t; typedef struct isns_dd_list isns_dd_list_t; typedef struct isns_dd_member isns_dd_member_t; struct isns_dd { uint32_t dd_id; char * dd_name; uint32_t dd_features; isns_dd_member_t * dd_members; unsigned int dd_inserted : 1; isns_object_t * dd_object; }; struct isns_dd_member { isns_dd_member_t * ddm_next; unsigned int ddm_type; isns_object_ref_t ddm_object; unsigned int ddm_added : 1; union { uint32_t ddm_index; /* Index must be first in all structs below. * Yeah, I know. Aliasing is bad. */ struct isns_dd_portal { uint32_t index; isns_portal_info_t info; } ddm_portal; struct isns_dd_iscsi_node { uint32_t index; char * name; } ddm_iscsi_node; struct isns_dd_ifcp_node { uint32_t index; char * name; } ddm_ifcp_node; }; }; struct isns_dd_list { unsigned int ddl_count; isns_dd_t ** ddl_data; }; /* * List of all discovery domains. * This duplicates the DD information from the database, * but unfortunately this can't be helped - we need to * have fast algorithms to compute the membership of a * node, and the relative visibility of two nodes. */ static int isns_dd_list_initialized = 0; static isns_dd_list_t isns_dd_list; static uint32_t isns_dd_next_id = 1; static isns_dd_t * isns_dd_alloc(void); static isns_dd_t * isns_dd_clone(const isns_dd_t *); static void isns_dd_release(isns_dd_t *); static int isns_dd_parse_attrs(isns_dd_t *, isns_db_t *, const isns_attr_list_t *, const isns_dd_t *, int); static int isns_dd_remove_members(isns_dd_t *, isns_db_t *, isns_dd_t *); static void isns_dd_notify(const isns_dd_t *, isns_dd_member_t *, isns_dd_member_t *, int); static void isns_dd_add_members(isns_dd_t *, isns_db_t *, isns_dd_t *); static void isns_dd_store(isns_db_t *, const isns_dd_t *, int); static void isns_dd_destroy(isns_db_t *, isns_dd_t *); static void isns_dd_insert(isns_dd_t *); static isns_dd_t * isns_dd_by_id(uint32_t); static isns_dd_t * isns_dd_by_name(const char *); static isns_dd_member_t * isns_dd_create_member(isns_object_t *); static inline void isns_dd_member_free(isns_dd_member_t *); static int isns_dd_remove_member(isns_dd_t *, isns_object_t *); static void isns_dd_list_resize(isns_dd_list_t *, unsigned int); static void isns_dd_list_insert(isns_dd_list_t *, isns_dd_t *); static void isns_dd_list_remove(isns_dd_list_t *, isns_dd_t *); static isns_object_t * isns_dd_get_member_object(isns_db_t *, const isns_attr_t *, const isns_attr_t *, int); /* * Create DDReg messages */ isns_simple_t * isns_create_dd_registration(isns_client_t *clnt, const isns_attr_list_t *attrs) { isns_simple_t *msg; isns_attr_t *id_attr; msg = isns_simple_create(ISNS_DD_REGISTER, clnt->ic_source, NULL); if (msg == NULL) return NULL; /* If the caller specified a DD_ID, use it in the * message key. */ if (isns_attr_list_get_attr(attrs, ISNS_TAG_DD_ID, &id_attr)) isns_attr_list_append_attr(&msg->is_message_attrs, id_attr); isns_attr_list_copy(&msg->is_operating_attrs, attrs); return msg; } isns_simple_t * isns_create_dd_deregistration(isns_client_t *clnt, uint32_t dd_id, const isns_attr_list_t *attrs) { isns_simple_t *msg; msg = isns_simple_create(ISNS_DD_DEREGISTER, clnt->ic_source, NULL); if (msg == NULL) return NULL; isns_attr_list_append_uint32(&msg->is_message_attrs, ISNS_TAG_DD_ID, dd_id); isns_attr_list_copy(&msg->is_operating_attrs, attrs); return msg; } /* * Process a DD registration */ int isns_process_dd_registration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_attr_t *attr; uint32_t id = 0; int status; /* * 5.6.5.9. * The Message Key, if used, contains the DD_ID of the Discovery * Domain to be registered. If the Message Key contains a DD_ID * of an existing DD entry in the iSNS database, then the DDReg * message SHALL attempt to update the existing entry. If the * DD_ID in the Message Key (if used) does not match an existing * DD entry, then the iSNS server SHALL reject the DDReg message * with a status code of 3 (Invalid Registration). */ switch (keys->ial_count) { case 0: /* Security: check if the client is allowed to * create a discovery domain */ if (!isns_policy_validate_object_creation(call->is_policy, call->is_source, &isns_dd_template, keys, attrs, call->is_function)) goto unauthorized; break; case 1: attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_DD_ID) goto reject; if (ISNS_ATTR_IS_NIL(attr)) break; if (!ISNS_ATTR_IS_UINT32(attr)) goto reject; id = attr->ia_value.iv_uint32; if (id == 0) goto reject; dd = isns_dd_by_id(id); if (dd == NULL) { isns_debug_state("DDReg for unknown ID=%u\n", id); goto reject; } /* Security: check if the client is allowed to * mess with this DD. */ isns_assert(dd->dd_object); if (!isns_policy_validate_object_update(call->is_policy, call->is_source, dd->dd_object, attrs, call->is_function)) goto unauthorized; break; default: goto reject; } temp_dd = isns_dd_alloc(); /* Parse the attributes and build a DD object. */ status = isns_dd_parse_attrs(temp_dd, db, attrs, dd, 1); if (status != ISNS_SUCCESS) goto out; if (dd == NULL) { /* Create the DD, and copy the general information * such asn features and symbolic name from temp_dd */ dd = isns_dd_clone(temp_dd); /* Don't assign the attrs to the DD right away. * First and foremost, they may be unsorted. Second, * we really want to hand-pick through them due to * the weird semantics mandated by the RFC. */ dd->dd_object = isns_create_object(&isns_dd_template, NULL, NULL); if (dd->dd_object == NULL) goto reject; /* Insert new domain into database */ isns_db_insert(db, dd->dd_object); /* Add it to the internal list. Assign DD_ID and * symbolic name if none were given. */ isns_dd_insert(dd); } else { if (!dd->dd_id) dd->dd_id = temp_dd->dd_id; dd->dd_features = temp_dd->dd_features; isns_assign_string(&dd->dd_name, temp_dd->dd_name); } /* Send notifications. This must be done before merging * the list of new members into the DD. */ isns_dd_notify(dd, dd->dd_members, temp_dd->dd_members, NOTIFY_MEMBER_ADDED); /* Update the DD */ isns_dd_add_members(dd, db, temp_dd); /* And add it to the database. */ isns_dd_store(db, dd, 0); reply = isns_simple_create(ISNS_DD_REGISTER, srv->is_source, NULL); isns_object_extract_all(dd->dd_object, &reply->is_operating_attrs); status = ISNS_SUCCESS; out: isns_dd_release(temp_dd); isns_dd_release(dd); *result = reply; return status; reject: status = ISNS_INVALID_REGISTRATION; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Process a DD deregistration */ int isns_process_dd_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_attr_t *attr; uint32_t id = 0; int status; /* * 5.6.5.10. * The Message Key Attribute for a DDDereg message is the DD * ID for the Discovery Domain being removed or having members * removed. */ if (keys->ial_count != 1) goto reject; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_DD_ID || ISNS_ATTR_IS_NIL(attr) || !ISNS_ATTR_IS_UINT32(attr)) goto reject; id = attr->ia_value.iv_uint32; if (id == 0) goto reject; dd = isns_dd_by_id(id); if (dd == NULL) goto reject; /* Security: check if the client is permitted to * modify the DD object. */ if (!isns_policy_validate_object_update(call->is_policy, call->is_source, dd->dd_object, attrs, call->is_function)) goto unauthorized; /* * 5.6.5.10. * If the DD ID matches an existing DD and there are * no Operating Attributes, then the DD SHALL be removed and a * success Status Code returned. Any existing members of that * DD SHALL remain in the iSNS database without membership in * the just-removed DD. */ if (attrs->ial_count == 0) { isns_dd_member_t *mp; /* Zap the membership bit */ for (mp = dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; isns_object_clear_membership(obj, dd->dd_id); } /* Notify all DD members that they will lose the other * nodes. */ isns_dd_notify(dd, NULL, dd->dd_members, NOTIFY_MEMBER_REMOVED); isns_dd_destroy(db, dd); } else { /* Parse the attributes and build a temporary DD object. */ temp_dd = isns_dd_alloc(); status = isns_dd_parse_attrs(temp_dd, db, attrs, dd, 0); if (status != ISNS_SUCCESS) goto out; /* Update the DD object */ status = isns_dd_remove_members(dd, db, temp_dd); if (status != ISNS_SUCCESS) goto out; /* Send notifications. This must be done before * updating the DD. */ isns_dd_notify(dd, dd->dd_members, temp_dd->dd_members, NOTIFY_MEMBER_REMOVED); /* Store it in the database. */ isns_dd_store(db, dd, 1); } reply = isns_simple_create(ISNS_DD_DEREGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: isns_dd_release(temp_dd); isns_dd_release(dd); *result = reply; return status; reject: status = ISNS_INVALID_DEREGISTRATION; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } static isns_dd_t * isns_dd_alloc(void) { return isns_calloc(1, sizeof(isns_dd_t)); } /* * Allocate a clone of the orig_dd, but without * copying the members. */ static isns_dd_t * isns_dd_clone(const isns_dd_t *orig_dd) { isns_dd_t *dd; dd = isns_dd_alloc(); dd->dd_id = orig_dd->dd_id; dd->dd_features = orig_dd->dd_features; dd->dd_object = isns_object_get(orig_dd->dd_object); isns_assign_string(&dd->dd_name, orig_dd->dd_name); return dd; } static void isns_dd_release(isns_dd_t *dd) { isns_dd_member_t *member; if (dd == NULL || dd->dd_inserted) return; while ((member = dd->dd_members) != NULL) { dd->dd_members = member->ddm_next; isns_dd_member_free(member); } if (dd->dd_object) isns_object_release(dd->dd_object); isns_free(dd->dd_name); isns_free(dd); } static isns_dd_member_t * isns_dd_create_member(isns_object_t *obj) { isns_dd_member_t *new; new = isns_calloc(1, sizeof(*new)); new->ddm_added = 1; if (ISNS_IS_ISCSI_NODE(obj)) new->ddm_type = ISNS_DD_MEMBER_ISCSI_NODE; else if (ISNS_IS_PORTAL(obj)) new->ddm_type = ISNS_DD_MEMBER_PORTAL; else if (ISNS_IS_FC_NODE(obj)) new->ddm_type = ISNS_DD_MEMBER_IFCP_NODE; else { isns_free(new); return NULL; } isns_object_reference_set(&new->ddm_object, obj); return new; } static inline void isns_dd_member_free(isns_dd_member_t *member) { switch (member->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: isns_free(member->ddm_iscsi_node.name); break; case ISNS_DD_MEMBER_IFCP_NODE: isns_free(member->ddm_ifcp_node.name); break; } isns_object_reference_drop(&member->ddm_object); isns_free(member); } void isns_dd_get_members(uint32_t dd_id, isns_object_list_t *list, int active_only) { isns_dd_t *dd; isns_dd_member_t *mp; dd = isns_dd_by_id(dd_id); if (dd == NULL) return; for (mp = dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; if (active_only && obj->ie_state != ISNS_OBJECT_STATE_MATURE) continue; isns_object_list_append(list, obj); } } /* * Helper function to remove a member referencing the given object */ static int isns_dd_remove_member(isns_dd_t *dd, isns_object_t *obj) { isns_dd_member_t *mp, **pos; pos = &dd->dd_members; while ((mp = *pos) != NULL) { if (mp->ddm_object.obj == obj) { *pos = mp->ddm_next; isns_dd_member_free(mp); return 1; } else { pos = &mp->ddm_next; } } return 0; } static void isns_dd_insert(isns_dd_t *dd) { if (dd->dd_inserted) return; if (dd->dd_id == 0) { uint32_t id = isns_dd_next_id; unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *cur = isns_dd_list.ddl_data[i]; if (cur->dd_id > id) break; if (cur->dd_id == id) ++id; } isns_debug_state("Allocated new DD_ID %d\n", id); dd->dd_id = id; isns_dd_next_id = id + 1; } /* * When creating a new DD, if the DD_Symbolic_Name is * not included in the Operating Attributes, or if it * is included with a zero-length TLV, then the iSNS * server SHALL provide a unique DD_Symbolic_Name value * for the created DD. The assigned DD_Symbolic_Name * value SHALL be returned in the DDRegRsp message. */ if (dd->dd_name == NULL) { char namebuf[64]; snprintf(namebuf, sizeof(namebuf), "isns.dd%u", dd->dd_id); isns_assign_string(&dd->dd_name, namebuf); } isns_dd_list_insert(&isns_dd_list, dd); dd->dd_inserted = 1; #ifdef DD_DEBUG /* Safety first - make sure domains are sorted by DD_ID */ { unsigned int i, prev_id = 0; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *cur = isns_dd_list.ddl_data[i]; isns_assert(cur->dd_id > prev_id); prev_id = cur->dd_id; } } #endif } /* * Resize the DD list */ #define LIST_SIZE(n) (((n) + 15) & ~15) void isns_dd_list_resize(isns_dd_list_t *list, unsigned int last_index) { unsigned int new_size; isns_dd_t **new_data; new_size = LIST_SIZE(last_index + 1); if (new_size < list->ddl_count) return; /* We don't use realloc here because we need * to zero the new pointers anyway. */ new_data = isns_calloc(new_size, sizeof(void *)); isns_assert(new_data); memcpy(new_data, list->ddl_data, list->ddl_count * sizeof(void *)); isns_free(list->ddl_data); list->ddl_data = new_data; list->ddl_count = last_index + 1; } /* * Find the insert position for a given DD ID. * returns true iff the DD was found in the list. */ static int __isns_dd_list_find_pos(isns_dd_list_t *list, unsigned int id, unsigned int *where) { unsigned int hi, lo, md; lo = 0; hi = list->ddl_count; /* binary search */ while (lo < hi) { isns_dd_t *cur; md = (lo + hi) / 2; cur = list->ddl_data[md]; if (id == cur->dd_id) { *where = md; return 1; } if (id < cur->dd_id) { hi = md; } else { lo = md + 1; } } *where = hi; return 0; } /* * In-order insert */ static void isns_dd_list_insert(isns_dd_list_t *list, isns_dd_t *dd) { unsigned int pos; if (__isns_dd_list_find_pos(list, dd->dd_id, &pos)) { isns_error("Internal error in %s: DD already listed\n", __FUNCTION__); return; } isns_dd_list_resize(list, list->ddl_count); /* Shift the tail of the list to make room for new entry. */ memmove(list->ddl_data + pos + 1, list->ddl_data + pos, (list->ddl_count - pos - 1) * sizeof(void *)); list->ddl_data[pos] = dd; } /* * Remove DD from list */ void isns_dd_list_remove(isns_dd_list_t *list, isns_dd_t *dd) { unsigned int pos; if (!__isns_dd_list_find_pos(list, dd->dd_id, &pos)) return; /* Shift the tail of the list */ memmove(list->ddl_data + pos, list->ddl_data + pos + 1, (list->ddl_count - pos - 1) * sizeof(void *)); list->ddl_count -= 1; } isns_dd_t * isns_dd_by_id(uint32_t id) { unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *dd = isns_dd_list.ddl_data[i]; if (dd && dd->dd_id == id) return dd; } return NULL; } static isns_dd_t * isns_dd_by_name(const char *name) { unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *dd = isns_dd_list.ddl_data[i]; if (dd && !strcmp(dd->dd_name, name)) return dd; } return NULL; } /* * Validate the operating attributes, which is surprisingly * tedious for DDs. It appears as if the whole DD/DDset * stuff has been slapped onto iSNS as an afterthought. * * DDReg has some funky rules about how eg iSCSI nodes * can be identified by either name or index, and how they * relate to each other. Unfortunately, the RFC is very vague * in describing how to treat DDReg message that mix these * two types of identification, except by saying they * need to be consistent. */ static int isns_dd_parse_attrs(isns_dd_t *dd, isns_db_t *db, const isns_attr_list_t *attrs, const isns_dd_t *orig_dd, int is_registration) { isns_dd_member_t **tail; const isns_dd_t *conflict; unsigned int i; int rv = ISNS_SUCCESS; if (orig_dd) { dd->dd_id = orig_dd->dd_id; dd->dd_features = orig_dd->dd_features; isns_assign_string(&dd->dd_name, orig_dd->dd_name); } isns_assert(dd->dd_members == NULL); tail = &dd->dd_members; for (i = 0; i < attrs->ial_count; ++i) { isns_object_t *obj = NULL; isns_attr_t *attr, *next = NULL; const char *name; uint32_t id; attr = attrs->ial_data[i]; if (!isns_object_attr_valid(&isns_dd_template, attr->ia_tag_id)) return ISNS_INVALID_REGISTRATION; switch (attr->ia_tag_id) { case ISNS_TAG_DD_ID: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * 5.6.5.9. * A DDReg message with no Message Key SHALL result * in the attempted creation of a new Discovery Domain * (DD). If the DD_ID attribute (with non-zero length) * is included among the Operating Attributes in the * DDReg message, then the new Discovery Domain SHALL be * assigned the value contained in that DD_ID attribute. * * If the DD_ID is included in both the Message * Key and Operating Attributes, then the DD_ID * value in the Message Key MUST be the same as * the DD_ID value in the Operating Attributes. * * Implementer's note: It's not clear why the standard * makes an exception for the DD_ID, while all other * index attributes are read-only. */ if (ISNS_ATTR_IS_NIL(attr)) break; id = attr->ia_value.iv_uint32; if (dd->dd_id != 0) { if (dd->dd_id != id) goto invalid; } else if ((conflict = isns_dd_by_id(id)) != NULL) { isns_debug_state("DDReg: requested ID %d " "clashes with existing DD (%s)\n", id, conflict->dd_name); goto invalid; } dd->dd_id = id; break; case ISNS_TAG_DD_SYMBOLIC_NAME: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * If the DD_Symbolic_Name is an operating * attribute and its value is unique (i.e., it * does not match the registered DD_Symbolic_Name * for another DD), then the value SHALL be stored * in the iSNS database as the DD_Symbolic_Name * for the specified Discovery Domain. If the * value for the DD_Symbolic_Name is not unique, * then the iSNS server SHALL reject the attempted * DD registration with a status code of 3 * (Invalid Registration). */ if (ISNS_ATTR_IS_NIL(attr)) break; name = attr->ia_value.iv_string; if (dd->dd_name && strcmp(name, dd->dd_name)) { isns_debug_state("DDReg: symbolic name conflict: " "id=%d name=%s requested=%s\n", dd->dd_id, dd->dd_name, name); goto invalid; } if (dd->dd_name) break; if ((conflict = isns_dd_by_name(name)) != NULL) { isns_debug_state("DDReg: requested symbolic name (%s) " "clashes with existing DD (id=%d)\n", name, conflict->dd_id); goto invalid; } isns_assign_string(&dd->dd_name, name); break; case ISNS_TAG_DD_FEATURES: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * When creating a new DD, if the DD_Features * attribute is not included in the Operating * Attributes, then the iSNS server SHALL assign * the default value. The default value for * DD_Features is 0. */ if (ISNS_ATTR_IS_UINT32(attr)) dd->dd_features = attr->ia_value.iv_uint32; break; case ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR: /* portal address must be followed by port */ if (i + 1 >= attrs->ial_count) goto invalid; next = attrs->ial_data[i + 1]; if (next->ia_tag_id != ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT) goto invalid; i += 1; /* fallthru to normal case */ case ISNS_TAG_DD_MEMBER_PORTAL_INDEX: case ISNS_TAG_DD_MEMBER_ISCSI_INDEX: case ISNS_TAG_DD_MEMBER_ISCSI_NAME: case ISNS_TAG_DD_MEMBER_FC_PORT_NAME: if (ISNS_ATTR_IS_NIL(attr)) goto invalid; obj = isns_dd_get_member_object(db, attr, next, is_registration); /* For a DD deregistration, it's okay if the * object does not exist. */ if (obj == NULL && is_registration) goto invalid; break; invalid: rv = ISNS_INVALID_REGISTRATION; continue; } if (obj) { if (is_registration && isns_object_test_membership(obj, dd->dd_id)) { /* Duplicates are ignored */ isns_debug_state("Ignoring duplicate DD registration " "for %s %u\n", obj->ie_template->iot_name, obj->ie_index); } else { /* This just adds the member to the temporary DD object, * without changing any state in the database. */ isns_dd_member_t *new; new = isns_dd_create_member(obj); if (new) { *tail = new; tail = &new->ddm_next; } /* mark this object as a member of this DD */ isns_object_mark_membership(obj, dd->dd_id); } isns_object_release(obj); } } return rv; } /* * Helper function: extract live nodes from the DD member list */ static inline void isns_dd_get_member_nodes(isns_dd_member_t *members, isns_object_list_t *result) { isns_dd_member_t *mp; /* Extract iSCSI nodes from both list. */ for (mp = members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; if (ISNS_IS_ISCSI_NODE(obj) && obj->ie_state == ISNS_OBJECT_STATE_MATURE) isns_object_list_append(result, obj); } } void isns_dd_notify(const isns_dd_t *dd, isns_dd_member_t *unchanged, isns_dd_member_t *changed, int removed) { isns_object_list_t dd_objects = ISNS_OBJECT_LIST_INIT; isns_object_list_t changed_objects = ISNS_OBJECT_LIST_INIT; unsigned int i, j, event; /* Extract iSCSI nodes from both list. */ isns_dd_get_member_nodes(unchanged, &dd_objects); isns_dd_get_member_nodes(changed, &changed_objects); /* Send a management SCN multicast to all * control nodes that care. */ event = removed? ISNS_SCN_DD_MEMBER_REMOVED_MASK : ISNS_SCN_DD_MEMBER_ADDED_MASK; for (i = 0; i < changed_objects.iol_count; ++i) { isns_object_t *obj = changed_objects.iol_data[i]; isns_object_event(obj, event | ISNS_SCN_MANAGEMENT_REGISTRATION_MASK, dd->dd_object); } #ifdef notagoodidea /* Not sure - it may be good to send OBJECT ADDED/REMOVED instead * of the DD membership messages. However, right now the SCN code * will nuke all SCN registrations for a node when it sees a * REMOVE event for it. */ event = removed? ISNS_SCN_OBJECT_REMOVED_MASK : ISNS_SCN_OBJECT_ADDED_MASK; #endif /* If we added an iscsi node, loop over all members * and send unicast events to each iscsi node, * informing them that a new member has been added/removed. */ for (j = 0; j < changed_objects.iol_count; ++j) { isns_object_t *changed = changed_objects.iol_data[j]; for (i = 0; i < dd_objects.iol_count; ++i) { isns_object_t *obj = dd_objects.iol_data[i]; /* For member removal, do not send notifications * if the two nodes are still visible to each * other through a different discovery domain */ if (removed && isns_object_test_visibility(obj, changed)) continue; /* Inform the old node that the new node was * added/removed. */ isns_unicast_event(obj, changed, event, NULL); /* Inform the new node that the old node became * (in)accessible to it. */ isns_unicast_event(changed, obj, event, NULL); } /* Finally, inform each changed node of the other * DD members that became (in)accessible to it. */ for (i = 0; i < changed_objects.iol_count; ++i) { isns_object_t *obj = changed_objects.iol_data[i]; if (obj == changed) continue; if (removed && isns_object_test_visibility(obj, changed)) continue; isns_unicast_event(changed, obj, event, NULL); } } } void isns_dd_add_members(isns_dd_t *dd, isns_db_t *db, isns_dd_t *new_dd) { isns_dd_member_t *mp, **tail; for (mp = new_dd->dd_members; mp; mp = mp->ddm_next) { const char *node_name; isns_object_t *obj = mp->ddm_object.obj; /* * If the Operating Attributes contain a DD * Member iSCSI Name value for a Storage Node * that is currently not registered in the iSNS * database, then the iSNS server MUST allocate an * unused iSCSI Node Index for that Storage Node. * The assigned iSCSI Node Index SHALL be returned * in the DDRegRsp message as the DD Member iSCSI * Node Index. The allocated iSCSI Node Index * value SHALL be assigned to the Storage Node * if and when it registers in the iSNS database. * [And likewise for portals] */ if (obj->ie_index == 0) isns_db_insert_limbo(db, obj); mp->ddm_index = obj->ie_index; /* Record the fact that the object is a member of this DD */ isns_object_mark_membership(obj, dd->dd_id); switch (mp->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: if (isns_object_get_string(obj, ISNS_TAG_ISCSI_NAME, &node_name)) isns_assign_string(&mp->ddm_iscsi_node.name, node_name); break; case ISNS_DD_MEMBER_IFCP_NODE: if (isns_object_get_string(obj, ISNS_TAG_FC_PORT_NAME_WWPN, &node_name)) isns_assign_string(&mp->ddm_ifcp_node.name, node_name); break; case ISNS_DD_MEMBER_PORTAL: isns_portal_from_object(&mp->ddm_portal.info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, obj); break; } } /* Find the tail of the DD member list */ tail = &dd->dd_members; while ((mp = *tail) != NULL) tail = &mp->ddm_next; /* Append the new list of members */ *tail = new_dd->dd_members; new_dd->dd_members = NULL; } /* * Remove members from a DD */ int isns_dd_remove_members(isns_dd_t *dd, isns_db_t *db, isns_dd_t *temp_dd) { isns_dd_member_t *mp; for (mp = temp_dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; /* Clear the membership bit. If the object wasn't in this * DD to begin with, bail out right away. */ if (!isns_object_clear_membership(obj, dd->dd_id)) { isns_debug_state("DD dereg: object %d is not in this DD\n", obj->ie_index); continue; } if (!isns_dd_remove_member(dd, obj)) isns_error("%s: DD member not found in internal list\n", __FUNCTION__); } return ISNS_SUCCESS; } void isns_dd_store(isns_db_t *db, const isns_dd_t *dd, int rewrite) { isns_object_t *obj = dd->dd_object; isns_dd_member_t *member; if (rewrite) isns_object_prune_attrs(obj); isns_object_set_uint32(obj, ISNS_TAG_DD_ID, dd->dd_id); isns_object_set_string(obj, ISNS_TAG_DD_SYMBOLIC_NAME, dd->dd_name); isns_object_set_uint32(obj, ISNS_TAG_DD_FEATURES, dd->dd_features); for (member = dd->dd_members; member; member = member->ddm_next) { struct isns_dd_iscsi_node *node; struct isns_dd_portal *portal; if (!member->ddm_added && !rewrite) continue; switch (member->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: node = &member->ddm_iscsi_node; isns_object_set_uint32(obj, ISNS_TAG_DD_MEMBER_ISCSI_INDEX, node->index); if (node->name) isns_object_set_string(obj, ISNS_TAG_DD_MEMBER_ISCSI_NAME, node->name); break; case ISNS_DD_MEMBER_PORTAL: portal = &member->ddm_portal; isns_object_set_uint32(obj, ISNS_TAG_DD_MEMBER_PORTAL_INDEX, portal->index); if (portal->info.addr.sin6_family != AF_UNSPEC) { isns_portal_to_object(&portal->info, ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR, ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT, obj); } break; } member->ddm_added = 0; } } /* * Destroy a DD * The caller should call isns_dd_release to free the DD object. */ void isns_dd_destroy(isns_db_t *db, isns_dd_t *dd) { isns_db_remove(db, dd->dd_object); isns_dd_list_remove(&isns_dd_list, dd); dd->dd_inserted = 0; } int isns_dd_load_all(isns_db_t *db) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; unsigned int i; int rc; if (isns_dd_list_initialized) return ISNS_SUCCESS; rc = isns_db_gang_lookup(db, &isns_dd_template, NULL, &list); if (rc != ISNS_SUCCESS) return rc; for (i = 0; i < list.iol_count; ++i) { isns_object_t *obj = list.iol_data[i]; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_dd_member_t *mp; temp_dd = isns_dd_alloc(); rc = isns_dd_parse_attrs(temp_dd, db, &obj->ie_attrs, NULL, 1); if (rc) { if (temp_dd->dd_id == 0) { isns_error("Problem converting DD object (index 0x%x). No DD_ID\n", obj->ie_index); goto next; } isns_error("Problem converting DD %u. Proceeding anyway.\n", temp_dd->dd_id); } else { isns_debug_state("Loaded DD %d from database\n", temp_dd->dd_id); } dd = isns_dd_clone(temp_dd); /* * XXX duplicate call? isns_object_get() is already called * at the end of isns_dd_clone() */ dd->dd_object = isns_object_get(obj); isns_dd_insert(dd); isns_dd_add_members(dd, db, temp_dd); /* Clear the ddm_added flag for all members, to * prevent all information from being duplicated * to the DB on the next DD modification. */ for (mp = dd->dd_members; mp; mp = mp->ddm_next) mp->ddm_added = 0; next: isns_dd_release(temp_dd); } isns_object_list_destroy(&list); isns_dd_list_initialized = 1; return ISNS_SUCCESS; } isns_object_t * isns_dd_get_member_object(isns_db_t *db, const isns_attr_t *key1, const isns_attr_t *key2, int create) { isns_attr_list_t query = ISNS_ATTR_LIST_INIT; isns_object_template_t *tmpl = NULL; isns_object_t *obj; isns_portal_info_t portal_info; char *key_string = NULL; uint32_t key_index = 0; switch (key1->ia_tag_id) { case ISNS_TAG_DD_MEMBER_ISCSI_INDEX: key_index = key1->ia_value.iv_uint32; isns_attr_list_append_uint32(&query, ISNS_TAG_ISCSI_NODE_INDEX, key_index); tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_DD_MEMBER_ISCSI_NAME: key_string = key1->ia_value.iv_string; isns_attr_list_append_string(&query, ISNS_TAG_ISCSI_NAME, key_string); tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_DD_MEMBER_FC_PORT_NAME: key_string = key1->ia_value.iv_string; isns_attr_list_append_string(&query, ISNS_TAG_FC_PORT_NAME_WWPN, key_string); tmpl = &isns_fc_port_template; break; case ISNS_TAG_DD_MEMBER_PORTAL_INDEX: key_index = key1->ia_value.iv_uint32; isns_attr_list_append_uint32(&query, ISNS_TAG_PORTAL_INDEX, key_index); tmpl = &isns_portal_template; break; case ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR: if (!isns_portal_from_attr_pair(&portal_info, key1, key2) || !isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, &query)) return NULL; key_string = isns_portal_string(&portal_info); tmpl = &isns_portal_template; break; default: return NULL; } obj = isns_db_lookup(db, tmpl, &query); if (!obj && create) { if (!key_string) { isns_debug_state("Attempt to register %s DD member " "with unknown index %u\n", tmpl->iot_name, key_index); goto out; } obj = isns_create_object(tmpl, &query, NULL); if (obj != NULL) isns_debug_state("Created limbo object for " "%s DD member %s\n", tmpl->iot_name, key_string); } out: isns_attr_list_destroy(&query); if (key_string) free(key_string); return obj; }
32,522
C
.c
1,100
26.492727
95
0.67517
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,500
client.c
cleech_open-isns/client.c
/* * Client functions * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <unistd.h> #include "config.h" #include <libisns/isns.h> #include "security.h" #include <libisns/util.h> #include "internal.h" static isns_client_t * __isns_create_default_client(isns_socket_t *sock, isns_security_t *ctx, const char *source_name) { isns_client_t *clnt; clnt = isns_calloc(1, sizeof(*clnt)); if (!source_name) source_name = isns_config.ic_source_name; clnt->ic_source = isns_source_create_iscsi(source_name); clnt->ic_socket = sock; isns_socket_set_security_ctx(clnt->ic_socket, ctx); return clnt; } isns_client_t * isns_create_client(isns_security_t *ctx, const char *source_name) { isns_socket_t *sock; const char *server_name; server_name = isns_config.ic_server_name; if (!server_name) return NULL; if (!strcasecmp(server_name, "SLP:") && !(server_name = isns_slp_find())) { isns_error("Unable to locate iSNS server through SLP\n"); return NULL; } sock = isns_create_bound_client_socket( isns_config.ic_bind_address, server_name, "isns", 0, SOCK_STREAM); if (sock == NULL) { isns_error("Unable to create socket for host \"%s\"\n", isns_config.ic_server_name); return NULL; } return __isns_create_default_client(sock, ctx? : isns_default_security_context(0), source_name); } isns_client_t * isns_create_default_client(isns_security_t *ctx) { return isns_create_client(ctx, isns_config.ic_source_name); } isns_client_t * isns_create_local_client(isns_security_t *ctx, const char *source_name) { isns_socket_t *sock; if (isns_config.ic_control_socket == NULL) isns_fatal("Cannot use local mode: no local control socket\n"); sock = isns_create_client_socket(isns_config.ic_control_socket, NULL, 0, SOCK_STREAM); if (sock == NULL) { isns_error("Unable to create control socket (%s)\n", isns_config.ic_control_socket); return NULL; } return __isns_create_default_client(sock, ctx, source_name); } int isns_client_call(isns_client_t *clnt, isns_simple_t **inout) { return isns_simple_call(clnt->ic_socket, inout); } void isns_client_destroy(isns_client_t *clnt) { if (clnt->ic_socket) isns_socket_free(clnt->ic_socket); if (clnt->ic_source) isns_source_release(clnt->ic_source); isns_free(clnt); } /* * Get the local address */ int isns_client_get_local_address(const isns_client_t *clnt, isns_portal_info_t *portal_info) { return isns_socket_get_portal_info(clnt->ic_socket, portal_info); } /* * Create a security context */ static isns_security_t * __create_security_context(const char *name, const char *auth_key, const char *server_key) { #ifdef WITH_SECURITY isns_security_t *ctx; isns_principal_t *princ; #endif /* WITH_SECURITY */ if (!isns_config.ic_security) return NULL; #ifndef WITH_SECURITY isns_error("Cannot create security context: security disabled at build time\n"); return NULL; #else /* WITH_SECURITY */ ctx = isns_create_dsa_context(); if (ctx == NULL) isns_fatal("Unable to create security context\n"); /* Load my own key */ princ = isns_security_load_privkey(ctx, auth_key); if (!princ) isns_fatal("Unable to load private key from %s\n", auth_key); isns_principal_set_name(princ, name); isns_security_set_identity(ctx, princ); if (server_key) { /* We're a client, and we want to load the * server's public key in order to authenticate * the server's responses. */ princ = isns_security_load_pubkey(ctx, server_key); if (!princ) isns_fatal("Unable to load public key from %s\n", server_key); /* Do *not* set a name for this principal - * this will be the default principal used when * verifying the server's reply, which is a good thing * because we don't know what SPI the server will * be using. */ isns_add_principal(ctx, princ); /* But set a policy for the server which allows it to send ESI and SCN messages */ isns_principal_set_policy(princ, isns_policy_server()); } return ctx; #endif /* WITH_SECURITY */ } /* * Create the default security context */ isns_security_t * isns_default_security_context(int server_only) { static isns_security_t *ctx; if (ctx == NULL) ctx = __create_security_context(isns_config.ic_auth_name, isns_config.ic_auth_key_file, server_only? NULL : isns_config.ic_server_key_file); return ctx; } /* * Create the control security context */ isns_security_t * isns_control_security_context(int server_only) { static isns_security_t *ctx; if (ctx == NULL) ctx = __create_security_context(isns_config.ic_control_name, isns_config.ic_control_key_file, server_only? NULL : isns_config.ic_server_key_file); return ctx; }
4,805
C
.c
174
25.281609
81
0.71873
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,501
simple.c
cleech_open-isns/simple.c
/* * Common handling for iSNS message parsing * * Copyright (C) 2007 Olaf Kirch <[email protected]> * */ #include <stdlib.h> #include <string.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include <libisns/message.h> #include "objects.h" #include "security.h" #include "socket.h" #include <libisns/util.h> typedef void isns_simple_callback_fn_t(uint32_t, int status, isns_simple_t *); static int isns_attr_list_scanner_get_pg(struct isns_attr_list_scanner *st); /* * Allocate an empty simple message */ static isns_simple_t * __isns_alloc_simple(void) { isns_simple_t *simp; simp = isns_calloc(1, sizeof(*simp)); isns_attr_list_init(&simp->is_message_attrs); isns_attr_list_init(&simp->is_operating_attrs); return simp; } /* * Create a simple message, and set the source name */ isns_simple_t * isns_simple_create(uint32_t function, isns_source_t *source, const isns_attr_list_t *key) { isns_simple_t *simp; simp = __isns_alloc_simple(); simp->is_function = function; simp->is_source = source; if (source != NULL) source->is_users++; if (key) isns_attr_list_copy(&simp->is_message_attrs, key); return simp; } /* * Perform a call to the server, waiting for the response. */ int isns_simple_call(isns_socket_t *sock, isns_simple_t **inout) { isns_simple_t *simp = *inout; isns_message_t *msg, *resp; int status; isns_simple_print(simp, isns_debug_message); status = isns_simple_encode(simp, &msg); if (status != ISNS_SUCCESS) { isns_error("Unable to encode %s: %s\n", isns_function_name(simp->is_function), isns_strerror(status)); return status; } isns_debug_message("Sending request, len=%d\n", buf_avail(msg->im_payload)); resp = isns_socket_call(sock, msg, isns_config.ic_network.call_timeout); isns_assert(msg->im_users == 1); isns_message_release(msg); if (resp == NULL) { isns_error("Timed out while waiting for reply\n"); return ISNS_INTERNAL_ERROR; } isns_debug_message("Received reply, len=%d\n", buf_avail(resp->im_payload)); isns_assert(resp->im_users == 1); status = isns_message_status(resp); if (status != ISNS_SUCCESS) { isns_message_release(resp); return status; } status = isns_simple_decode(resp, &simp); isns_message_release(resp); if (status) { isns_error("Unable to decode server response: %s (status 0x%04x)\n", isns_strerror(status), status); return status; } isns_simple_print(simp, isns_debug_message); isns_simple_free(*inout); *inout = simp; return ISNS_SUCCESS; } /* * This callback is invoked from the network layer when * we received a response to an async message */ static void isns_simple_recv_response(isns_message_t *cmsg, isns_message_t *rmsg) { isns_simple_callback_fn_t *user_callback; isns_simple_t *resp = NULL; int status = ISNS_INTERNAL_ERROR; /* rmsg being NULL means the call timed out. */ if (rmsg == NULL) goto callback; status = isns_message_status(rmsg); if (status != ISNS_SUCCESS) { isns_error("Server flags error: %s (status 0x%04x)\n", isns_strerror(status), status); goto callback; } status = isns_simple_decode(rmsg, &resp); if (status) { isns_error("Unable to decode server response: %s (status 0x%04x)\n", isns_strerror(status), status); resp = NULL; goto callback; } isns_simple_print(resp, isns_debug_message); callback: user_callback = cmsg->im_calldata; if (user_callback) user_callback(cmsg->im_xid, status, resp); if (resp) isns_simple_free(resp); } /* * Transmit a call, without waiting for the response. */ int isns_simple_transmit(isns_socket_t *sock, isns_simple_t *call, const isns_portal_info_t *dest, unsigned int timeout, isns_simple_callback_fn_t *user_callback) { isns_message_t *msg; int status; isns_simple_print(call, isns_debug_message); status = isns_simple_encode(call, &msg); if (status != ISNS_SUCCESS) { isns_error("Unable to encode %s: %s\n", isns_function_name(call->is_function), isns_strerror(status)); return status; } isns_debug_message("Sending message, len=%d\n", buf_avail(msg->im_payload)); if (user_callback) { msg->im_callback = isns_simple_recv_response; msg->im_calldata = user_callback; } if (!isns_socket_submit(sock, msg, timeout)) status = ISNS_INTERNAL_ERROR; isns_message_release(msg); return status; } /* * Delete the simple message object */ void isns_simple_free(isns_simple_t *simp) { if (simp == NULL) return; isns_attr_list_destroy(&simp->is_message_attrs); isns_attr_list_destroy(&simp->is_operating_attrs); isns_source_release(simp->is_source); isns_policy_release(simp->is_policy); isns_free(simp); } /* * Get the source associated with this simple message */ isns_source_t * isns_simple_get_source(isns_simple_t *simp) { return simp->is_source; } const isns_attr_list_t * isns_simple_get_attrs(isns_simple_t *simp) { return &simp->is_operating_attrs; } /* * Determine whether message includes a source attr. */ static inline int isns_simple_include_source(uint16_t function) { if (function & 0x8000) return 0; switch (function) { case ISNS_STATE_CHANGE_NOTIFICATION: case ISNS_ENTITY_STATUS_INQUIRY: return 0; } return 1; } /* * Decode a simple message */ int isns_simple_decode(isns_message_t *msg, isns_simple_t **result) { isns_simple_t *simp = __isns_alloc_simple(); buf_t *bp = msg->im_payload; int status = ISNS_SUCCESS; simp->is_function = msg->im_header.i_function; simp->is_xid = msg->im_xid; if (isns_simple_include_source(simp->is_function)) { status = isns_source_decode(bp, &simp->is_source); if (status != ISNS_SUCCESS) goto out; } switch (simp->is_function & 0x7FFF) { case ISNS_ENTITY_STATUS_INQUIRY: case ISNS_STATE_CHANGE_NOTIFICATION: /* Server messages do not include a source */ status = isns_attr_list_decode(bp, &simp->is_message_attrs); break; default: status = isns_attr_list_decode_delimited(bp, &simp->is_message_attrs); if (status == ISNS_SUCCESS) status = isns_attr_list_decode(bp, &simp->is_operating_attrs); } if (msg->im_header.i_flags & ISNS_F_REPLACE) simp->is_replace = 1; out: if (status == ISNS_SUCCESS) { *result = simp; } else { isns_simple_free(simp); *result = NULL; } return status; } /* * Encode a simple message reply or response */ static int __isns_simple_encode(isns_simple_t *simp, buf_t *bp) { int status = ISNS_SUCCESS; if (isns_simple_include_source(simp->is_function)) { if (simp->is_source == NULL) { isns_error("Cannot encode %s message - caller forgot to set source\n", isns_function_name(simp->is_function)); return ISNS_SOURCE_UNKNOWN; } status = isns_source_encode(bp, simp->is_source); } if (status == ISNS_SUCCESS) status = isns_attr_list_encode(bp, &simp->is_message_attrs); /* Some functions have just one set of attrs. */ switch (simp->is_function & 0x7fff) { /* It's not entirely clear which calls actually have the delimiter. * The spec is sometimes a little vague on this. */ case ISNS_SCN_DEREGISTER: case ISNS_ENTITY_STATUS_INQUIRY: case ISNS_STATE_CHANGE_NOTIFICATION: break; default: if (status == ISNS_SUCCESS) status = isns_encode_delimiter(bp); if (status == ISNS_SUCCESS) status = isns_attr_list_encode(bp, &simp->is_operating_attrs); break; } return status; } int isns_simple_encode(isns_simple_t *simp, isns_message_t **result) { isns_message_t *msg; int status, flags; flags = ISNS_F_CLIENT; if (simp->is_replace) flags |= ISNS_F_REPLACE; msg = isns_create_message(simp->is_function, flags); /* FIXME: for UDP sockets, isns_simple_t may contain a destination address. */ status = __isns_simple_encode(simp, msg->im_payload); if (status != ISNS_SUCCESS) { isns_message_release(msg); msg = NULL; } /* Report the XID to the caller */ simp->is_xid = msg->im_xid; *result = msg; return status; } int isns_simple_encode_response(isns_simple_t *reg, const isns_message_t *request, isns_message_t **result) { isns_message_t *msg; int status; msg = isns_create_reply(request); status = __isns_simple_encode(reg, msg->im_payload); if (status != ISNS_SUCCESS) { isns_message_release(msg); msg = NULL; } *result = msg; return status; } int isns_simple_decode_response(isns_message_t *resp, isns_simple_t **result) { return isns_simple_decode(resp, result); } /* * Extract the list of objects from a DevAttrReg/DevAttrQry * response or similar. */ int isns_simple_response_get_objects(isns_simple_t *resp, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, NULL, &resp->is_operating_attrs); while (1) { isns_object_t *obj; status = isns_attr_list_scanner_next(&state); if (status == ISNS_NO_SUCH_ENTRY) { status = ISNS_SUCCESS; break; } if (status) break; obj = isns_create_object(state.tmpl, &state.keys, NULL); isns_object_set_attrlist(obj, &state.attrs); if (obj != state.key_obj) isns_object_list_append(result, obj); isns_object_release(obj); } isns_attr_list_scanner_destroy(&state); return status; } /* * Print a simple message object */ void isns_simple_print(isns_simple_t *simp, isns_print_fn_t *fn) { char buffer[256]; if (fn == isns_debug_message && !isns_debug_enabled(DBG_MESSAGE)) return; fn("---%s%s---\n", isns_function_name(simp->is_function), simp->is_replace? "[REPLACE]" : ""); if (simp->is_source) { fn("Source:\n", buffer); isns_attr_print(simp->is_source->is_attr, fn); } else { fn("Source: <empty>\n"); } if (simp->is_message_attrs.ial_count == 0) { fn("Message attributes: <empty list>\n"); } else { fn("Message attributes:\n"); isns_attr_list_print(&simp->is_message_attrs, fn); } if (simp->is_operating_attrs.ial_count == 0) { fn("Operating attributes: <empty list>\n"); } else { fn("Operating attributes:\n"); isns_attr_list_print(&simp->is_operating_attrs, fn); } } /* * This set of functions analyzes the operating attrs of a registration, * or a query response, and chops it up into separate chunks, one * per objects. * * It always returns the keys and attrs for one object, * following the ordering constraints laid out in the RFC. */ void isns_attr_list_scanner_init(struct isns_attr_list_scanner *st, isns_object_t *key_obj, const isns_attr_list_t *attrs) { memset(st, 0, sizeof(*st)); st->orig_attrs = *attrs; st->key_obj = key_obj; } void isns_attr_list_scanner_destroy(struct isns_attr_list_scanner *st) { isns_attr_list_destroy(&st->keys); isns_attr_list_destroy(&st->attrs); memset(st, 0, sizeof(*st)); } int isns_attr_list_scanner_next(struct isns_attr_list_scanner *st) { isns_attr_t *attr; unsigned int i, pos = st->pos; isns_attr_list_destroy(&st->keys); isns_attr_list_destroy(&st->attrs); if (st->orig_attrs.ial_count <= pos) return ISNS_NO_SUCH_ENTRY; attr = st->orig_attrs.ial_data[pos]; /* handle those funky inlined PGT definitions */ if (st->pgt_next_attr && attr->ia_tag_id == st->pgt_next_attr) return isns_attr_list_scanner_get_pg(st); /* This isn't really structured programming anymore */ if (st->index_acceptable && (st->tmpl = isns_object_template_for_index_tag(attr->ia_tag_id))) goto copy_attrs; /* * Find the object template for the given key attr(s). * This function also enforces restrictions on the * order of key attributes. */ st->tmpl = isns_object_template_find(attr->ia_tag_id); if (st->tmpl == NULL) { isns_debug_protocol("%s: attr %u is not a key attr\n", __FUNCTION__, attr->ia_tag_id); return ISNS_INVALID_REGISTRATION; } /* Copy the key attrs */ for (i = 0; i < st->tmpl->iot_num_keys; ++i, ++pos) { if (pos >= st->orig_attrs.ial_count) { isns_debug_protocol("%s: incomplete %s object " "(key attr %u missing)\n", __FUNCTION__, st->tmpl->iot_name, pos); return ISNS_INVALID_REGISTRATION; } attr = st->orig_attrs.ial_data[pos]; /* Make sure key attrs are complete and in order */ if (attr->ia_tag_id != st->tmpl->iot_keys[i]) { isns_debug_protocol("%s: incomplete %s object " "(key attr %u missing)\n", __FUNCTION__, st->tmpl->iot_name, pos); return ISNS_INVALID_REGISTRATION; } isns_attr_list_append_attr(&st->keys, attr); } /* * Consume all non-key attributes corresponding to the * object class. We stop whenever we hit another * key attribute, or an attribute that does not belong to * the object type (eg when a storage node is followed by * a PGT attribute, as described in section 5.6.5.1). */ copy_attrs: while (pos < st->orig_attrs.ial_count) { uint32_t tag; attr = st->orig_attrs.ial_data[pos]; tag = attr->ia_tag_id; if (!isns_object_attr_valid(st->tmpl, tag) || isns_object_template_find(tag) != NULL) break; pos++; isns_attr_list_append_attr(&st->attrs, attr); } st->pos = pos; return ISNS_SUCCESS; } int isns_attr_list_scanner_get_pg(struct isns_attr_list_scanner *st) { isns_attr_t *attr, *next = NULL; unsigned int pos = st->pos; attr = st->orig_attrs.ial_data[st->pos++]; if (st->pgt_next_attr == ISNS_TAG_PG_TAG) { isns_object_t *base = st->pgt_base_object; if (ISNS_ATTR_IS_NIL(attr)) st->pgt_value = 0; else if (ISNS_ATTR_IS_UINT32(attr)) st->pgt_value = attr->ia_value.iv_uint32; else return ISNS_INVALID_REGISTRATION; if (ISNS_IS_PORTAL(base) && isns_portal_from_object(&st->pgt_portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, base)) { st->pgt_next_attr = ISNS_TAG_PG_ISCSI_NAME; } else if (ISNS_IS_ISCSI_NODE(base) && isns_object_get_string(base, ISNS_TAG_ISCSI_NAME, &st->pgt_iscsi_name)) { st->pgt_next_attr = ISNS_TAG_PG_PORTAL_IP_ADDR; } else { return ISNS_INTERNAL_ERROR; } /* Trailing PGT at end of list. Shrug. */ if (st->pos >= st->orig_attrs.ial_count) return ISNS_NO_SUCH_ENTRY; attr = st->orig_attrs.ial_data[st->pos++]; if (attr->ia_tag_id != st->pgt_next_attr) { /* Some clients may do this; catch them so * we can fix it. */ isns_error("Oops, client sends PGT followed by <%s>\n", attr->ia_tag->it_name); return ISNS_INVALID_REGISTRATION; } } st->tmpl = &isns_iscsi_pg_template; if (st->pgt_next_attr == ISNS_TAG_PG_ISCSI_NAME) { isns_attr_list_append_attr(&st->keys, attr); isns_portal_to_attr_list(&st->pgt_portal_info, ISNS_TAG_PG_PORTAL_IP_ADDR, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, &st->keys); } else if (st->pgt_next_attr == ISNS_TAG_PG_PORTAL_IP_ADDR) { if (st->pos >= st->orig_attrs.ial_count) return ISNS_INVALID_REGISTRATION; next = st->orig_attrs.ial_data[st->pos++]; if (next->ia_tag_id != ISNS_TAG_PG_PORTAL_TCP_UDP_PORT) return ISNS_INVALID_REGISTRATION; isns_attr_list_append_string(&st->keys, ISNS_TAG_PG_ISCSI_NAME, st->pgt_iscsi_name); isns_attr_list_append_attr(&st->keys, attr); isns_attr_list_append_attr(&st->keys, next); } else { return ISNS_INTERNAL_ERROR; } isns_attr_list_append_uint32(&st->attrs, ISNS_TAG_PG_TAG, st->pgt_value); /* Copy other PG attributes if present */ for (pos = st->pos; pos < st->orig_attrs.ial_count; ++pos) { uint32_t tag; attr = st->orig_attrs.ial_data[pos]; tag = attr->ia_tag_id; /* * Additional sets of PGTs and PG iSCSI Names to be * associated to the registered Portal MAY follow. */ if (tag == ISNS_TAG_PG_TAG) { st->pgt_next_attr = tag; break; } if (tag == ISNS_TAG_PG_ISCSI_NAME || tag == ISNS_TAG_PG_PORTAL_IP_ADDR || tag == ISNS_TAG_PG_PORTAL_TCP_UDP_PORT || !isns_object_attr_valid(st->tmpl, tag)) break; isns_attr_list_append_attr(&st->attrs, attr); } st->pos = pos; return ISNS_SUCCESS; } /* * Get the name of a function */ #define __ISNS_MAX_FUNCTION 16 static const char * isns_req_function_names[__ISNS_MAX_FUNCTION] = { [ISNS_DEVICE_ATTRIBUTE_REGISTER]= "DevAttrReg", [ISNS_DEVICE_ATTRIBUTE_QUERY] = "DevAttrQry", [ISNS_DEVICE_GET_NEXT] = "DevGetNext", [ISNS_DEVICE_DEREGISTER] = "DevDereg", [ISNS_SCN_REGISTER] = "SCNReg", [ISNS_SCN_DEREGISTER] = "SCNDereg", [ISNS_SCN_EVENT] = "SCNEvent", [ISNS_STATE_CHANGE_NOTIFICATION]= "SCN", [ISNS_DD_REGISTER] = "DDReg", [ISNS_DD_DEREGISTER] = "DDDereg", [ISNS_DDS_REGISTER] = "DDSReg", [ISNS_DDS_DEREGISTER] = "DDSDereg", [ISNS_ENTITY_STATUS_INQUIRY] = "ESI", [ISNS_HEARTBEAT] = "Heartbeat", }; static const char * isns_resp_function_names[__ISNS_MAX_FUNCTION] = { [ISNS_DEVICE_ATTRIBUTE_REGISTER]= "DevAttrRegResp", [ISNS_DEVICE_ATTRIBUTE_QUERY] = "DevAttrQryResp", [ISNS_DEVICE_GET_NEXT] = "DevGetNextResp", [ISNS_DEVICE_DEREGISTER] = "DevDeregResp", [ISNS_SCN_REGISTER] = "SCNRegResp", [ISNS_SCN_DEREGISTER] = "SCNDeregResp", [ISNS_SCN_EVENT] = "SCNEventResp", [ISNS_STATE_CHANGE_NOTIFICATION]= "SCNResp", [ISNS_DD_REGISTER] = "DDRegResp", [ISNS_DD_DEREGISTER] = "DDDeregResp", [ISNS_DDS_REGISTER] = "DDSRegResp", [ISNS_DDS_DEREGISTER] = "DDSDeregResp", [ISNS_ENTITY_STATUS_INQUIRY] = "ESIRsp", /* No response code for heartbeat */ }; const char * isns_function_name(uint32_t function) { static char namebuf[32]; const char **names, *name; unsigned int num = function; names = isns_req_function_names; if (num & 0x8000) { names = isns_resp_function_names; num &= 0x7fff; } name = NULL; if (num < __ISNS_MAX_FUNCTION) name = names[num]; if (name == NULL) { snprintf(namebuf, sizeof(namebuf), "<function %08x>", function); name = namebuf; } return name; }
17,545
C
.c
615
26.001626
78
0.696438
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,502
isnsd.c
cleech_open-isns/isnsd.c
/* * isnsd - the iSNS Daemon * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <time.h> #ifdef MTRACE # include <mcheck.h> #endif #include <libisns/isns.h> #include "security.h" #include <libisns/util.h> #include <libisns/paths.h> #include "internal.h" enum { MODE_NORMAL, MODE_DUMP_DB, MODE_INIT, }; static const char * opt_configfile = ISNS_DEFAULT_ISNSD_CONFIG; static int opt_af = AF_UNSPEC; static int opt_mode = MODE_NORMAL; static int opt_foreground = 0; static char * slp_url; static int init_server(void); static void run_server(isns_server_t *, isns_db_t *); static void usage(int, const char *); static void cleanup(int); static struct option options[] = { { "config", required_argument, NULL, 'c' }, { "debug", required_argument, NULL, 'd' }, { "foreground", no_argument, NULL, 'f' }, { "init", no_argument, NULL, MODE_INIT }, { "dump-db", no_argument, NULL, MODE_DUMP_DB }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL } }; int main(int argc, char **argv) { isns_server_t *server; isns_source_t *source; isns_db_t *db; int c; #ifdef MTRACE mtrace(); #endif while ((c = getopt_long(argc, argv, "46c:d:fh", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'f': opt_foreground = 1; break; case MODE_DUMP_DB: case MODE_INIT: opt_mode = c; break; case 'h': usage(0, NULL); case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch <[email protected]>\n", OPENISNS_VERSION_STRING); return 0; default: usage(1, "Unknown option"); } } if (optind != argc) usage(1, NULL); isns_read_config(opt_configfile); if (!isns_config.ic_source_name) { /* * Try to read the source name from open-iscsi configuration, * using the default iniatiator name */ isns_read_initiatorname(ISCSI_DEFAULT_INITIATORNAME); } isns_init_names(); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); source = isns_source_create_iscsi(isns_config.ic_source_name); if (opt_mode == MODE_INIT) return !init_server(); if (opt_mode == MODE_NORMAL) isns_write_pidfile(isns_config.ic_pidfile); db = isns_db_open(isns_config.ic_database); if (db == NULL) isns_fatal("Unable to open database\n"); if (opt_mode == MODE_DUMP_DB) { isns_db_print(db, isns_print_stdout); exit(0); } if (!opt_foreground) { if (daemon(0, 0) < 0) isns_fatal("Unable to background server process\n"); isns_log_background(); isns_update_pidfile(isns_config.ic_pidfile); } signal(SIGTERM, cleanup); signal(SIGINT, cleanup); server = isns_create_server(source, db, &isns_default_service_ops); run_server(server, db); return 0; } void usage(int exval, const char *msg) { if (msg) fprintf(stderr, "Error: %s\n", msg); fprintf(stderr, "Usage: isnsd [options]\n\n" " --config Specify alternative config fille\n" " --foreground Do not put daemon in the background\n" " --debug Enable debugging (list of debug flags)\n" " --init Initialize the server (key generation etc)\n" " --dump-db Display the database contents and exit\n" " --help Print this message\n" ); exit(exval); } void cleanup(int sig) { isns_remove_pidfile(isns_config.ic_pidfile); exit(sig == SIGTERM ? 0 : 1); } static void slp_cleanup(void) { char *url = slp_url; slp_url = NULL; if (url) { isns_slp_unregister(url); isns_free(url); } } /* * Initialize server */ int init_server(void) { if (!isns_security_init()) return 0; /* Anything else? */ return 1; } /* * Server main loop */ void run_server(isns_server_t *server, isns_db_t *db) { isns_socket_t *sock; isns_security_t *ctx = NULL; isns_message_t *msg, *resp; int status; if (isns_config.ic_security) { const char *ksname; isns_keystore_t *ks; ctx = isns_default_security_context(1); if (!(ksname = isns_config.ic_client_keystore)) isns_fatal("config problem: no key store specified\n"); if (!strcasecmp(ksname, "db:")) ks = isns_create_db_keystore(db); else ks = isns_create_keystore(ksname); if (ks == NULL) isns_fatal("Unable to create keystore %s\n", ksname); isns_security_set_keystore(ctx, ks); } status = isns_dd_load_all(db); if (status != ISNS_SUCCESS) isns_fatal("Problem loading Discovery Domains from database\n"); /* First socket is the control socket */ sock = isns_create_systemd_socket(0); if (sock) { /* Second socket is the iSNS port */ sock = isns_create_systemd_socket(1); isns_debug_socket("Using systemd fds\n"); goto set_security; } if (isns_config.ic_control_socket) { sock = isns_create_server_socket(isns_config.ic_control_socket, NULL, AF_UNSPEC, SOCK_STREAM); if (sock == NULL) isns_fatal("Unable to create control socket\n"); /* * isns_socket_set_security_ctx(sock, ctx); */ } sock = isns_create_server_socket(isns_config.ic_bind_address, "isns", opt_af, SOCK_STREAM); if (sock == NULL) isns_fatal("Unable to create server socket\n"); set_security: isns_socket_set_security_ctx(sock, ctx); if (isns_config.ic_slp_register) { slp_url = isns_slp_build_url(0); isns_slp_register(slp_url); atexit(slp_cleanup); } isns_esi_init(server); isns_scn_init(server); while (1) { struct timeval timeout = { 0, 0 }; time_t now, then, next_timeout = time(NULL) + 3600; /* Expire entities that haven't seen any activity * for a while. */ if (isns_config.ic_registration_period) { then = isns_db_expire(db); if (then && then < next_timeout) next_timeout = then; } /* Run any timers (eg for ESI) */ then = isns_run_timers(); if (then && then < next_timeout) next_timeout = then; /* There may be pending SCNs, push them out now */ then = isns_scn_transmit_all(); if (then && then < next_timeout) next_timeout = then; /* Purge any objects that have been marked for removal * from the DB (deleting them, or moving them to limbo * state). */ isns_db_purge(db); /* Determine how long we can sleep before working * the ESI queues and DB expiry again. */ now = time(NULL); if (next_timeout <= now) continue; timeout.tv_sec = next_timeout - now; if ((msg = isns_recv_message(&timeout)) == NULL) continue; if ((resp = isns_process_message(server, msg)) != NULL) { isns_socket_t *sock = isns_message_socket(msg); isns_socket_send(sock, resp); isns_message_release(resp); } isns_message_release(msg); } }
6,895
C
.c
261
23.582375
73
0.669557
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,504
isnsadm.c
cleech_open-isns/isnsadm.c
/* * isnsadm - helper utility * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <limits.h> #include "config.h" #include <libisns/isns.h> #include <libisns/util.h> #include "vendor.h" #include <libisns/attrs.h> #include "security.h" #include "objects.h" #include <libisns/paths.h> #define ISNS_DEFAULT_PORT_INITIATOR 860 #define ISNS_DEFAULT_PORT_TARGET 3260 enum { DO_REGISTER = 1024, DO_QUERY, DO_QUERY_EID, DO_LIST, DO_DEREGISTER, DO_DD_REGISTER, DO_DD_DEREGISTER, DO_ENROLL, DO_EDIT_POLICY, DO_DELETE_POLICY, }; static struct option options[] = { { "help", no_argument, NULL, 'h' }, { "config", required_argument, NULL, 'c' }, { "debug", required_argument, NULL, 'd' }, { "keyfile", required_argument, NULL, 'K', }, { "key", required_argument, NULL, 'k', }, { "server", required_argument, NULL, 's', }, { "local", no_argument, NULL, 'l' }, { "control", no_argument, NULL, 'C' }, { "replace", no_argument, NULL, 'r' }, { "query", no_argument, NULL, DO_QUERY }, { "query-eid", no_argument, NULL, DO_QUERY_EID }, { "list", no_argument, NULL, DO_LIST }, { "register", no_argument, NULL, DO_REGISTER }, { "deregister", no_argument, NULL, DO_DEREGISTER }, { "dd-register", no_argument, NULL, DO_DD_REGISTER }, { "dd-deregister", no_argument, NULL, DO_DD_DEREGISTER}, { "enroll", no_argument, NULL, DO_ENROLL }, { "edit-policy", no_argument, NULL, DO_EDIT_POLICY }, { "delete-policy", no_argument, NULL, DO_DELETE_POLICY }, { "version", no_argument, NULL, 'V' }, { NULL } }; static const char * opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; static int opt_af = AF_UNSPEC; static int opt_action = 0; static int opt_local = 0; static int opt_control = 0; static int opt_replace = 0; static char * opt_keyfile = NULL; static char * opt_key = NULL; static const char * opt_servername = NULL; static struct sockaddr_storage opt_myaddr; static void usage(int, const char *); static int register_objects(isns_client_t *, int, char **); static int query_objects(isns_client_t *, int, char **); static int query_entity_id(isns_client_t *, int, char **); static int list_objects(isns_client_t *, int, char **); static int deregister_objects(isns_client_t *, int, char **); static int register_domain(isns_client_t *, int, char **); static int deregister_domain(isns_client_t *, int, char **); static int enroll_client(isns_client_t *, int, char **); static int edit_policy(isns_client_t *, int, char **); static isns_attr_t * load_key_callback(const char *); static isns_attr_t * generate_key_callback(void); int main(int argc, char **argv) { isns_client_t *clnt; isns_security_t *security = NULL; int c, status; while ((c = getopt_long(argc, argv, "46Cc:d:hK:k:ls:", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'C': opt_control = 1; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'h': usage(0, NULL); break; case 'K': opt_keyfile = optarg; break; case 'k': opt_key = optarg; break; case 'l': opt_local = 1; break; case 'r': opt_replace = 1; break; case 's': opt_servername = optarg; break; case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch <[email protected]>\n", OPENISNS_VERSION_STRING); return 0; case DO_REGISTER: case DO_QUERY: case DO_QUERY_EID: case DO_LIST: case DO_DEREGISTER: case DO_DD_REGISTER: case DO_DD_DEREGISTER: case DO_ENROLL: case DO_EDIT_POLICY: case DO_DELETE_POLICY: if (opt_action) usage(1, "You cannot specify more than one mode\n"); opt_action = c; break; default: usage(1, "Unknown option"); } } if (opt_configfile) isns_read_config(opt_configfile); if (!isns_config.ic_source_name) { /* * Try to read the source name from open-iscsi configuration */ isns_read_initiatorname(ISCSI_DEFAULT_INITIATORNAME); } isns_init_names(); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); if (!isns_config.ic_server_name && opt_servername) isns_config.ic_server_name = strdup(opt_servername); if (!isns_config.ic_server_name && !opt_local) usage(1, "Please specify an iSNS server name"); if (!opt_action) usage(1, "Please specify an operating mode"); if (opt_control) { if (!isns_config.ic_security) isns_fatal("Cannot use control mode, security disabled\n"); security = isns_control_security_context(0); if (!security) isns_fatal("Unable to create control security context\n"); /* Create a networked client, using isns.control as * the source name */ clnt = isns_create_client(security, isns_config.ic_control_name); } else if (opt_local) { /* Create a local client, using isns.control as * the source name */ clnt = isns_create_local_client(security, isns_config.ic_control_name); } else { /* Create a networked client, using the configured * source name */ clnt = isns_create_default_client(security); } if (clnt == NULL) return 1; /* We're an interactive app, and don't want to retry * forever if the server refuses us. */ isns_socket_set_disconnect_fatal(clnt->ic_socket); /* Get the IP address we use to talk to the iSNS server */ if (opt_myaddr.ss_family == AF_UNSPEC && !opt_local) { if (!isns_socket_get_local_addr(clnt->ic_socket, &opt_myaddr)) isns_fatal("Unable to obtain my IP address\n"); isns_addr_set_port((struct sockaddr *) &opt_myaddr, 860); } argv += optind; argc -= optind; switch (opt_action) { case DO_REGISTER: status = register_objects(clnt, argc, argv); break; case DO_QUERY: status = query_objects(clnt, argc, argv); break; case DO_QUERY_EID: status = query_entity_id(clnt, argc, argv); break; case DO_LIST: status = list_objects(clnt, argc, argv); break; case DO_DEREGISTER: status = deregister_objects(clnt, argc, argv); break; case DO_DD_REGISTER: status = register_domain(clnt, argc, argv); break; case DO_DD_DEREGISTER: status = deregister_domain(clnt, argc, argv); break; case DO_ENROLL: status = enroll_client(clnt, argc, argv); break; case DO_EDIT_POLICY: status = edit_policy(clnt, argc, argv); break; // case DO_DELETE_POLICY: default: isns_fatal("Not yet implemented\n"); status = 1; /* compiler food */ } return status != ISNS_SUCCESS; } void usage(int exval, const char *msg) { if (msg) fprintf(stderr, "Error: %s\n", msg); fprintf(stderr, "Usage: isnsadm [options] --action ...\n" " --config Specify alternative config fille\n" " --debug Enable debugging (list of debug flags)\n" " --keyfile Where to store newly generated private key\n" " --local Use local Unix socket to talk to isnsd\n" " --control Assume control node identity for authentication\n" " --replace Use replace mode (--register only)\n" "\nThe following actions are supported:\n" " --register Register one or more objects\n" " --deregister Deregister an object (and children)\n" " --dd-register Register a Discovery Domain (and members)\n" " --dd-deregister Deregister a Discovery Domain (and members)\n" " --query Query iSNS server for objects\n" " --list List all objects of a given type\n" " --enroll Create a new policy object for a client\n" " --edit-policy Edit a policy object\n" " --delete-policy Edit a policy object\n" " --help Display this message\n" "\nUse \"--query help\" to get help on e.g. the query action\n" ); exit(exval); } int parse_registration(char **argv, int argc, isns_object_list_t *objs, isns_object_t *key_obj) { struct sockaddr_storage def_addr; isns_object_t *entity = NULL, *last_portal = NULL, *last_node = NULL; const char *def_port = NULL; int i; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object registration:\n" " isnsadm [-key attr=value] --register type,attr=value,... type,attr=value,...\n" "Where type can be one of:\n" " entity create/update network entity\n" " initiator create iSCSI initiator storage node\n" " target create iSCSI target storage node\n" " control create control node\n" " portal create portal\n" " pg create portal group\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(NULL); exit(0); } if (argc == 0) usage(1, "Missing object list\n"); if (key_obj) { //isns_object_list_append(objs, key_obj); if (isns_object_is_entity(key_obj)) entity = key_obj; } def_addr = opt_myaddr; for (i = 0; i < argc; ++i) { isns_attr_list_t attrlist = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_object_t *obj; char *name, *value, *next_attr; char *attrs[128]; unsigned int nattrs = 0; name = argv[i]; if ((next_attr = strchr(name, ',')) != NULL) *next_attr++ = '\0'; while (next_attr && *next_attr) { if (nattrs > 128) isns_fatal("Too many attributes\n"); /* Show mercy with fat fingered * people,,,,who,cannot,,,type,properly */ if (next_attr[0] != ',') attrs[nattrs++] = next_attr; if ((next_attr = strchr(next_attr, ',')) != NULL) *next_attr++ = '\0'; } if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; if (!strcmp(name, "entity")) { if (entity == NULL) { isns_error("Cannot create entity object " "within this key object\n"); return 0; } if (value != NULL) isns_object_set_string(entity, ISNS_TAG_ENTITY_IDENTIFIER, value); obj = isns_object_get(entity); goto handle_attributes; } else if (!strcmp(name, "node") || !strcmp(name, "initiator")) { const char *node_name; node_name = isns_config.ic_source_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_INITIATOR_MASK, entity); last_node = obj; isns_addr_set_port((struct sockaddr *) &def_addr, ISNS_DEFAULT_PORT_INITIATOR); def_port = "iscsi"; } else if (!strcmp(name, "target")) { const char *node_name; node_name = isns_config.ic_source_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_TARGET_MASK, entity); last_node = obj; isns_addr_set_port((struct sockaddr *) &def_addr, ISNS_DEFAULT_PORT_TARGET); def_port = "iscsi-target"; } else if (!strcmp(name, "control")) { const char *node_name; node_name = isns_config.ic_control_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_CONTROL_MASK, entity); last_node = obj; def_port = NULL; } else if (!strcmp(name, "portal")) { isns_portal_info_t portal_info; if (value == NULL) { if (def_port == NULL) isns_fatal("portal must follow initiator or target\n"); isns_portal_init(&portal_info, (struct sockaddr *) &def_addr, IPPROTO_TCP); } else if (!isns_portal_parse(&portal_info, value, def_port)) isns_fatal("Unable to parse portal=%s\n", value); obj = isns_create_portal(&portal_info, entity); last_portal = obj; } else if (!strcmp(name, "pg")) { if (value) isns_fatal("Unexpected value for portal group\n"); if (!last_portal || !last_node) isns_fatal("Portal group registration must follow portal and node\n"); obj = isns_create_portal_group(last_portal, last_node, 10); } else { isns_error("Unknown object type \"%s\"\n", name); return 0; } if (obj == NULL) { isns_error("Failure to create %s object\n", name); return 0; } isns_object_list_append(objs, obj); handle_attributes: isns_attr_list_parser_init(&state, obj->ie_template); state.default_port = def_port; if (!isns_parse_attrs(nattrs, attrs, &attrlist, &state) || !isns_object_set_attrlist(obj, &attrlist)) { isns_error("Failure to set all %s attributes\n", name); isns_attr_list_destroy(&attrlist); return 0; } isns_attr_list_destroy(&attrlist); isns_object_release(obj); } return 1; } static int __register_objects(isns_client_t *clnt, isns_object_t *key_obj, const isns_object_list_t *objects) { isns_source_t *source = NULL; isns_simple_t *reg; uint32_t status; unsigned int i; for (i = 0; i < objects->iol_count && !source; ++i) { isns_object_t *obj = objects->iol_data[i]; if (!isns_object_is_iscsi_node(obj)) continue; source = isns_source_from_object(obj); } reg = isns_create_registration2(clnt, key_obj, source); isns_registration_set_replace(reg, opt_replace); /* Add all objects to be registered */ for (i = 0; i < objects->iol_count; ++i) isns_registration_add_object(reg, objects->iol_data[i]); status = isns_client_call(clnt, &reg); isns_simple_free(reg); if (status == ISNS_SUCCESS) printf("Successfully registered object(s)\n"); else isns_error("Failed to register object(s): %s\n", isns_strerror(status)); if (source) isns_source_release(source); return status; } int register_objects(isns_client_t *clnt, int argc, char **argv) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_object_t *key_obj = NULL; uint32_t status; if (opt_key != NULL) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); if (!isns_parse_attrs(1, &opt_key, &key_attrs, &state)) { isns_error("Cannot parse registration key \"%s\"\n", opt_key); return 0; } key_obj = isns_create_object(isns_attr_list_parser_context(&state), &key_attrs, NULL); isns_attr_list_destroy(&key_attrs); if (!key_obj) { isns_error("Cannot create registration key object\n"); return 0; } } else { /* If the user does not provide a key object, * create/update an entity. */ key_obj = isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, NULL); } if (!parse_registration(argv, argc, &objects, key_obj)) isns_fatal("Unable to parse registration\n"); status = __register_objects(clnt, key_obj, &objects); isns_object_list_destroy(&objects); isns_object_release(key_obj); return status; } /* * Parse the query string given by the user * * 5.6.5.2 * The Message Key may contain key or non-key attributes or no * attributes at all. If multiple attributes are used as the * Message Key, then they MUST all be from the same object type * (e.g., IP address and TCP/UDP Port are attributes of the * Portal object type). */ int parse_query(char **argv, int argc, isns_attr_list_t *keys, isns_attr_list_t *query) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); state.nil_permitted = 1; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --query attr=value attr=value ... ?query-attr ?query-attr ...\n" "All key attributes must refer to a common object type.\n" "Query attributes specify the attributes the server should return," "and can refer to any object type.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } if (argc == 0) isns_fatal("Missing query attributes\n"); return isns_parse_query_attrs(argc, argv, keys, query, &state); } int query_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_attr_list_t oper_attrs = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; uint32_t status; isns_simple_t *qry; unsigned int i; if (!parse_query(argv, argc, &query_key, &oper_attrs)) isns_fatal("Unable to parse query\n"); qry = isns_create_query(clnt, &query_key); isns_attr_list_destroy(&query_key); /* Add the list of attributes we request */ for (i = 0; i < oper_attrs.ial_count; ++i) isns_query_request_attr(qry, oper_attrs.ial_data[i]); isns_attr_list_destroy(&oper_attrs); status = isns_client_call(clnt, &qry); if (status != ISNS_SUCCESS) { isns_error("Query failed: %s\n", isns_strerror(status)); return status; } status = isns_query_response_get_objects(qry, &objects); if (status) { isns_error("Unable to extract object list from query response: %s\n", isns_strerror(status), status); return status; } isns_object_list_print(&objects, isns_print_stdout); isns_object_list_destroy(&objects); isns_simple_free(qry); return status; } int query_entity_id(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; uint32_t status; isns_simple_t *qry; const char *eid; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Query iSNS for own entity ID.\n" "No arguments allowed\n"); exit(0); } if (argc != 0) isns_fatal("EID query - no arguments accepted\n"); isns_attr_list_append_string(&query_key, ISNS_TAG_ISCSI_NAME, isns_config.ic_source_name); qry = isns_create_query(clnt, &query_key); isns_attr_list_destroy(&query_key); isns_query_request_attr_tag(qry, ISNS_TAG_ENTITY_IDENTIFIER); status = isns_client_call(clnt, &qry); if (status != ISNS_SUCCESS) { isns_error("Query failed: %s\n", isns_strerror(status)); return status; } status = isns_query_response_get_objects(qry, &objects); if (status) { isns_error("Unable to extract object list from query response: %s\n", isns_strerror(status), status); return status; } status = ISNS_NO_SUCH_ENTRY; if (objects.iol_count == 0) { isns_error("Node %s not registered with iSNS\n", isns_config.ic_source_name); } else if (!isns_object_get_string(objects.iol_data[0], ISNS_TAG_ENTITY_IDENTIFIER, &eid)) { isns_error("Query for %s returned an object without EID\n", isns_config.ic_source_name); } else { printf("%s\n", eid); status = ISNS_SUCCESS; } isns_object_list_destroy(&objects); isns_simple_free(qry); return status; } /* * Parse the list query string given by the user */ int parse_list(int argc, char **argv, isns_object_template_t **type_p, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_object_template_t *query_type = NULL; char *type_name; if (argc == 0) usage(1, "Missing object type"); if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --list type attr=value attr=value ...\n" "Possible value for <type>:\n" " entities - list all network entities\n" " nodes - list all storage nodes\n" " portals - list all portals\n" " portal-groups - list all portal groups\n" " dds - list all discovery domains\n" " ddsets - list all discovery domains sets\n" " policies - list all policies (privileged)\n" "Additional attributes can be specified to scope the\n" "search. They must match the specified object type.\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(NULL); exit(0); } type_name = *argv++; --argc; if (!strcasecmp(type_name, "entities")) query_type = &isns_entity_template; else if (!strcasecmp(type_name, "nodes")) query_type = &isns_iscsi_node_template; else if (!strcasecmp(type_name, "portals")) query_type = &isns_portal_template; else if (!strcasecmp(type_name, "portal-groups")) query_type = &isns_iscsi_pg_template; else if (!strcasecmp(type_name, "dds")) query_type = &isns_dd_template; else if (!strcasecmp(type_name, "ddsets")) query_type = &isns_ddset_template; else if (!strcasecmp(type_name, "policies")) query_type = &isns_policy_template; else { isns_error("Unknown object type \"%s\"\n", type_name); return 0; } *type_p = query_type; isns_attr_list_parser_init(&state, query_type); state.nil_permitted = 1; return isns_parse_attrs(argc, argv, keys, &state); } int list_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_keys = ISNS_ATTR_LIST_INIT; isns_object_template_t *query_type = NULL; isns_simple_t *simp; int status, count = 0; if (!parse_list(argc, argv, &query_type, &query_keys)) isns_fatal("Unable to parse parameters\n"); simp = isns_create_getnext(clnt, query_type, &query_keys); while (1) { isns_object_t *obj = NULL; isns_simple_t *followup; status = isns_client_call(clnt, &simp); if (status) break; status = isns_getnext_response_get_object(simp, &obj); if (status) break; printf("Object %u:\n", count++); isns_object_print(obj, isns_print_stdout); isns_object_release(obj); followup = isns_create_getnext_followup(clnt, simp, &query_keys); isns_simple_free(simp); simp = followup; } if (status == ISNS_SOURCE_UNAUTHORIZED && query_type == &isns_policy_template && !opt_local) isns_warning("Please use --local trying to list policies\n"); if (status != ISNS_NO_SUCH_ENTRY) { isns_error("GetNext call failed: %s\n", isns_strerror(status)); return status; } return ISNS_SUCCESS; } /* * Parse the deregistration string given by the user * * 5.6.5.2 * The Message Key may contain key or non-key attributes or no * attributes at all. If multiple attributes are used as the * Message Key, then they MUST all be from the same object type * (e.g., IP address and TCP/UDP Port are attributes of the * Portal object type). */ int parse_deregistration(char **argv, int argc, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); state.multi_type_permitted = 1; state.nil_permitted = 1; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object deregistration:\n" " isnsadm --deregister attr=value attr=value ...\n" "All attributes must refer to a common object type.\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, keys, &state); } int deregister_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *dereg; uint32_t status; if (!parse_deregistration(argv, argc, &query_key)) isns_fatal("Unable to parse unregistration\n"); dereg = isns_create_deregistration(clnt, &query_key); isns_attr_list_destroy(&query_key); status = isns_client_call(clnt, &dereg); if (status != ISNS_SUCCESS) { isns_error("Deregistration failed: %s\n", isns_strerror(status)); return status; } #if 0 status = isns_dereg_msg_response_get_objects(dereg, &objects); if (status) { isns_error("Unable to extract object list from deregistration response: %s\n", isns_strerror(status), status); goto done; } isns_object_list_print(&objects, isns_print_stdout); #endif isns_object_list_destroy(&objects); isns_simple_free(dereg); return status; } /* * Handle discovery domain registration/deregistration */ int parse_dd_registration(char **argv, int argc, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_dd_template); if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --dd-register attr=value attr=value ...\n" "You cannot specify more than one domain.\n" "If you want to modify an existing domain, you must specify its ID.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, keys, &state); } int register_domain(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_simple_t *msg; uint32_t status; if (!parse_dd_registration(argv, argc, &attrs)) isns_fatal("Unable to parse DD registration\n"); msg = isns_create_dd_registration(clnt, &attrs); isns_attr_list_destroy(&attrs); if (msg == NULL) { isns_error("Cannot create message\n"); return ISNS_INTERNAL_ERROR; } status = isns_client_call(clnt, &msg); if (status != ISNS_SUCCESS) { isns_error("Registration failed: %s\n", isns_strerror(status)); return status; } if (status == ISNS_SUCCESS) { printf("Registered DD:\n"); isns_attr_list_print( isns_simple_get_attrs(msg), isns_print_stdout); } isns_simple_free(msg); return status; } int parse_dd_deregistration(char **argv, int argc, uint32_t *dd_id, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_dd_template); if (argc == 0 || (argc == 1 && !strcmp(argv[0], "help"))) { printf("DD deregistration:\n" " isnsadm --dd-deregister dd-id attr=value attr=value ...\n" "You cannot specify more than one domain.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } *dd_id = parse_count(argv[0]); return isns_parse_attrs(argc - 1, argv + 1, keys, &state); } int deregister_domain(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_simple_t *msg; uint32_t dd_id, status; if (!parse_dd_deregistration(argv, argc, &dd_id, &attrs)) isns_fatal("Unable to parse DD registration\n"); msg = isns_create_dd_deregistration(clnt, dd_id, &attrs); isns_attr_list_destroy(&attrs); if (msg == NULL) { isns_error("Cannot create message\n"); return ISNS_INTERNAL_ERROR; } status = isns_client_call(clnt, &msg); if (status != ISNS_SUCCESS) { isns_error("Deregistration failed: %s\n", isns_strerror(status)); return status; } isns_simple_free(msg); return status; } /* * Parse a policy */ int parse_policy(int argc, char **argv, isns_attr_list_t *attrs, const char *help_title, const char *help_action) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_policy_template); state.nil_permitted = 0; state.load_key = load_key_callback; state.generate_key = generate_key_callback; if (argc == 1 && !strcmp(argv[0], "help")) { printf("%s:\n" " isnsadm %s attr=value attr=value ...\n" "Specifying a Security Policy Index is mandatory.\n" "\nThe following attributes are recognized:\n", help_title, help_action); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, attrs, &state); } static int __create_policy(isns_client_t *clnt, const isns_attr_list_t *attrs) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_object_t *obj; int status; obj = isns_create_object(&isns_policy_template, attrs, NULL); if (!obj) isns_fatal("Cannot create policy object\n"); isns_object_list_append(&objects, obj); status = __register_objects(clnt, NULL, &objects); isns_object_list_destroy(&objects); return status; } /* * Enroll a new client */ int enroll_client(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; const char *client_name; int status; if (argc == 0) usage(1, "Missing client name"); client_name = *argv++; --argc; isns_attr_list_append_string(&attrs, OPENISNS_TAG_POLICY_SPI, client_name); #if 0 isns_attr_list_append_string(&attrs, OPENISNS_TAG_POLICY_SOURCE_NAME, client_name); #endif if (!opt_keyfile) { size_t capacity = strlen(client_name) + 5; char *namebuf = isns_malloc(capacity); if (!namebuf) isns_fatal("Out of memory."); snprintf(namebuf, capacity, "%s.key", client_name); opt_keyfile = namebuf; } if (argc && !parse_policy(argc, argv, &attrs, "Enroll an iSNS client", "--enroll hostname")) isns_fatal("Cannot parse policy\n"); /* If no key is given, generate one */ if (!isns_attr_list_contains(&attrs, OPENISNS_TAG_POLICY_KEY)) { printf("No key given, generating one\n"); isns_attr_list_append_attr(&attrs, generate_key_callback()); } status = __create_policy(clnt, &attrs); isns_attr_list_destroy(&attrs); return status; } /* * Create a new policy */ int edit_policy(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; int status; if (!parse_policy(argc, argv, &attrs, "Edit an existing policy", "--edit-policy")) isns_fatal("Cannot parse policy\n"); status = __create_policy(clnt, &attrs); isns_attr_list_destroy(&attrs); return status; } #ifdef WITH_SECURITY static isns_attr_t * __key_to_attr(EVP_PKEY *pkey) { struct __isns_opaque key; isns_value_t value; isns_attr_t *attr = NULL; if (!isns_dsa_encode_public(pkey, &key.ptr, &key.len)) goto out; /* Must pad key. This means we may end up encoding a few * bytes of trash. Oh well. */ key.len = ISNS_PAD(key.len); value = ISNS_VALUE_INIT(opaque, key); attr = isns_attr_alloc(OPENISNS_TAG_POLICY_KEY, NULL, &value); isns_free(key.ptr); out: EVP_PKEY_free(pkey); return attr; } isns_attr_t * generate_key_callback(void) { EVP_PKEY *pkey; if (opt_keyfile == NULL) isns_fatal("Key generation requires --keyfile option\n"); if (!(pkey = isns_dsa_generate_key())) isns_fatal("Key generation failed\n"); if (!isns_dsa_store_private(opt_keyfile, pkey)) isns_fatal("Unable to write private key to %s\n", opt_keyfile); printf("Stored DSA private key in %s\n", opt_keyfile); return __key_to_attr(pkey); } isns_attr_t * load_key_callback(const char *pathname) { EVP_PKEY *pkey; if (!(pkey = isns_dsa_load_public(pathname))) isns_fatal("Unable to load public key from file %s\n", pathname); return __key_to_attr(pkey); } #else /* WITH_SECURITY */ isns_attr_t * generate_key_callback(void) { isns_fatal("Authentication disabled in this build\n"); return NULL; } isns_attr_t * load_key_callback(const char *pathname) { isns_fatal("Authentication disabled in this build\n"); return NULL; } #endif
30,216
C
.c
969
28.04128
91
0.676582
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,505
scope.c
cleech_open-isns/scope.c
/* * Handle object visibility and scope. * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include "objects.h" #include <libisns/message.h> #include "security.h" #include <libisns/util.h> #include "db.h" struct isns_scope { isns_db_t * ic_db; unsigned int ic_users; isns_object_t * ic_source_node; isns_object_template_t * ic_query_class; isns_object_list_t ic_dd_nodes; isns_object_list_t ic_dd_portals; isns_object_list_t ic_objects; }; static int __isns_scope_collect_dd(uint32_t, void *); /* * Allocate an empty scope */ isns_scope_t * isns_scope_alloc(isns_db_t *db) { isns_scope_t *scope; scope = isns_calloc(1, sizeof(*scope)); scope->ic_db = db; scope->ic_users = 1; return scope; } isns_scope_t * isns_scope_get(isns_scope_t *scope) { if (scope) { isns_assert(scope->ic_users); scope->ic_users++; } return scope; } void isns_scope_release(isns_scope_t *scope) { if (!scope) return; isns_assert(scope->ic_users); if (--(scope->ic_users)) return; isns_object_release(scope->ic_source_node); isns_object_list_destroy(&scope->ic_dd_nodes); isns_object_list_destroy(&scope->ic_dd_portals); isns_object_list_destroy(&scope->ic_objects); isns_free(scope); } /* * Get the scope for this operation */ isns_scope_t * isns_scope_for_call(isns_db_t *db, const isns_simple_t *call) { isns_source_t *source = call->is_source; isns_object_t *node; isns_scope_t *scope; uint32_t node_type; /* FIXME use source->is_node and source->is_node_type */ /* When we get here, we already know that the client * represents the specified source node. */ node = isns_db_lookup_source_node(db, source); /* Allow unknown nodes to query the DB */ if (node == NULL) { node = isns_create_storage_node2(source, 0, NULL); if (node == NULL) return NULL; source->is_untrusted = 1; } if (isns_object_get_uint32(node, ISNS_TAG_ISCSI_NODE_TYPE, &node_type) && (node_type & ISNS_ISCSI_CONTROL_MASK)) { isns_object_release(node); return isns_scope_get(db->id_global_scope); } scope = isns_scope_alloc(db); scope->ic_source_node = node; { isns_object_list_t members = ISNS_OBJECT_LIST_INIT; unsigned int i; isns_object_get_visible(node, db, &members); isns_object_list_uniq(&members); /* If the node is not a member of any DD, allow it * to at least talk to itself. */ if (members.iol_count == 0) isns_object_list_append(&members, node); /* Sort DD members into nodes and portals */ for (i = 0; i < members.iol_count; ++i) { isns_object_t *obj = members.iol_data[i]; if (obj->ie_state != ISNS_OBJECT_STATE_MATURE) continue; if (!isns_policy_validate_object_access(call->is_policy, source, obj, call->is_function)) continue; if (ISNS_IS_ISCSI_NODE(obj)) isns_object_list_append(&scope->ic_dd_nodes, obj); else if (ISNS_IS_PORTAL(obj)) isns_object_list_append(&scope->ic_dd_portals, obj); } isns_object_list_destroy(&members); } return scope; } /* * Add an object to a scope */ void isns_scope_add(isns_scope_t *scope, isns_object_t *obj) { isns_object_list_append(&scope->ic_objects, obj); } int isns_scope_remove(isns_scope_t *scope, isns_object_t *obj) { return isns_object_list_remove(&scope->ic_objects, obj); } /* * Get all objects related through a portal group, optionally * including the portal group objects themselves */ static void __isns_scope_get_pg_related(isns_scope_t *scope, const isns_object_t *obj, isns_object_list_t *result) { isns_object_list_t temp = ISNS_OBJECT_LIST_INIT; unsigned int i; /* Get all portal groups related to this object */ isns_db_get_relationship_objects(scope->ic_db, obj, ISNS_RELATION_PORTAL_GROUP, &temp); /* Include all portals/nodes that we can reach. */ for (i = 0; i < temp.iol_count; ++i) { isns_object_t *pg, *other; uint32_t pgt; pg = temp.iol_data[i]; /* Skip any portal group objects with a PG tag of 0; * these actually deny access. */ if (!isns_object_get_uint32(pg, ISNS_TAG_PG_TAG, &pgt) || pgt == 0) continue; /* Get the other object. * Note that isns_relation_get_other doesn't * bump the reference count, so there's no need * to call isns_object_release(other). */ other = isns_relation_get_other(pg->ie_relation, obj); if (other->ie_state != ISNS_OBJECT_STATE_MATURE) continue; isns_object_list_append(result, other); isns_object_list_append(result, pg); } isns_object_list_destroy(&temp); } /* * Get all portals related to the given node. * * 2.2.2 * Placing Portals of a Network Entity into Discovery Domains allows * administrators to indicate the preferred IP Portal interface through * which storage traffic should access specific Storage Nodes of that * Network Entity. If no Portals of a Network Entity have been placed * into a DD, then queries scoped to that DD SHALL report all Portals of * that Network Entity. If one or more Portals of a Network Entity have * been placed into a DD, then queries scoped to that DD SHALL report * only those Portals that have been explicitly placed in the DD. */ static void __isns_scope_get_portals(isns_scope_t *scope, const isns_object_t *node, isns_object_list_t *portals, isns_object_list_t *pgs, int unique) { isns_object_list_t related = ISNS_OBJECT_LIST_INIT; unsigned int i, specific = 0; /* Get all portals and portal groups related to the * given node. This will put pairs of (portal, portal-group) * on the list. */ __isns_scope_get_pg_related(scope, node, &related); /* If we're querying for our own portals, don't limit * visibility. */ if (node == scope->ic_source_node) goto report_all_portals; /* Check if any of the portals is mentioned in the DD * FIXME: There is some ambiguity over what the right * answer is when you have two nodes (initiator, target), * and two discovery domains linking the two. One * DD mentions a specific portal through which target * should be accessed; the other DD does not (allowing * use of any portal in that entity). Which portals * to return here? * We go for the strict interpretation, ie if *any* DD * restricts access to certain portals, we report only * those. */ for (i = 0; i < related.iol_count; i += 2) { isns_object_t *portal = related.iol_data[i]; if (isns_object_list_contains(&scope->ic_dd_portals, portal)) { if (portals && !(unique || isns_object_list_contains(portals, portal))) isns_object_list_append(portals, portal); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); specific++; } } if (specific) goto out; report_all_portals: /* No specific portal given for this node. Add them all. */ for (i = 0; i < related.iol_count; i += 2) { isns_object_t *portal = related.iol_data[i]; if (portals && !(unique && isns_object_list_contains(portals, portal))) isns_object_list_append(portals, portal); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); } out: isns_object_list_destroy(&related); } /* * Get all nodes reachable through a given portal * This is really the same as __isns_scope_get_portals * minus the special casing for preferred portals. * Still, let's put this into it's own function - the whole * thing is already complex enough already. */ static void __isns_scope_get_nodes(isns_scope_t *scope, const isns_object_t *portal, isns_object_list_t *nodes, isns_object_list_t *pgs, int unique) { isns_object_list_t related = ISNS_OBJECT_LIST_INIT; unsigned int i; /* Get all nodes and portal groups related to the * given node. This will put pairs of (nodes, portal-group) * on the list. */ __isns_scope_get_pg_related(scope, portal, &related); for (i = 0; i < related.iol_count; i += 2) { isns_object_t *node = related.iol_data[i]; if (nodes && !(unique && isns_object_list_contains(nodes, node))) isns_object_list_append(nodes, node); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); } isns_object_list_destroy(&related); } static void __isns_scope_get_default_dd(isns_scope_t *scope) { isns_object_t *obj; if (isns_config.ic_use_default_domain) { obj = isns_create_default_domain(); isns_object_list_append(&scope->ic_objects, obj); isns_object_release(obj); } } /* * Scope the query */ static void __isns_scope_prepare_query(isns_scope_t *scope, isns_object_template_t *tmpl) { isns_object_list_t *nodes; unsigned int i; /* Global and default scope have no source node; they're just * a list of objects. */ if (scope->ic_source_node == NULL) return; if (scope->ic_query_class) { if (scope->ic_query_class == tmpl) return; isns_object_list_destroy(&scope->ic_objects); } scope->ic_query_class = tmpl; nodes = &scope->ic_dd_nodes; if (tmpl == &isns_entity_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; if (obj->ie_container) isns_object_list_append(&scope->ic_objects, obj->ie_container); } } else if (tmpl == &isns_iscsi_node_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; isns_object_list_append(&scope->ic_objects, obj); } } else if (tmpl == &isns_portal_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; __isns_scope_get_portals(scope, obj, &scope->ic_objects, NULL, 0); } } else if (tmpl == &isns_iscsi_pg_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; __isns_scope_get_portals(scope, obj, NULL, &scope->ic_objects, 0); } } else if (tmpl == &isns_dd_template) { isns_object_t *node = scope->ic_source_node; if (node && !isns_bitvector_is_empty(node->ie_membership)) isns_bitvector_foreach(node->ie_membership, __isns_scope_collect_dd, scope); else __isns_scope_get_default_dd(scope); } isns_object_list_uniq(&scope->ic_objects); } static int __isns_scope_collect_dd(uint32_t dd_id, void *ptr) { isns_scope_t *scope = ptr; isns_object_t *dd; dd = isns_db_vlookup(scope->ic_db, &isns_dd_template, ISNS_TAG_DD_ID, dd_id, 0); if (dd) { isns_object_list_append(&scope->ic_objects, dd); isns_object_release(dd); } return 0; } /* * Lookup functions for scope */ int isns_scope_gang_lookup(isns_scope_t *scope, isns_object_template_t *tmpl, const isns_attr_list_t *match, isns_object_list_t *result) { isns_assert(tmpl); if (!scope) return 0; __isns_scope_prepare_query(scope, tmpl); return isns_object_list_gang_lookup(&scope->ic_objects, tmpl, match, result); } /* * Get related objects. * This is used by the query code. */ void isns_scope_get_related(isns_scope_t *scope, const isns_object_t *origin, unsigned int type_mask, isns_object_list_t *result) { isns_object_template_t *tmpl = origin->ie_template; isns_object_list_t nodes_result = ISNS_OBJECT_LIST_INIT; isns_object_list_t portals_result = ISNS_OBJECT_LIST_INIT; isns_object_list_t *members = &scope->ic_dd_nodes; unsigned int i; if (tmpl == &isns_entity_template) { /* Entity: include all storage nodes contained, * the portals through which to reach them, and * the portal groups for those. */ for (i = 0; i < members->iol_count; ++i) { isns_object_t *obj = members->iol_data[i]; if (obj->ie_container != origin) continue; isns_object_list_append(&nodes_result, obj); __isns_scope_get_portals(scope, obj, &portals_result, &portals_result, 1); } } else if (tmpl == &isns_iscsi_node_template) { /* Storage node: include all portals through * which it can be reached, and the portal * groups for those. */ __isns_scope_get_portals(scope, origin, &portals_result, &portals_result, 1); /* FIXME: Include all discovery domains the * node is a member of. */ } else if (tmpl == &isns_portal_template) { /* Portal: include all storage nodes which can * be reached through it, and the portal groups * for those. */ __isns_scope_get_nodes(scope, origin, &portals_result, &portals_result, 1); } else if (tmpl == &isns_iscsi_pg_template) { /* Portal group: PGs *are* a relationship, but * unclear how this should be handled. * Return nothing for now. */ } else if (tmpl == &isns_dd_template) { /* Discovery domain: no related objects. */ } isns_object_list_append_list(result, &nodes_result); isns_object_list_append_list(result, &portals_result); isns_object_list_destroy(&nodes_result); isns_object_list_destroy(&portals_result); } isns_object_t * isns_scope_get_next(isns_scope_t *scope, isns_object_template_t *tmpl, const isns_attr_list_t *current, const isns_attr_list_t *match) { if (!tmpl || !scope) return NULL; __isns_scope_prepare_query(scope, tmpl); return __isns_db_get_next(&scope->ic_objects, tmpl, current, match); }
13,059
C
.c
439
27.009112
72
0.694141
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,506
policy.c
cleech_open-isns/policy.c
/* * Open-iSNS policy engine * * Copyright (C) 2007 Olaf Kirch <[email protected]> * * For now, policy is static. We can make it configurable * later. */ #include <string.h> #include <stdlib.h> #include "config.h" #include <libisns/isns.h> #include "security.h" #include "objects.h" #include <libisns/message.h> #include <libisns/util.h> /* A brief discussion of policy For now, a principal's name (ie its SPI string) *must* match the iSNS source name it uses. Special care needs to be taken to restrict which principals are permitted to act as a control node. For now, we don't implement control node semantics. */ static unsigned int isns_policy_gen = 0; /* * Administrative policy (everything allowed, * talks to entity "CONTROL" */ static isns_policy_t isns_superhero_powers = { .ip_name = "administrator", .ip_users = 1, .ip_gen = 0, .ip_entity = ISNS_ENTITY_CONTROL, .ip_functions = ~0, .ip_object_types = ~0, .ip_node_types = ~0, }; /* * Policy for anon user */ static isns_policy_t isns_dweeb_powers = { .ip_name = "anonymous", .ip_users = 1, .ip_gen = 0, .ip_functions = 1 << ISNS_DEVICE_ATTRIBUTE_QUERY, .ip_object_types = 0, .ip_node_types = 0, }; #define IS_ANON_POLICY(p) ((p) == &isns_dweeb_powers) /* * These are used when security is turned off. * Essentially the same as superhero, except * no eid specified. */ static isns_policy_t isns_flyingpigs_powers = { .ip_name = "insecure", .ip_users = 1, .ip_gen = 0, .ip_functions = ~0, .ip_object_types = ~0, .ip_node_types = ~0, }; isns_policy_t * isns_policy_bind(const isns_message_t *msg) { isns_policy_t *policy = NULL; isns_principal_t *princ = NULL; /* When the admin turns off gravity, * pigs can fly, too. */ if (isns_config.ic_security == 0) { policy = &isns_flyingpigs_powers; goto found; } /* If the caller is the local root user, s/he can * do anything. */ if (msg->im_creds && msg->im_creds->CMSGCRED_uid == 0) { policy = &isns_superhero_powers; goto found; } /* Tie the SPI given in the auth block to a * source name. * For now, the names have to match. Down the road, * there may be more flexible schemes. */ if ((princ = msg->im_security) != NULL) { if ((policy = princ->is_policy) != NULL) goto found; isns_error("Internal error - no policy for " "principal %s!\n", princ->is_name); } policy = &isns_dweeb_powers; found: policy->ip_users++; return policy; } /* * Check whether the call is permitted. * This is particularly useful to prevent rogue * clients from messing with Discovery Domains. */ int isns_policy_validate_function(const isns_policy_t *policy, const isns_message_t *msg) { uint32_t function = msg->im_header.i_function; int rv = 0; if (function >= 32) { isns_debug_auth("Bad function code %08x\n", function); return 0; } if (!(policy->ip_functions & (1 << function))) goto reject; rv = 1; reject: isns_debug_auth(":: policy %s function %s (%04x) %s\n", policy->ip_name, isns_function_name(function), function, rv? "permitted" : "DENIED"); return rv; } /* * Helper function to validate node names and source names */ static int __validate_node_name(const isns_policy_t *policy, const char *name) { const struct string_array *ap; unsigned int i; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) return 1; ap = &policy->ip_node_names; for (i = 0; i < ap->count; ++i) { const char *s; s = ap->list[i]; if (s == NULL) continue; if (isns_source_pattern_match(s, name)) return 1; } return 0; } /* * Validate the source of a message */ int isns_policy_validate_source(const isns_policy_t *policy, const isns_source_t *source) { const char *src_name = isns_source_name(source); int rv = 0; if (!__validate_node_name(policy, src_name)) goto reject; rv = 1; reject: isns_debug_auth(":: policy %s source %s %s\n", policy->ip_name, src_name, rv? "permitted" : "DENIED"); return rv; } /* * Check whether the entity name specified by the client * is actually his to use. */ int isns_policy_validate_entity(const isns_policy_t *policy, const char *eid) { int rv = 0, eidlen; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; /* For anonymous clients, refuse any attempt to * create an entity */ if (IS_ANON_POLICY(policy)) goto reject; /* If no entity is assigned, this means the client * is not permitted to specify its own entity name, * and accept what we assign it. */ if (policy->ip_entity == NULL) goto reject; eidlen = strlen(policy->ip_entity); if (strncasecmp(policy->ip_entity, eid, eidlen) && (eid[eidlen] == ':' || eid[eidlen] == '\0')) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s entity ID %s %s\n", policy->ip_name, eid, rv? "permitted" : "DENIED"); return rv; } const char * isns_policy_default_entity(const isns_policy_t *policy) { return policy->ip_entity; } int isns_policy_validate_node_name(const isns_policy_t *policy, const char *node_name) { int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (!__validate_node_name(policy, node_name)) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s storage node name %s %s\n", policy->ip_name, node_name, rv? "permitted" : "DENIED"); return rv; } /* * Check whether the client is allowed to access * the given object in a particular way. */ static int __isns_policy_validate_object_access(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, isns_object_template_t *tmpl, unsigned int function) { uint32_t mask, perm = ISNS_PERMISSION_WRITE; int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (function == ISNS_DEVICE_ATTRIBUTE_QUERY || function == ISNS_DEVICE_GET_NEXT) perm = ISNS_PERMISSION_READ; /* * 5.6.1. Source Attribute * * For messages that change the contents of the iSNS * database, the iSNS server MUST verify that the Source * Attribute identifies either a Control Node or a Storage * Node that is a part of the Network Entity containing * the added, deleted, or modified objects. * * Note: this statement makes sense for nodes, portals * etc, but not for discovery domains, which are not * part of any network entity (but the Control Node clause * above still applies). */ if (perm == ISNS_PERMISSION_WRITE && obj != NULL) { const isns_object_t *entity; entity = obj->ie_container; if (entity && entity != source->is_entity) goto refuse; /* You're not allowed to modify virtual objects */ if (obj->ie_rebuild) goto refuse; } /* Check whether the client is permitted to access such an object */ mask = ISNS_ACCESS(tmpl->iot_handle, perm); if (!(policy->ip_object_types & mask)) goto refuse; if (source->is_untrusted && (obj->ie_flags & ISNS_OBJECT_PRIVATE)) goto refuse; accept: rv = 1; refuse: if (obj) { isns_debug_auth(":: policy %s operation %s on object %08x (%s) %s\n", policy->ip_name, isns_function_name(function), obj->ie_index, tmpl->iot_name, rv? "permitted" : "DENIED"); } else { isns_debug_auth(":: policy %s operation %s on %s object %s\n", policy->ip_name, isns_function_name(function), tmpl->iot_name, rv? "permitted" : "DENIED"); } return rv; } /* * Check whether the client is allowed to access * the given object. This is called for read functions. */ int isns_policy_validate_object_access(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, unsigned int function) { return __isns_policy_validate_object_access(policy, source, obj, obj->ie_template, function); } /* * Check whether the client is allowed to update * the given object. */ int isns_policy_validate_object_update(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, const isns_attr_list_t *attrs, unsigned int function) { return __isns_policy_validate_object_access(policy, source, obj, obj->ie_template, function); } /* * Check whether the client is allowed to create an object * with the given attrs. */ int isns_policy_validate_object_creation(const isns_policy_t *policy, const isns_source_t *source, isns_object_template_t *tmpl, const isns_attr_list_t *keys, const isns_attr_list_t *attrs, unsigned int function) { const char *name = NULL; if (tmpl == &isns_entity_template) { /* DevReg messages may contain an empty EID * string, which means the server should select * one. */ if (isns_attr_list_get_string(keys, ISNS_TAG_ENTITY_IDENTIFIER, &name) && !isns_policy_validate_entity(policy, name)) return 0; } if (tmpl == &isns_iscsi_node_template) { if (isns_attr_list_get_string(keys, ISNS_TAG_ISCSI_NAME, &name) && !isns_policy_validate_node_name(policy, name)) return 0; } /* Should we also include the permitted portals * in the policy? */ return __isns_policy_validate_object_access(policy, source, NULL, tmpl, function); } /* * Check whether the client is permitted to access * or create an object of this type. * FIXME: Pass R/W permission bit */ int isns_policy_validate_object_type(const isns_policy_t *policy, isns_object_template_t *tmpl, unsigned int function) { uint32_t mask; int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; mask = ISNS_ACCESS_R(tmpl->iot_handle); if (!(policy->ip_object_types & mask)) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s operation %s on object type %s %s\n", policy->ip_name, isns_function_name(function), tmpl->iot_name, rv? "permitted" : "DENIED"); return rv; } int isns_policy_validate_node_type(const isns_policy_t *policy, uint32_t type) { int rv = 0; if ((~policy->ip_node_types & type) == 0) rv = 1; isns_debug_auth(":: policy %s registration of node type 0x%x %s\n", policy->ip_name, type, rv? "permitted" : "DENIED"); return rv; } /* * 6.4.4. * Management SCNs provide information about all changes to the network, * regardless of discovery domain membership. Registration for management * SCNs is indicated by setting bit 26 to 1. Only Control Nodes may * register for management SCNs. Bits 30 and 31 may only be enabled if * bit 26 is set to 1. */ int isns_policy_validate_scn_bitmap(const isns_policy_t *policy, uint32_t bitmap) { int rv = 1; if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (!(bitmap & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK)) { if (bitmap & (ISNS_SCN_DD_MEMBER_ADDED_MASK | ISNS_SCN_DD_MEMBER_REMOVED_MASK)) goto reject; goto accept; } reject: rv = 0; accept: isns_debug_auth(":: policy %s scn bitmap 0x%x %s\n", policy->ip_name, bitmap, rv? "permitted" : "DENIED"); return rv; } /* * Create the default policy for a given SPI */ isns_policy_t * isns_policy_default(const char *spi, size_t len) { return __isns_policy_alloc(spi, len); } /* * Create the policy object for the server we're * talking to. The server is allowed to send us * ESI and SCN messages, and that's about it. */ isns_policy_t * isns_policy_server(void) { isns_policy_t *policy; policy = __isns_policy_alloc("<server>", 8); policy->ip_functions = (1 << ISNS_ENTITY_STATUS_INQUIRY) | (1 << ISNS_STATE_CHANGE_NOTIFICATION); policy->ip_node_types = 0; policy->ip_object_types = 0; isns_string_array_append(&policy->ip_node_names, "*"); return policy; } /* * Allocate an empty policy object */ isns_policy_t * __isns_policy_alloc(const char *spi, size_t len) { isns_policy_t *policy; policy = isns_calloc(1, sizeof(*policy)); policy->ip_name = isns_malloc(len + 1); policy->ip_users = 1; policy->ip_gen = isns_policy_gen; memcpy(policy->ip_name, spi, len); policy->ip_name[len] = '\0'; /* Only register/query allowed */ policy->ip_functions = (1 << ISNS_DEVICE_ATTRIBUTE_REGISTER) | (1 << ISNS_DEVICE_ATTRIBUTE_QUERY) | (1 << ISNS_DEVICE_GET_NEXT) | (1 << ISNS_DEVICE_DEREGISTER) | (1 << ISNS_SCN_REGISTER); /* Can only register initiator node(s) */ policy->ip_node_types = ISNS_ISCSI_INITIATOR_MASK; /* Can only view/modify standard objects */ policy->ip_object_types = ISNS_DEFAULT_OBJECT_ACCESS; return policy; } /* * Release a policy object */ void isns_policy_release(isns_policy_t *policy) { if (!policy) return; isns_assert(policy->ip_users); if (--(policy->ip_users)) return; isns_assert(policy != &isns_superhero_powers); isns_assert(policy != &isns_flyingpigs_powers); isns_assert(policy != &isns_dweeb_powers); isns_free(policy->ip_name); isns_free(policy->ip_entity); isns_free(policy->ip_dd_default); isns_string_array_destroy(&policy->ip_node_names); isns_free(policy); }
13,090
C
.c
487
24.429158
74
0.696347
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,508
register.c
cleech_open-isns/register.c
/* * Handle iSNS Device Attribute Registration * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include "config.h" #include <libisns/isns.h> #include <libisns/attrs.h> #include "objects.h" #include <libisns/message.h> #include "security.h" #include <libisns/util.h> #include "db.h" static int isns_create_default_pgs_for_object(isns_db_t *, isns_object_t *); /* * Create a registration, and set the source name */ static isns_simple_t * __isns_create_registration(isns_source_t *source, isns_object_t *key_obj) { isns_simple_t *reg; reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, source, NULL); if (reg == NULL) return NULL; /* * When sending a registration, you can either specify * the object to be modified in the key attrs, or leave * the key empty. */ if (key_obj == NULL) return reg; /* User gave us a key object. We need to put the key * attributes into the message attrs, and *all* attrs * into the operating attrs. */ if (!isns_object_extract_keys(key_obj, &reg->is_message_attrs)) { /* bummer - seems the object is missing some * vital organs. */ isns_warning("%s: object not fully specified, key attrs missing\n", __FUNCTION__); goto failed; } /* * The Message Key identifies the object the DevAttrReg message * acts upon. [...] The key attribute(s) identifying this object * MUST also be included among the Operating Attributes. * * We do not enforce this here, we rely on the caller to get this * right. */ #if 0 if (!isns_object_extract_all(key_obj, &reg->is_operating_attrs)) { isns_warning("%s: unable to extract attrs from key objects\n", __FUNCTION__); goto failed; } #endif return reg; failed: isns_simple_free(reg); return NULL; } isns_simple_t * isns_create_registration(isns_client_t *clnt, isns_object_t *key_obj) { return __isns_create_registration(clnt->ic_source, key_obj); } isns_simple_t * isns_create_registration2(isns_client_t *clnt, isns_object_t *key_obj, isns_source_t *source) { return __isns_create_registration(source?: clnt->ic_source, key_obj); } /* * Set the replace flag */ void isns_registration_set_replace(isns_simple_t *reg, int replace) { reg->is_replace = !!replace; } /* * Add an object to the registration */ void isns_registration_add_object(isns_simple_t *reg, isns_object_t *obj) { isns_object_extract_writable(obj, &reg->is_operating_attrs); } void isns_registration_add_object_list(isns_simple_t *reg, isns_object_list_t *list) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_extract_writable(list->iol_data[i], &reg->is_operating_attrs); } } /* * Get the key object given in this message * * It doesn't say anywhere explicitly in the RFC, but * the message key can contain both key and non-key * attributes. For instance, you can search by * Portal Group Index (section 3.4). */ static int isns_registration_get_key(isns_simple_t *reg, isns_db_t *db, isns_object_t **key_obj) { isns_attr_list_t *keys = &reg->is_message_attrs; isns_attr_list_t dummy_keys = ISNS_ATTR_LIST_INIT; isns_attr_t *attr; isns_object_t *obj = NULL; const char *eid = NULL; char eidbuf[128]; int status = ISNS_SUCCESS; int obj_must_exist = 0; /* * 5.6.5.1 * If the Message Key is not present, then the DevAttrReg message * implicitly registers a new Network Entity. In this case, * the replace bit SHALL be ignored; a new Network Entity SHALL * be created. * * Note that some clients seem to leave the message key * empty, but hide the entity identifier in the operating * attrs. */ if (keys->ial_count != 0) { attr = keys->ial_data[0]; /* * 5.6.5.1 * If the Message Key does not contain an EID, and no * pre-existing objects match the Message Key, then the * DevAttrReg message SHALL be rejected with a status * code of 3 (Invalid Registration). */ if (keys->ial_count != 1 || attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) obj_must_exist = 1; } else { /* Empty message key. But the client may have hidden * the EID in the operating attrs :-/ */ if (reg->is_operating_attrs.ial_count == 0) goto create_entity; attr = reg->is_operating_attrs.ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) goto create_entity; isns_attr_list_append_attr(&dummy_keys, attr); keys = &dummy_keys; } /* If the caller specifies an EID, extract it while * we know what we're doing :-) */ if (attr->ia_tag_id == ISNS_TAG_ENTITY_IDENTIFIER && ISNS_ATTR_IS_STRING(attr)) eid = attr->ia_value.iv_string; /* Look up the object identified by the keys. * We do not scope the lookup, as the client * may want to add nodes to an entity that's * currently empty - and hence not visible to * any DD. */ if (!ISNS_ATTR_IS_NIL(attr)) obj = isns_db_lookup(db, NULL, keys); if (obj == NULL && obj_must_exist) goto err_invalid; if (obj != NULL) { /* * Policy: verify that the client is permitted * to access this object. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow modification of * this object type. */ if (!isns_policy_validate_object_access(reg->is_policy, reg->is_source, obj, reg->is_function)) goto err_unauthorized; found_object: if (reg->is_replace) { isns_object_t *container = NULL; if (!ISNS_IS_ENTITY(obj)) { container = isns_object_get_entity(obj); if (container == NULL) { isns_error("Trying to replace %s (id %u) " "which has no container\n", obj->ie_template->iot_name, obj->ie_index); goto err_invalid; } } isns_debug_state("Replacing %s (id %u)\n", obj->ie_template->iot_name, obj->ie_index); isns_db_remove(db, obj); isns_object_release(obj); /* Purge the deleted objects from the database now */ isns_db_purge(db); /* We need to flush pending SCNs because the * objects may be resurrected from limbo, * and we might be looking at stale data. */ isns_scn_transmit_all(); /* It's an entity. Nuke it and create * a new one. */ if (container == NULL) { isns_source_set_entity(reg->is_source, NULL); goto create_entity; } obj = isns_object_get(container); } goto out; } /* * If the Message Key contains an EID and no pre-existing objects * match the Message Key, then the DevAttrReg message SHALL create a * new Entity with the specified EID and any new object(s) specified * by the Operating Attributes. The replace bit SHALL be ignored. * * Implementer's note: the EID attribute may be empty, in which case * we also create a new entity. */ create_entity: if (!isns_policy_validate_object_creation(reg->is_policy, reg->is_source, &isns_entity_template, keys, NULL, reg->is_function)) goto err_unauthorized; /* * 5.6.5.1 * A registration message that creates a new Network Entity object * MUST contain at least one Portal or one Storage Node. If the * message does not, then it SHALL be considered invalid and result * in a response with Status Code of 3 (Invalid Registration). */ /* FIXME: Implement this check */ /* We try to play nice with lazy clients and attempt to * look up the network entity given the source name. * But we don't do this if a non-NULL EID was given, * because the client may explicitly want to specify more * than one Network Entity. */ if (eid == NULL) { obj = reg->is_source->is_entity; if (obj != NULL) { isns_object_get(obj); goto found_object; } /* The policy may define a default entity name. * If that is the case, use it. */ eid = isns_policy_default_entity(reg->is_policy); if (eid) { obj = isns_db_vlookup(db, &isns_entity_template, ISNS_TAG_ENTITY_IDENTIFIER, eid, 0); if (obj) { reg->is_source->is_entity = isns_object_get(obj); goto found_object; } } } /* * 5.6.5.1 * If the Message Key and Operating Attributes do not contain * an EID attribute, or if the EID attribute has a length of 0, * then a new Network Entity object SHALL be created and the iSNS * server SHALL supply a unique EID value for it. */ if (eid == NULL) eid = isns_db_generate_eid(db, eidbuf, sizeof(eidbuf)); /* * 6.2.2. Entity Protocol * * This attribute is required during initial registration of * the Network Entity. * * Implementer's note: we don't rely on this. Instead, the * Entity Protocol is selected based on the source type. * If the client specifies the protocol, the auto-selected * value is overwritten. */ obj = isns_create_entity_for_source(reg->is_source, eid); if (obj == NULL) goto err_invalid; isns_source_set_entity(reg->is_source, obj); /* * 6.2.6 * If a Registration Period is not requested by the iSNS * client and Entity Status Inquiry (ESI) messages are not * enabled for that client, then the Registration Period * SHALL be set to a non-zero value by the iSNS server. * This implementation-specific value for the Registration * Period SHALL be returned in the registration response to the * iSNS client. The Registration Period may be set to zero, * indicating its non-use, only if ESI messages are enabled for * that Network Entity. * * Implementer's note: we diverge from this in two ways: * - the admin may choose to disable registration timeout, * by setting RegistrationPeriod=0 in the config file * * - When a new entity is created, we always set the * registration interval because we cannot know yet * whether the client will subsequently enable ESI or * not. * * - The control entity (holding policy objects) will * not expire. */ if (isns_config.ic_registration_period && strcasecmp(eid, ISNS_ENTITY_CONTROL)) { isns_object_set_uint32(obj, ISNS_TAG_REGISTRATION_PERIOD, isns_config.ic_registration_period); isns_object_set_uint64(obj, ISNS_TAG_TIMESTAMP, time(NULL)); } /* Insert into database, and set the object's owner */ isns_db_insert(db, obj); reg->is_replace = 0; out: *key_obj = obj; isns_attr_list_destroy(&dummy_keys); return ISNS_SUCCESS; error: if (obj) isns_object_release(obj); isns_attr_list_destroy(&dummy_keys); return status; err_unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto error; err_invalid: status = ISNS_INVALID_REGISTRATION; goto error; } static int isns_registration_get_next_object(isns_db_t *db, struct isns_attr_list_scanner *st, isns_object_list_t *result) { isns_object_t *current; int status, esi = 0; status = isns_attr_list_scanner_next(st); /* We get here if the registration has a trailing PGT */ if (status == ISNS_NO_SUCH_ENTRY) return ISNS_SUCCESS; if (status) return status; /* * Validate the attrlist. * This makes sure the client does not include * duplicate attributes, readonly attributes * such as Registration Timestamp, Index and Next Index, * or privileged data (such as marking a storage node as * control node). */ status = isns_attr_list_validate(&st->attrs, st->policy, ISNS_DEVICE_ATTRIBUTE_REGISTER); if (status) { isns_debug_protocol("invalid attr in message\n"); return status; } /* * 6.3.4. Entity Status Inquiry Interval * * If the iSNS server is unable to support ESI messages * or the ESI Interval requested, it SHALL [...] reject * the ESI request by returning an "ESI Not Available" * Status Code [...] * * Implementer's note: In section 5.7.5.1, the RFC talks * about modifying the requested ESI interval; so it seems * it's okay to be liberal about the ESI intervals we accept, * and update them quietly. */ if (isns_attr_list_contains(&st->attrs, ISNS_TAG_ESI_PORT)) { if (!isns_esi_enabled) { isns_debug_esi("Refusing to accept portal " "registration with ESI port\n"); return ISNS_ESI_NOT_AVAILABLE; } esi = 1; } /* * Override any registration period specified by the client. */ if (isns_attr_list_contains(&st->attrs, ISNS_TAG_REGISTRATION_PERIOD)) { isns_value_t value = ISNS_VALUE_INIT(uint32, isns_config.ic_registration_period); isns_attr_list_update_value(&st->attrs, ISNS_TAG_REGISTRATION_PERIOD, NULL, &value); } if (st->tmpl == &isns_entity_template) { /* * 5.6.5.1. * A maximum of one Network Entity object can be * created or updated with a single DevAttrReg * message. Consequently, the Operating Attributes * MUST NOT contain more than one Network Entity * object. */ if (st->entities++) { isns_debug_protocol("More than one entity in DevAttrReg msg\n"); return ISNS_INVALID_REGISTRATION; } /* This should be the key object. * The EID specified by by the client may be * empty, so don't overwrite the value we * assigned with something else. */ if (!isns_object_match(st->key_obj, &st->keys)) { isns_debug_protocol("Entity mismatch in message vs. operating attrs\n"); return ISNS_INVALID_REGISTRATION; } current = isns_object_get(st->key_obj); } else if (st->tmpl == &isns_dd_template || st->tmpl == &isns_ddset_template) { isns_debug_protocol("DevAttrReg of type %s not allowed\n", st->tmpl->iot_name); return ISNS_INVALID_REGISTRATION; } else { /* This will also catch objects in limbo. */ current = isns_db_lookup(db, st->tmpl, &st->keys); } if (current != NULL) { /* * If the replace bit is not set, then the message updates * the attributes of the object identified by the Message Key * and its subordinate objects. Existing object containment * relationships MUST NOT be changed. For existing objects, * key attributes MUST NOT be modified, but new subordinate * objects MAY be added. */ /* * [...] * If the Node identified by the Source Attribute is * not a Control Node, then the objects in the operating * attributes MUST be members of the same Network Entity * as the Source Node. */ if (!isns_policy_validate_object_update(st->policy, st->source, current, &st->attrs, ISNS_DEVICE_ATTRIBUTE_REGISTER)) { isns_object_release(current); return ISNS_SOURCE_UNAUTHORIZED; } /* We shouldn't allow messages affecting one Entity * to modify objects owned by a different Entity. * * However, there may be orphan objects (created * while populating discovery domains). These will * not be associated with any Network Entity, so * they're up for grabs. */ if (st->key_obj == current || st->key_obj == current->ie_container) { /* All is well. The current object is the * key object itself, or a direct descendant of the * key object. */ /* FIXME: with FC we can get deeper nesting; * this needs work. */ } else if (!isns_object_is_valid_container(st->key_obj, st->tmpl)) { isns_error("Client attempts to add %s object to a %s - tsk tsk.\n", st->tmpl->iot_name, st->key_obj->ie_template->iot_name); goto invalid_registration; } else if (current->ie_container) { /* We shouldn't get here in authenticated mode, * but in insecure mode we still may. */ isns_error("Client attempts to move %s %u to a different %s\n", current->ie_template->iot_name, current->ie_index, st->key_obj->ie_template->iot_name); goto invalid_registration; } } else { if (!isns_object_is_valid_container(st->key_obj, st->tmpl)) { isns_error("Client attempts to add %s object to a %s - tsk tsk.\n", st->tmpl->iot_name, st->key_obj->ie_template->iot_name); goto invalid_registration; } if (!isns_policy_validate_object_creation(st->policy, st->source, st->tmpl, &st->keys, &st->attrs, ISNS_DEVICE_ATTRIBUTE_REGISTER)) { return ISNS_SOURCE_UNAUTHORIZED; } current = isns_create_object(st->tmpl, &st->keys, isns_object_get_entity(st->key_obj)); /* We do not insert the new object into the database yet. * That happens after we're done with parsing *all* * objects. */ } if (!isns_object_set_attrlist(current, &st->attrs)) { isns_debug_state("Error updating object's attrlist\n"); isns_object_release(current); return ISNS_INTERNAL_ERROR; } /* If the client specifies an ESI port, make sure the * ESI interval is set and within bounds. */ if (esi) { uint32_t esi_interval; if (!isns_object_get_uint32(current, ISNS_TAG_ESI_INTERVAL, &esi_interval)) { esi_interval = isns_config.ic_esi_min_interval; } else if (esi_interval < isns_config.ic_esi_min_interval) { esi_interval = isns_config.ic_esi_min_interval; } else if (esi_interval > isns_config.ic_esi_max_interval) { esi_interval = isns_config.ic_esi_max_interval; } else { esi_interval = 0; } if (esi_interval) isns_object_set_uint32(current, ISNS_TAG_ESI_INTERVAL, esi_interval); } /* Append it to the result list. * We do not return the key object, otherwise * we end up putting it into the response twice. */ if (current != st->key_obj) isns_object_list_append(result, current); /* * When a Portal is registered, the Portal attributes MAY immediately be * followed by a PGT attribute. * [...] * When an iSCSI Storage Node is registered, the Storage Node attributes * MAY immediately be followed by a PGT attribute. */ if (st->tmpl == &isns_portal_template || st->tmpl == &isns_iscsi_node_template) { st->pgt_next_attr = ISNS_TAG_PG_TAG; st->pgt_base_object = current; } else if (st->tmpl != &isns_iscsi_pg_template) { st->pgt_next_attr = 0; st->pgt_base_object = NULL; } isns_object_release(current); return ISNS_SUCCESS; invalid_registration: if (current) isns_object_release(current); return ISNS_INVALID_REGISTRATION; } /* * Extract the list of objects to be registered from * the list of operating attributes. */ static int isns_registration_get_objects(isns_simple_t *reg, isns_db_t *db, isns_object_t *key_obj, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, key_obj, &reg->is_operating_attrs); state.source = reg->is_source; state.policy = reg->is_policy; /* * 5.6.4. * The ordering of Operating Attributes in the message is * important for determining the relationships among objects * and their ownership of non-key attributes. iSNS protocol * messages that violate these ordering rules SHALL be rejected * with the Status Code of 2 (Message Format Error). */ /* FIXME: Implement this check */ while (state.pos < state.orig_attrs.ial_count) { status = isns_registration_get_next_object(db, &state, result); if (status) break; } isns_attr_list_scanner_destroy(&state); return status; } /* * 5.6.5.1 * New PG objects are registered when an associated Portal or * iSCSI Node object is registered. An explicit PG object * registration MAY follow a Portal or iSCSI Node object * registration in a DevAttrReg message. * [...] * If the PGT value is not included in the Storage Node or * Portal object registration, and if a PGT value was not * previously registered for the relationship, then the PGT for * the corresponding PG object SHALL be registered with a value * of 0x00000001. */ static int isns_create_registration_pgs(isns_db_t *db, const isns_object_list_t *list) { unsigned int i, num_created = 0; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (ISNS_IS_ISCSI_NODE(obj) || ISNS_IS_PORTAL(obj)) num_created += isns_create_default_pgs_for_object(db, obj); } return num_created; } static int isns_create_default_pgs_for_object(isns_db_t *db, isns_object_t *this) { isns_object_template_t *match_tmpl; isns_object_t *entity; unsigned int i, num_created = 0; if (ISNS_IS_ISCSI_NODE(this)) match_tmpl = &isns_portal_template; else match_tmpl = &isns_iscsi_node_template; entity = isns_object_get_entity(this); for (i = 0; i < entity->ie_children.iol_count; ++i) { isns_object_t *that = entity->ie_children.iol_data[i], *pg; if (that->ie_template != match_tmpl) continue; /* Create the portal group if it does not * exist. * Note: we do not return these implicitly * created portal groups - that's a matter * of sheer laziness. We would have to * splice these into the list in the * appropriate location, and I guess it's * not really worth the hassle. */ if (ISNS_IS_ISCSI_NODE(this)) pg = isns_create_default_portal_group(db, that, this); else pg = isns_create_default_portal_group(db, this, that); /* There already is a PG linking these two * objects. */ if (pg == NULL) continue; isns_db_insert(db, pg); isns_debug_message("--Created default PG:--\n"); isns_object_print(pg, isns_debug_message); isns_object_release(pg); num_created++; } return num_created; } /* * Commit all changes to the DB */ static int isns_commit_registration(isns_db_t *db, isns_object_t *key_obj, isns_object_list_t *list) { unsigned int i; /* * If there are any Portal Groups in this registration, build * the relationship handle: * * 3.4 * A new PG object can only be registered by referencing * its associated iSCSI Storage Node or Portal object. * A pre-existing PG object can be modified or queried * by using its Portal Group Index as message key, or * by referencing its associated iSCSI Storage Node or * Portal object. * * Implementation note: isns_db_create_pg_relation * checks whether the referenced node and portal exist, * and belong to the same entity as the PG. If this is * not the case, NULL is returned, and no relation is * defined. */ for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_template_t *tmpl; tmpl = obj->ie_template; if (tmpl->iot_build_relation && !obj->ie_relation && !tmpl->iot_build_relation(db, obj, list)) { isns_debug_protocol("Unable to build relation for new %s\n", tmpl->iot_name); return ISNS_INVALID_REGISTRATION; } } for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_template_t *tmpl; tmpl = obj->ie_template; if (key_obj != obj && !obj->ie_container) { if (!isns_object_attach(obj, key_obj)) { /* This should not fail any longer */ isns_debug_protocol("Unable to attach %s %u to %s\n", tmpl->iot_name, obj->ie_index, key_obj->ie_template->iot_name); return ISNS_INVALID_REGISTRATION; } } if (obj->ie_state != ISNS_OBJECT_STATE_MATURE) isns_db_insert(db, obj); } return ISNS_SUCCESS; } /* * Process a registration */ int isns_process_registration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *reply = NULL; isns_object_t *key_obj = NULL; isns_db_t *db = srv->is_db; int status; unsigned int i; /* * 5.6.1 * For messages that change the contents of the iSNS database, * the iSNS server MUST verify that the Source Attribute * identifies either a Control Node or a Storage Node that is * a part of the Network Entity containing the added, deleted, * or modified objects. * * This check happens in isns_registration_get_key by calling * isns_policy_validate_object_access. */ /* Get the key object (usually a Network Entity) */ status = isns_registration_get_key(call, db, &key_obj); if (status) goto done; /* Get the objects to register */ status = isns_registration_get_objects(call, db, key_obj, &objects); if (status != ISNS_SUCCESS) goto done; /* We parsed the request alright; all semantic checks passed. * Now insert the modified/new objects. * We do this in two passes, by first committing all nodes and * portals, and then committing the portal groups. */ status = isns_commit_registration(db, key_obj, &objects); if (status != ISNS_SUCCESS) goto done; /* The client may have registered a bunch of storage nodes, * and created an entity in the process. However, there's the * odd chance that the source node name it used was not * registered. However, we need to be able to later find * the entity it registered based on its source name. * So we implicitly create a dummy storage node with the given * source name and attach it. */ #if 1 if (ISNS_IS_ENTITY(key_obj) && !isns_source_set_node(call->is_source, db)) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_source_t *source = call->is_source; isns_object_t *obj; isns_attr_list_append_attr(&attrs, isns_source_attr(source)); isns_attr_list_append_uint32(&attrs, ISNS_TAG_ISCSI_NODE_TYPE, 0); obj = isns_create_object(&isns_iscsi_node_template, &attrs, key_obj); if (obj) { isns_db_insert(db, obj); } else { isns_warning("Unable to create dummy storage node " "for source %s\n", isns_source_name(source)); } isns_attr_list_destroy(&attrs); } #endif /* * 5.6.5.1 * New PG objects are registered when an associated Portal or * iSCSI Node object is registered. An explicit PG object * registration MAY follow a Portal or iSCSI Node object * registration in a DevAttrReg message. * [...] * If the PGT value is not included in the Storage Node or * Portal object registration, and if a PGT value was not * previously registered for the relationship, then the PGT for * the corresponding PG object SHALL be registered with a value * of 0x00000001. */ isns_create_registration_pgs(db, &objects); /* Success: create a new registration message, and * send it in our reply. */ reply = __isns_create_registration(srv->is_source, key_obj); if (reply == NULL) { status = ISNS_INTERNAL_ERROR; goto done; } /* If the key object was modified (or created) * include it in the response. * We really ought to restrict ourselves to the * key attrs plus those that were modified by this * registration. But right now have no way of * finding out. */ if (key_obj->ie_flags & ISNS_OBJECT_DIRTY) isns_registration_add_object(reply, key_obj); for (i = 0; i < objects.iol_count; ++i) { isns_registration_add_object(reply, objects.iol_data[i]); } done: isns_object_list_destroy(&objects); isns_object_release(key_obj); *result = reply; return status; } /* * Extract the list of objects from the DevAttrReg response */ int isns_registration_response_get_objects(isns_simple_t *reg, isns_object_list_t *result) { return isns_simple_response_get_objects(reg, result); }
26,583
C
.c
826
29.14891
90
0.701731
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,509
db-file.c
cleech_open-isns/db-file.c
/* * iSNS object database * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <limits.h> #include <libisns/isns.h> #include "objects.h" #include <libisns/message.h> #include <libisns/util.h> #include "db.h" #define DBE_FILE_VERSION 1 struct isns_db_file_info { uint32_t db_version; uint32_t db_last_eid; uint32_t db_last_index; }; struct isns_db_object_info { uint32_t db_version; char db_type[64]; uint32_t db_parent; uint32_t db_state; uint32_t db_flags; uint32_t db_scn_mask; /* reserved bytes */ uint32_t __db_reserved[15]; }; static int isns_dbe_file_sync(isns_db_t *); static int isns_dbe_file_reload(isns_db_t *); static int isns_dbe_file_store(isns_db_t *, const isns_object_t *); static int isns_dbe_file_remove(isns_db_t *, const isns_object_t *); static int __dbe_file_load_all(const char *, isns_object_list_t *); /* * Helper functions */ static char * __path_concat(const char *dirname, const char *prefix, const char *basename) { size_t capacity = strlen(dirname) + strlen(prefix) + strlen(basename) + 2; char *pathname; pathname = isns_malloc(capacity); if (!pathname) isns_fatal("Out of memory."); snprintf(pathname, capacity, "%s/%s%s", dirname, prefix, basename); return pathname; } static char * __print_index(uint32_t index) { char namebuf[32]; char *result; snprintf(namebuf, sizeof(namebuf), "%08x", index); result = isns_strdup(namebuf); if (!result) isns_fatal("Out of memory."); return result; } static int __get_index(const char *name, uint32_t *result) { char *end; *result = strtoul(name, &end, 16); if (*end) return ISNS_INTERNAL_ERROR; return ISNS_SUCCESS; } /* * Build path names for an object */ static char * __dbe_file_object_path(const char *dirname, const isns_object_t *obj) { char *index_str = __print_index(obj->ie_index); char *result = __path_concat(dirname, "", index_str); isns_free(index_str); return result; } /* * Build a path name for a temporary file. */ static char * __dbe_file_object_temp(const char *dirname, const isns_object_t *obj) { char *index_str = __print_index(obj->ie_index); char *result = __path_concat(dirname, ".", index_str); isns_free(index_str); return result; } /* * Recursively create a directory */ static int __dbe_mkdir_path(const char *dirname) { unsigned int true_len = strlen(dirname); char *copy, *s; copy = isns_strdup(dirname); /* Walk up until we find a directory that exists */ while (1) { s = strrchr(copy, '/'); if (s == NULL) break; *s = '\0'; if (access(copy, F_OK) == 0) break; } while (strcmp(dirname, copy)) { unsigned int len = strlen(copy); /* Better safe than sorry */ isns_assert(len < true_len); /* Put the next slash back in */ copy[len] = '/'; /* and try to create the directory */ if (mkdir(copy, 0700) < 0) return -1; } return 0; } /* * Write an object to a file */ static int __dbe_file_store_object(const char *dirname, const isns_object_t *obj) { struct isns_db_object_info info; char *path = __dbe_file_object_path(dirname, obj); char *temp = __dbe_file_object_temp(dirname, obj); buf_t *bp = NULL; int status = ISNS_INTERNAL_ERROR; isns_debug_state("DB: Storing object %u -> %s\n", obj->ie_index, path); if (access(dirname, F_OK) < 0 && (errno != ENOENT || __dbe_mkdir_path(dirname) < 0)) { isns_error("DB: Unable to create %s: %m\n", dirname); goto out; } bp = buf_open(temp, O_CREAT|O_TRUNC|O_WRONLY); if (bp == NULL) { isns_error("Unable to open %s: %m\n", temp); goto out; } /* Encode the header info ... */ memset(&info, 0, sizeof(info)); info.db_version = htonl(DBE_FILE_VERSION); info.db_state = htonl(obj->ie_state); info.db_flags = htonl(obj->ie_flags); info.db_scn_mask = htonl(obj->ie_scn_mask); strcpy(info.db_type, obj->ie_template->iot_name); if (obj->ie_container) info.db_parent = htonl(obj->ie_container->ie_index); if (!buf_put(bp, &info, sizeof(info))) goto out; /* ... and attributes */ status = isns_attr_list_encode(bp, &obj->ie_attrs); if (status != ISNS_SUCCESS) goto out; /* Renaming an open file. NFS will hate this */ if (rename(temp, path) < 0) { isns_error("Cannot rename %s -> %s: %m\n", temp, path); unlink(temp); status = ISNS_INTERNAL_ERROR; } out: isns_free(path); isns_free(temp); if (bp) buf_close(bp); return status; } /* * Store all children of an object */ static int __dbe_file_store_children(const char *dirname, const isns_object_t *obj) { int status = ISNS_SUCCESS; unsigned int i; for (i = 0; i < obj->ie_children.iol_count; ++i) { isns_object_t *child; child = obj->ie_children.iol_data[i]; status = __dbe_file_store_object(dirname, child); if (status) break; status = __dbe_file_store_children(dirname, child); if (status) break; } return status; } /* * Remove object and children */ static int __dbe_file_remove_object(const char *dirname, const isns_object_t *obj) { char *path = __dbe_file_object_path(dirname, obj); isns_debug_state("DB: Purging object %u (%s)\n", obj->ie_index, path); if (unlink(path) < 0) isns_error("DB: Cannot remove %s: %m\n", path); isns_free(path); return ISNS_SUCCESS; } static int __dbe_file_remove_children(const char *dirname, const isns_object_t *obj) { const isns_object_list_t *list = &obj->ie_children; unsigned int i; for (i = 0; i < list->iol_count; ++i) __dbe_file_remove_object(dirname, list->iol_data[i]); return ISNS_SUCCESS; } /* * Load an object from file */ static int __dbe_file_load_object(const char *filename, const char *basename, isns_object_list_t *result) { struct isns_db_object_info info; isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_object_template_t *tmpl; isns_object_t *obj = NULL; buf_t *bp = NULL; uint32_t index; int status; bp = buf_open(filename, O_RDONLY); if (bp == NULL) { isns_error("Unable to open %s: %m\n", filename); goto internal_error; } /* Decode the header ... */ if (!buf_get(bp, &info, sizeof(info))) goto internal_error; if (info.db_version != htonl(DBE_FILE_VERSION)) { /* If we ever have to deal with a DB version * upgrade, we could do it here. */ isns_fatal("Found iSNS database version %u; not supported\n", ntohl(info.db_version)); } /* ... and attributes */ status = isns_attr_list_decode(bp, &attrs); if (status != ISNS_SUCCESS) goto out; /* Get the index from the file name */ status = __get_index(basename, &index); if (status != ISNS_SUCCESS) goto out; tmpl = isns_object_template_by_name(info.db_type); if (tmpl == NULL) { isns_error("DB: Bad type name \"%s\" in object file\n", info.db_type); goto internal_error; } obj = isns_create_object(tmpl, &attrs, NULL); if (obj == NULL) goto internal_error; obj->ie_state = ntohl(info.db_state); obj->ie_flags = ntohl(info.db_flags) & ~(ISNS_OBJECT_DIRTY); obj->ie_scn_mask = ntohl(info.db_scn_mask); obj->ie_index = index; /* Stash away the parent's index; we resolve them later on * once we've loaded all objects */ obj->ie_container_idx = ntohl(info.db_parent); isns_object_list_append(result, obj); out: if (bp) buf_close(bp); if (obj) isns_object_release(obj); isns_attr_list_destroy(&attrs); return status; internal_error: isns_error("Unable to load %s: Internal error\n", filename); status = ISNS_INTERNAL_ERROR; goto out; } /* * Load contents of directory into our database. * * We take two passes over the directory. In the first pass, we load * all regular files containing objects. The file names correspond to * the DB index. * * In the second pass, we load all directories, containing children of * an object. The directories names are formed by the object's index, * with ".d" appended to it. */ static int __dbe_file_load_all(const char *dirpath, isns_object_list_t *result) { struct dirent *dp; DIR *dir; int status = ISNS_SUCCESS; if ((dir = opendir(dirpath)) == NULL) { isns_error("DB: cannot open %s: %m\n", dirpath); return ISNS_INTERNAL_ERROR; } while ((dp = readdir(dir)) != NULL) { struct stat stb; char *path; if (dp->d_name[0] == '.' || !strcmp(dp->d_name, "DB")) continue; path = __path_concat(dirpath, "", dp->d_name); if (lstat(path, &stb) < 0) { isns_error("DB: cannot stat %s: %m\n", path); status = ISNS_INTERNAL_ERROR; } else if (S_ISREG(stb.st_mode)) { status = __dbe_file_load_object(path, dp->d_name, result); } else { isns_debug_state("DB: ignoring %s\n", path); } isns_free(path); if (status != ISNS_SUCCESS) break; } closedir(dir); return status; } /* * Load and store DB metadata */ static int __dbe_file_write_info(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; char *path = NULL; buf_t *bp; int status = ISNS_INTERNAL_ERROR; path = __path_concat(back->idb_name, "", "DB"); if ((bp = buf_open(path, O_CREAT|O_TRUNC|O_WRONLY)) == NULL) { isns_error("Unable to write %s: %m\n", path); goto out; } if (buf_put32(bp, DBE_FILE_VERSION) && buf_put32(bp, db->id_last_eid) && buf_put32(bp, db->id_last_index)) status = ISNS_SUCCESS; out: isns_free(path); if (bp) buf_close(bp); return status; } static int __dbe_file_load_info(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; struct isns_db_file_info info; char *path = NULL; buf_t *bp = NULL; int status = ISNS_NO_SUCH_ENTRY; path = __path_concat(back->idb_name, "", "DB"); if ((bp = buf_open(path, O_RDONLY)) == NULL) goto out; /* * if the frist read fails that means the file is * likely truncated, so handle that */ if (!buf_get32(bp, &info.db_version)) { isns_warning("DB file truncated? Ignoring it\n"); goto out; } status = ISNS_INTERNAL_ERROR; if (info.db_version != DBE_FILE_VERSION) { isns_error("DB file from unsupported version %04x\n", info.db_version); goto out; } if (buf_get32(bp, &info.db_last_eid) && buf_get32(bp, &info.db_last_index)) { db->id_last_eid = info.db_last_eid; db->id_last_index = info.db_last_index; status = ISNS_SUCCESS; } out: isns_free(path); if (bp) buf_close(bp); return status; } /* * Find object with the given index. */ static isns_object_t * __dbe_find_object(isns_object_list_t *list, uint32_t index) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_index == index) return obj; } return NULL; } int isns_dbe_file_reload(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; int status; unsigned int i; isns_debug_state("DB: loading all objects from %s\n", back->idb_name); if (access(back->idb_name, R_OK) < 0) { if (errno == ENOENT) { /* Empty database is okay */ return ISNS_NO_SUCH_ENTRY; } isns_error("Cannot open database %s: %m\n", back->idb_name); return ISNS_INTERNAL_ERROR; } status = __dbe_file_load_info(db); if (status) return status; status = __dbe_file_load_all(back->idb_name, db->id_objects); if (status) return status; /* Resolve parent/child relationship for all nodes */ for (i = 0; i < db->id_objects->iol_count; ++i) { isns_object_t *obj = db->id_objects->iol_data[i]; uint32_t index = obj->ie_container_idx; isns_object_t *parent; if (index == 0) continue; obj->ie_container = NULL; parent = __dbe_find_object(db->id_objects, index); if (parent == NULL) { isns_warning("DB: object %u references " "unknown container %u\n", obj->ie_index, index); } else { isns_object_attach(obj, parent); } } /* Add objects to the appropriate lists */ for (i = 0; i < db->id_objects->iol_count; ++i) { isns_object_template_t *tmpl; isns_object_t *obj = db->id_objects->iol_data[i]; switch (obj->ie_state) { case ISNS_OBJECT_STATE_MATURE: isns_scope_add(db->id_global_scope, obj); obj->ie_references++; tmpl = obj->ie_template; if (tmpl->iot_build_relation && !tmpl->iot_build_relation(db, obj, NULL)) isns_warning("DB: cannot build relation for " "object %u\n", obj->ie_index); if (obj->ie_relation) isns_relation_add(db->id_relations, obj->ie_relation); if (ISNS_IS_ENTITY(obj)) isns_esi_register(obj); break; case ISNS_OBJECT_STATE_LIMBO: isns_object_list_append(&db->id_limbo, obj); break; default: isns_error("Unexpected object state %d in object %u " "loaded from %s\n", obj->ie_state, obj->ie_index, back->idb_name); } /* Clear the dirty flag, which will be set when the object is created. */ obj->ie_flags &= ~ISNS_OBJECT_DIRTY; } return ISNS_SUCCESS; } int isns_dbe_file_sync(isns_db_t *db) { return __dbe_file_write_info(db); } int isns_dbe_file_store(isns_db_t *db, const isns_object_t *obj) { isns_db_backend_t *back = db->id_backend; int status; if (obj->ie_index == 0) { isns_error("DB: Refusing to store object with index 0\n"); return ISNS_INTERNAL_ERROR; } status = __dbe_file_store_object(back->idb_name, obj); if (status == ISNS_SUCCESS) status = __dbe_file_store_children(back->idb_name, obj); return status; } int isns_dbe_file_remove(isns_db_t *db, const isns_object_t *obj) { isns_db_backend_t *back = db->id_backend; int status; status = __dbe_file_remove_object(back->idb_name, obj); if (status == ISNS_SUCCESS) status = __dbe_file_remove_children(back->idb_name, obj); return status; } /* * Create the file backend */ isns_db_backend_t * isns_create_file_db_backend(const char *pathname) { isns_db_backend_t *back; isns_debug_state("Creating file DB backend (%s)\n", pathname); back = isns_calloc(1, sizeof(*back)); back->idb_name = isns_strdup(pathname); back->idb_reload = isns_dbe_file_reload; back->idb_sync = isns_dbe_file_sync; back->idb_store = isns_dbe_file_store; back->idb_remove = isns_dbe_file_remove; return back; }
14,006
C
.c
530
23.979245
76
0.674544
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,510
entity.c
cleech_open-isns/entity.c
/* * iSNS object model - network entity specific code * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <string.h> #include <time.h> #include <libisns/isns.h> #include "objects.h" #include <libisns/util.h> /* * Create a network entity */ isns_object_t * isns_create_entity(int protocol, const char *name) { isns_object_t *obj; obj = isns_create_object(&isns_entity_template, NULL, NULL); isns_object_set_string(obj, ISNS_TAG_ENTITY_IDENTIFIER, name); isns_object_set_uint32(obj, ISNS_TAG_ENTITY_PROTOCOL, protocol); return obj; } isns_object_t * isns_create_entity_for_source(const isns_source_t *source, const char *eid) { switch (isns_source_type(source)) { case ISNS_TAG_ISCSI_NAME: return isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, eid); case ISNS_TAG_FC_PORT_NAME_WWPN: return isns_create_entity(ISNS_ENTITY_PROTOCOL_IFCP, eid); } return NULL; } const char * isns_entity_name(const isns_object_t *node) { const isns_attr_t *attr; if (node->ie_attrs.ial_count == 0) return NULL; attr = node->ie_attrs.ial_data[0]; if (attr->ia_value.iv_type != &isns_attr_type_string || attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) return NULL; return attr->ia_value.iv_string; } int isns_object_is_entity(const isns_object_t *obj) { return ISNS_IS_ENTITY(obj); } /* * 6.2.4. Entity Registration Timestamp * * This field indicates the most recent time when the Network Entity * registration occurred or when an associated object attribute was * updated or queried by the iSNS client registering the Network Entity. * The time format is, in seconds, the update period since the standard * base time of 00:00:00 GMT on January 1, 1970. This field cannot be * explicitly registered. This timestamp TLV format is also used in * the SCN and ESI messages. * * Implementer's note: we consider any kind of activity from * the client an indication that it is still alive. * Only exception is the pseudo-entity that holds the access control * information; we never assign it a timestamp so it is never subject * to expiry. */ void isns_entity_touch(isns_object_t *obj) { /* Do not add a timestamp to entity CONTROL */ if (obj == NULL || (obj->ie_flags & ISNS_OBJECT_PRIVATE) || obj->ie_template != &isns_entity_template) return; isns_object_set_uint64(obj, ISNS_TAG_TIMESTAMP, time(NULL)); } /* * Object template */ static uint32_t entity_attrs[] = { ISNS_TAG_ENTITY_IDENTIFIER, ISNS_TAG_ENTITY_PROTOCOL, ISNS_TAG_MGMT_IP_ADDRESS, ISNS_TAG_TIMESTAMP, ISNS_TAG_PROTOCOL_VERSION_RANGE, ISNS_TAG_REGISTRATION_PERIOD, ISNS_TAG_ENTITY_INDEX, ISNS_TAG_ENTITY_ISAKMP_PHASE_1, ISNS_TAG_ENTITY_CERTIFICATE, }; static uint32_t entity_key_attrs[] = { ISNS_TAG_ENTITY_IDENTIFIER, }; isns_object_template_t isns_entity_template = { .iot_name = "Network Entity", .iot_handle = ISNS_OBJECT_TYPE_ENTITY, .iot_attrs = entity_attrs, .iot_num_attrs = array_num_elements(entity_attrs), .iot_keys = entity_key_attrs, .iot_num_keys = array_num_elements(entity_key_attrs), .iot_index = ISNS_TAG_ENTITY_INDEX, .iot_next_index = ISNS_TAG_ENTITY_NEXT_INDEX, };
3,170
C
.c
110
26.836364
72
0.74236
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,511
export.c
cleech_open-isns/export.c
/* * Helper functions to represent iSNS objects as text, * and/or to parse objects represented in textual form. * These functions can be used by command line utilities * such as isnsadm, as well as applications like iscsid * or stgtd when talking to the iSNS discovery daemon. * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include "config.h" #include <libisns/isns.h> #include <libisns/util.h> #include "vendor.h" #include <libisns/attrs.h> #include "security.h" #include "objects.h" #include <libisns/paths.h> #define MAX_ALIASES 4 struct isns_tag_prefix { const char * name; unsigned int name_len; isns_object_template_t *context; }; struct tag_name { const char * name; uint32_t tag; struct isns_tag_prefix *prefix; const char * alias[MAX_ALIASES]; }; static struct isns_tag_prefix all_prefixes[__ISNS_OBJECT_TYPE_MAX] = { [ISNS_OBJECT_TYPE_ENTITY] = { "entity-", 7, &isns_entity_template }, [ISNS_OBJECT_TYPE_NODE] = { "iscsi-", 6, &isns_iscsi_node_template }, [ISNS_OBJECT_TYPE_PORTAL] = { "portal-", 7, &isns_portal_template }, [ISNS_OBJECT_TYPE_PG] = { "pg-", 3, &isns_iscsi_pg_template }, [ISNS_OBJECT_TYPE_DD] = { "dd-", 3, &isns_dd_template }, [ISNS_OBJECT_TYPE_POLICY] = { "policy-", 7, &isns_policy_template }, }; static struct tag_name all_attrs[] = { { "id", ISNS_TAG_ENTITY_IDENTIFIER, .alias = { "eid", }, }, { "prot", ISNS_TAG_ENTITY_PROTOCOL }, { "idx", ISNS_TAG_ENTITY_INDEX }, { "name", ISNS_TAG_ISCSI_NAME }, { "node-type", ISNS_TAG_ISCSI_NODE_TYPE }, { "alias", ISNS_TAG_ISCSI_ALIAS }, { "authmethod", ISNS_TAG_ISCSI_AUTHMETHOD }, { "idx", ISNS_TAG_ISCSI_NODE_INDEX }, { "addr", ISNS_TAG_PORTAL_IP_ADDRESS }, { "port", ISNS_TAG_PORTAL_TCP_UDP_PORT }, { "name", ISNS_TAG_PORTAL_SYMBOLIC_NAME }, { "esi-port", ISNS_TAG_ESI_PORT }, { "esi-interval", ISNS_TAG_ESI_INTERVAL }, { "scn-port", ISNS_TAG_SCN_PORT }, { "idx", ISNS_TAG_PORTAL_INDEX }, { "name", ISNS_TAG_PG_ISCSI_NAME }, { "addr", ISNS_TAG_PG_PORTAL_IP_ADDR }, { "port", ISNS_TAG_PG_PORTAL_TCP_UDP_PORT }, { "tag", ISNS_TAG_PG_TAG }, { "pgt", ISNS_TAG_PG_TAG }, { "idx", ISNS_TAG_PG_INDEX }, { "id", ISNS_TAG_DD_ID }, { "name", ISNS_TAG_DD_SYMBOLIC_NAME }, { "member-name", ISNS_TAG_DD_MEMBER_ISCSI_NAME }, { "member-iscsi-idx", ISNS_TAG_DD_MEMBER_ISCSI_INDEX }, { "member-fc-name", ISNS_TAG_DD_MEMBER_FC_PORT_NAME }, { "member-portal-idx", ISNS_TAG_DD_MEMBER_PORTAL_INDEX }, { "member-addr", ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR }, { "member-port", ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT }, { "features", ISNS_TAG_DD_FEATURES }, { "name", OPENISNS_TAG_POLICY_SPI, .alias = { "spi" }, }, { "key", OPENISNS_TAG_POLICY_KEY }, { "entity", OPENISNS_TAG_POLICY_ENTITY }, { "object-type", OPENISNS_TAG_POLICY_OBJECT_TYPE }, { "node-type", OPENISNS_TAG_POLICY_NODE_TYPE }, { "node-name", OPENISNS_TAG_POLICY_NODE_NAME }, { "functions", OPENISNS_TAG_POLICY_FUNCTIONS }, { NULL } }; /* * Initialize tag array */ static void init_tags(void) { struct tag_name *t; for (t = all_attrs; t->name; ++t) { isns_object_template_t *tmpl; tmpl = isns_object_template_for_tag(t->tag); if (tmpl == NULL) isns_fatal("Bug: cannot find object type for tag %s\n", t->name); t->prefix = &all_prefixes[tmpl->iot_handle]; } } /* * Match prefix */ static struct isns_tag_prefix * find_prefix(const char *name) { struct isns_tag_prefix *p; unsigned int i; for (i = 0, p = all_prefixes; i < __ISNS_OBJECT_TYPE_MAX; ++i, ++p) { if (p->name && !strncmp(name, p->name, p->name_len)) return p; } return NULL; } /* * Look up the tag for a given attribute name. * By default, attr names come with a disambiguating * prefix that defines the object type the attribute applies * to, such as "entity-" or "portal-". Once a context has * been established (ie we know the object type subsequent * attributes apply to), specifying the prefix is optional. * * For instance, in a portal context, "addr=10.1.1.1 port=616 name=foo" * specifies three portal related attributes. Whereas in a portal * group context, the same string would specify three portal group * related attributes. To disambiguate, the first attribute in * this list should be prefixed by "portal-" or "pg-", respectively. */ static uint32_t tag_by_name(const char *name, struct isns_attr_list_parser *st) { const char *orig_name = name; unsigned int nmatch = 0, i; struct tag_name *t, *match[8]; struct isns_tag_prefix *specific = NULL; if (all_attrs[0].prefix == NULL) init_tags(); specific = find_prefix(name); if (specific != NULL) { if (st->prefix && st->prefix != specific && !st->multi_type_permitted) { isns_error("Cannot mix attributes of different types\n"); return 0; } name += specific->name_len; st->prefix = specific; } for (t = all_attrs; t->name; ++t) { if (specific && t->prefix != specific) continue; if (!st->multi_type_permitted && st->prefix && t->prefix != st->prefix) continue; if (!strcmp(name, t->name)) goto match; for (i = 0; i < MAX_ALIASES && t->alias[i]; ++i) { if (!strcmp(name, t->alias[i])) goto match; } continue; match: if (nmatch < 8) match[nmatch++] = t; } if (nmatch > 1) { char conflict[128]; unsigned int i; conflict[0] = '\0'; for (i = 0; i < nmatch; ++i) { if (i) strcat(conflict, ", "); t = match[i]; strcat(conflict, t->prefix->name); strcat(conflict, t->name); } isns_error("tag name \"%s\" not unique in this context " "(could be one of %s)\n", orig_name, conflict); return 0; } if (nmatch == 0) { isns_error("tag name \"%s\" not known in this context\n", orig_name); return 0; } st->prefix = match[0]->prefix; return match[0]->tag; } static const char * name_by_tag(uint32_t tag, struct isns_attr_list_parser *st) { struct tag_name *t; for (t = all_attrs; t->name; ++t) { if (st->prefix && t->prefix != st->prefix) continue; if (t->tag == tag) return t->name; } return NULL; } static int parse_one_attr(const char *name, const char *value, isns_attr_list_t *attrs, struct isns_attr_list_parser *st) { isns_attr_t *attr; uint32_t tag; /* Special case: "portal=<address:port>" is translated to * addr=<address> port=<port> * If no context has been set, assume portal context. */ if (!strcasecmp(name, "portal")) { isns_portal_info_t portal_info; uint32_t addr_tag, port_tag; if (st->prefix == NULL) { addr_tag = tag_by_name("portal-addr", st); port_tag = tag_by_name("portal-port", st); } else { addr_tag = tag_by_name("addr", st); port_tag = tag_by_name("port", st); } if (!addr_tag || !port_tag) { isns_error("portal=... not supported in this context\n"); return 0; } if (value == NULL) { isns_attr_list_append_nil(attrs, addr_tag); isns_attr_list_append_nil(attrs, port_tag); return 1; } if (!isns_portal_parse(&portal_info, value, st->default_port)) return 0; isns_portal_to_attr_list(&portal_info, addr_tag, port_tag, attrs); return 1; } if (!(tag = tag_by_name(name, st))) return 0; /* Special handling for key objects */ if (tag == OPENISNS_TAG_POLICY_KEY) { if (!value || !strcasecmp(value, "gen")) { if (st->generate_key == NULL) { isns_error("Key generation not supported in this context\n"); return 0; } attr = st->generate_key(); } else { if (st->load_key == NULL) { isns_error("Policy-key attribute not supported in this context\n"); return 0; } attr = st->load_key(value); } goto append_attr; } if (value == NULL) { isns_attr_list_append_nil(attrs, tag); return 1; } attr = isns_attr_from_string(tag, value); if (!attr) return 0; append_attr: isns_attr_list_append_attr(attrs, attr); return 1; } void isns_attr_list_parser_init(struct isns_attr_list_parser *st, isns_object_template_t *tmpl) { if (all_attrs[0].prefix == NULL) init_tags(); memset(st, 0, sizeof(*st)); if (tmpl) st->prefix = &all_prefixes[tmpl->iot_handle]; } int isns_attr_list_split(char *line, char **argv, unsigned int argc_max) { char *src = line; unsigned int argc = 0, quoted = 0; if (!line) return 0; while (1) { char *dst; while (isspace(*src)) ++src; if (!*src) break; argv[argc] = dst = src; while (*src) { char cc = *src++; if (cc == '"') { quoted = !quoted; continue; } if (!quoted && isspace(cc)) { *dst = '\0'; break; } *dst++ = cc; } if (quoted) { isns_error("%s: Unterminated quoted string: \"%s\"\n", __FUNCTION__, argv[argc]); return -1; } argc++; } return argc; } int isns_parse_attrs(unsigned int argc, char **argv, isns_attr_list_t *attrs, struct isns_attr_list_parser *st) { unsigned int i; for (i = 0; i < argc; ++i) { char *name, *value; name = argv[i]; if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; if (!value && !st->nil_permitted) { isns_error("Missing value for atribute %s\n", name); return 0; } if (!parse_one_attr(name, value, attrs, st)) { isns_error("Unable to parse %s=%s\n", name, value); return 0; } } return 1; } /* * Query strings may contain a mix of query keys (foo=bar), * and requested attributes (?foo). The former are used by * the server in its object search, whereas the latter instruct * it which attributes to return. */ int isns_parse_query_attrs(unsigned int argc, char **argv, isns_attr_list_t *keys, isns_attr_list_t *requested_attrs, struct isns_attr_list_parser *st) { struct isns_attr_list_parser query_state; unsigned int i; query_state = *st; query_state.multi_type_permitted = 1; for (i = 0; i < argc; ++i) { char *name, *value; name = argv[i]; if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; if (name[0] == '?') { uint32_t tag; if (value) { isns_error("No value allowed for query attribute %s\n", name); return 0; } if ((tag = tag_by_name(name + 1, &query_state)) != 0) { isns_attr_list_append_nil(requested_attrs, tag); continue; } } else { if (!value && !st->nil_permitted) { isns_error("Missing value for atribute %s\n", name); return 0; } if (parse_one_attr(name, value, keys, st)) continue; } isns_error("Unable to parse %s=%s\n", name, value); return 0; } return 1; } void isns_attr_list_parser_help(struct isns_attr_list_parser *st) { isns_object_template_t *tmpl, *current = NULL; struct tag_name *t; if (all_attrs[0].prefix == NULL) init_tags(); for (t = all_attrs; t->name; ++t) { const isns_tag_type_t *tag_type; char namebuf[64]; const char *help; unsigned int i; if (st && !st->multi_type_permitted && st->prefix && t->prefix != st->prefix) continue; tmpl = t->prefix->context; if (tmpl != current) { printf("\nAttributes for object type %s; using prefix %s\n", tmpl->iot_name, t->prefix->name); current = tmpl; } snprintf(namebuf, sizeof(namebuf), "%s%s", t->prefix->name, t->name); printf(" %-20s ", namebuf); tag_type = isns_tag_type_by_id(t->tag); if (tag_type == NULL) { printf("Unknown\n"); continue; } printf("%s (%s", tag_type->it_name, tag_type->it_type->it_name); if (tag_type->it_readonly) printf("; readonly"); if (tag_type->it_multiple) printf("; multiple instances"); printf(")"); help = NULL; if (t->tag == OPENISNS_TAG_POLICY_KEY) { help = "name of key file, or \"gen\" for key generation"; } else if (tag_type->it_help) help = tag_type->it_help(); if (help) { if (strlen(help) < 20) printf(" [%s]", help); else printf("\n%25s[%s]", "", help); } printf("\n"); if (t->alias[0]) { printf("%25sAliases:", ""); for (i = 0; i < MAX_ALIASES && t->alias[i]; ++i) printf(" %s", t->alias[i]); printf("\n"); } } } isns_object_template_t * isns_attr_list_parser_context(const struct isns_attr_list_parser *st) { if (st->prefix) return st->prefix->context; return NULL; } int isns_print_attrs(isns_object_t *obj, char **argv, unsigned int argsmax) { struct isns_attr_list_parser st; unsigned int i, argc = 0; isns_attr_list_parser_init(&st, obj->ie_template); for (i = 0; i < obj->ie_attrs.ial_count; ++i) { isns_attr_t *attr = obj->ie_attrs.ial_data[i]; char argbuf[512], value[512]; const char *name; name = name_by_tag(attr->ia_tag_id, &st); if (name == NULL) continue; if (argc + 1 >= argsmax) break; snprintf(argbuf, sizeof(argbuf), "%s%s=%s", st.prefix->name, name, isns_attr_print_value(attr, value, sizeof(value))); argv[argc++] = isns_strdup(argbuf); } argv[argc] = NULL; return argc; }
12,789
C
.c
466
24.733906
72
0.645127
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,512
source.h
cleech_open-isns/include/libisns/source.h
/* * iSNS source attribute handling * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_SOURCE_H #define ISNS_SOURCE_H #include <libisns/attrs.h> struct isns_source { unsigned int is_users; isns_attr_t * is_attr; unsigned int is_untrusted : 1; isns_object_t * is_node; unsigned int is_node_type; isns_object_t * is_entity; }; extern int isns_source_encode(buf_t *, const isns_source_t *); extern int isns_source_decode(buf_t *, isns_source_t **); extern int isns_source_set_node(isns_source_t *, isns_db_t *); extern void isns_source_set_entity(isns_source_t *, isns_object_t *); extern isns_source_t * isns_source_dummy(void); extern char * isns_build_source_pattern(const char *); extern int isns_source_pattern_match(const char *, const char *); #endif /* ISNS_SOURCE_H */
828
C
.c
24
32.75
70
0.719849
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,513
pauw1.c
cleech_open-isns/tests/pauw1.c
/* * Test case, captured from a Wasabi Storage Builder * registering itself. */ #include <getopt.h> #include <libisns/isns.h> #include <libisns/paths.h> #include <libisns/util.h> #include <libisns/message.h> int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int c; while ((c = getopt(argc, argv, "c:d:")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); isns_assign_string(&isns_config.ic_source_name, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); attrs = &reg->is_operating_attrs; #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) STR(ENTITY_IDENTIFIER, "cyan.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); U32(REGISTRATION_PERIOD, 31536000); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0", "Test (10 GB)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1", "160 GB disk (ntfs)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2", "160 GB disk (ext3)", "CHAP"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3", "Test (1 GB)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4", "Test (40 GB)", "CHAP"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5", "test", "None"); isns_portal_parse(&portal_info, "10.0.0.1:3260/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); /* Mumbo jumbo encoding of portal groups */ U32(PG_TAG, 1); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5"); /* Strictly speaking, a PGT not followed by any data is invalid. * * 5.6.5.1. * When a Portal is registered, the Portal attributes MAY * immediately be followed by a PGT attribute. The PGT attribute * SHALL be followed by the set of PG iSCSI Names representing * nodes that will be associated to the Portal using the indicated * PGT value. */ NIL(PG_TAG); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object(s)\n"); isns_simple_print(reg, isns_print_stdout); return 0; } /* Creating file DB backend (/var/lib/isns) DB: loading all objects from /var/lib/isns Next ESI message in 3600 seconds Incoming PDU xid=0001 seq=0 len=1208 func=DevAttrReg client first last Next message xid=0001 Received message ---DevAttrReg--- Source: 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" Message attributes: <empty list> Operating attributes: 0001 string : Entity identifier = "cyan.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 31536000 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (10 GB)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ntfs)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ext3)" 002a string : iSCSI auth method = "CHAP" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (1 GB)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (40 GB)" 002a string : iSCSI auth method = "CHAP" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "test" 002a string : iSCSI auth method = "None" 0010 ipaddr : Portal IP address = 10.0.0.1 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0033 uint32 : Portal group tag = 1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0033 nil : Portal group tag = <empty> :: policy insecure function DevAttrReg (0001) permitted :: policy insecure source iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0 permitted :: policy insecure operation DevAttrReg on Network Entity object permitted DB: Storing object 00000001 -> /var/lib/isns/00000001 DB: added object 1 (Network Entity) state 1 Segmentation fault */
6,773
C
.c
159
38.685535
98
0.684713
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,515
pauw4.c
cleech_open-isns/tests/pauw4.c
/* * Test MS initiator registration. * The oddity about this is that the PG object precedes the * initiator object in the message. */ #include <getopt.h> #include <unistd.h> #include <libisns/isns.h> #include <libisns/paths.h> #include <libisns/util.h> #include <libisns/message.h> #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int opt_replace = 1; int c; while ((c = getopt(argc, argv, "c:d:n")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'n': opt_replace = 0; break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); isns_assign_string(&isns_config.ic_source_name, "iqn.1991-05.com.microsoft:orange"); clnt = isns_create_default_client(NULL); /* * test that we can deregister for SCN events, even though * not registered */ reg = isns_simple_create(ISNS_SCN_DEREGISTER, clnt->ic_source, NULL); /* Message attributes */ attrs = &reg->is_message_attrs; STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_error("SCNDereg failed: %s\n", isns_strerror(status)); else printf("Successfully deregistered for SCN events\n"); isns_simple_free(reg); /* * test that we can deregister a device, even though not * registered -- note that the portal group object proceeds * the initiator (name) object in the operating attribute * list */ reg = isns_simple_create(ISNS_DEVICE_DEREGISTER, clnt->ic_source, NULL); attrs = &reg->is_operating_attrs; STR(ENTITY_IDENTIFIER, "troopa.nki.nl"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.40:3229/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("DevDereg failed: %s\n", isns_strerror(status)); else printf("Successfully deregistered a device\n"); isns_simple_free(reg); /* * test that we can register (w/replace) device attributes */ reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = opt_replace; attrs = &reg->is_operating_attrs; STR(ENTITY_IDENTIFIER, "troopa.nki.nl"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.40:3229/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(SCN_PORT, 3230); U32(ESI_PORT, 3230); U32(PG_TAG, 1); STR(PG_ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, "<MS SW iSCSI Initiator>"); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("DevAttrReg failed: %s\n", isns_strerror(status)); else printf("Successfully registered device attributes\n"); isns_simple_free(reg); /* * test that we can call DEVICE GET NEXT to get the next (only) * iscsi Storage Node */ reg = isns_simple_create(ISNS_DEVICE_GET_NEXT, clnt->ic_source, NULL); attrs = &reg->is_message_attrs; NIL(ISCSI_NAME); attrs = &reg->is_operating_attrs; U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); NIL(ISCSI_NODE_TYPE); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("DevGetNext failed: %s\n", isns_strerror(status)); else printf("Successfully got next device node\n"); isns_simple_free(reg); return 0; }
4,245
C
.c
132
29.606061
73
0.712956
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,516
pauw2.c
cleech_open-isns/tests/pauw2.c
/* * Test case, captured from iscsi-target * registering itself. */ #include <getopt.h> #include <libisns/isns.h> #include <libisns/paths.h> #include <libisns/util.h> #include <libisns/message.h> #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int c; while ((c = getopt(argc, argv, "c:d:")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2007-03.com.example:stgt.disk" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0017 uint32 : SCN port = 42138/tcp 0020 string : iSCSI name = "iqn.2007-03.com.example:stgt.disk" 0021 uint32 : iSCSI node type = Target */ isns_assign_string(&isns_config.ic_source_name, "iqn.2007-03.com.example:stgt.disk"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = 1; /* Message attributes */ attrs = &reg->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = &reg->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:3260/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(SCN_PORT, 42138); STR(ISCSI_NAME, "iqn.2007-03.com.example:stgt.disk"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object #1\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0014 uint32 : ESI port = 56288/tcp 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" [...] response status 0x0003 (Invalid registration) This would fail because we got confused about EID in the replace case. */ isns_assign_string(&isns_config.ic_source_name, "iqn.2005-03.org.open-iscsi:blue"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = 1; /* Message attributes */ attrs = &reg->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = &reg->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:33849/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(ESI_PORT, 56288); STR(ISCSI_NAME, "iqn.2005-03.org.open-iscsi:blue"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, "blue.pauw.homeunix.net"); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object #2\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); return 0; } /* Creating file DB backend (/var/lib/isns) DB: loading all objects from /var/lib/isns Next ESI message in 3600 seconds Incoming PDU xid=0001 seq=0 len=232 func=DevAttrReg client first last Next message xid=0001 Received message :: policy insecure function DevAttrReg (0001) permitted :: policy insecure source iqn.2005-03.org.open-iscsi:blue permitted :: policy insecure operation DevAttrReg on object 00000001 (Network Entity) permitted Replacing Network Entity (id 1) DB: removed object 2 (Portal) DB: removed object 4 (iSCSI Portal Group) DB: removed object 3 (iSCSI Storage Node) DB: removed object 1 (Network Entity) DB: destroying object 2 (Portal) DB: Purging object 2 (/var/lib/isns/00000002) DB: destroying object 1 (Network Entity) DB: Purging object 1 (/var/lib/isns/00000001) DB: destroying object 3 (iSCSI Storage Node) DB: Purging object 3 (/var/lib/isns/00000003) DB: destroying object 4 (iSCSI Portal Group) DB: Purging object 4 (/var/lib/isns/00000004) :: policy insecure entity ID blue.pauw.homeunix.net permitted :: policy insecure operation DevAttrReg on Network Entity object permitted DB: Storing object 5 -> /var/lib/isns/00000005 DB: added object 5 (Network Entity) state 1 DB: Storing object 5 -> /var/lib/isns/00000005 isns_esi_callback(0x9dee788, 0x10) Deleting SCN registration for iqn.2007-03.com.example:stgt.disk isns_esi_callback(0x9deeae0, 0x10) isns_esi_callback(0x9deea30, 0x10) isns_esi_callback(0x9deec80, 0x10) SCN multicast <iSCSI Storage Node 3, removed> isns_scn_callback(0x9deec80, 0x10) isns_esi_callback(0x9def4b0, 0xc) Enable ESI monitoring for entity 5 */
6,769
C
.c
180
33.733333
75
0.69361
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,518
pauw3.c
cleech_open-isns/tests/pauw3.c
/* * This tests another problem reported by Albert, where a * re-registration shortly before ESI expiry would fail * to resurrect the registration properly. * * Usage: * pauw3 [options] timeout * * Where timeout is the delay until we try to re-register */ #include <getopt.h> #include <unistd.h> #include <libisns/isns.h> #include <libisns/paths.h> #include <libisns/util.h> #include <libisns/message.h> #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int opt_replace = 1; int c, n, timeout; while ((c = getopt(argc, argv, "c:d:n")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'n': opt_replace = 0; break; default: isns_fatal("Unknown option\n"); } } if (optind != argc - 1) isns_fatal("Need timeout argument\n"); timeout = parse_timeout(argv[optind]); isns_read_config(opt_configfile); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0014 uint32 : ESI port = 56288/tcp 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" [...] response status 0x0003 (Invalid registration) This would fail because we got confused about EID in the replace case. */ isns_assign_string(&isns_config.ic_source_name, "iqn.2005-03.org.open-iscsi:blue"); for (n = 0; n < 2; ++n) { clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = opt_replace; /* Message attributes */ attrs = &reg->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = &reg->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:33849/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(ESI_PORT, 56288); STR(ISCSI_NAME, "iqn.2005-03.org.open-iscsi:blue"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, "blue.pauw.homeunix.net"); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, &reg); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); if (n == 0) { printf("Sleeping for %d seconds\n", timeout); sleep(timeout); } } return 0; }
3,760
C
.c
115
29.156522
73
0.675228
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,584
vendor.h
cleech_open-isns/vendor.h
/* * iSNS "vendor-specific" protocol definitions * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_VENDOR_H #define ISNS_VENDOR_H #include <libisns/isns-proto.h> /* * We're poor, we don't own a OUI. Let's fake one. */ #define OPENISNS_VENDOR_OUI 0xFFFF00 #define OPENISNS_VENDOR_PREFIX (OPENISNS_VENDOR_OUI << 8) #define OPENISNS_IS_PRIVATE_ATTR(tag) (((tag) >> 16) == 0xFFFF) enum openisns_vendor_tag { /* Security Policy Identifier */ OPENISNS_TAG_POLICY_SPI = OPENISNS_VENDOR_PREFIX + ISNS_VENDOR_SPECIFIC_OTHER_BASE, __OPENISNS_TAG_POLICY_RESERVED, /* DSA signature key (public) */ OPENISNS_TAG_POLICY_KEY, /* Entity name to use */ OPENISNS_TAG_POLICY_ENTITY, /* Functions the client is permitted to invoke */ OPENISNS_TAG_POLICY_FUNCTIONS, /* Object types the client is permitted to see. */ OPENISNS_TAG_POLICY_OBJECT_TYPE, /* iSCSI node name the client is permitted to register. * This attribute may occur multiple times. * If absent, it defaults to POLICY_SOURCE_NAME */ OPENISNS_TAG_POLICY_NODE_NAME, /* Node type bitmap the client is permitted to register */ OPENISNS_TAG_POLICY_NODE_TYPE, /* Default discovery domain the client will be * placed in. * Not used yet. */ OPENISNS_TAG_POLICY_DEFAULT_DD, OPENISNS_TAG_POLICY_VISIBLE_DD, }; extern const struct isns_object_template isns_policy_template; #endif /* ISNS_VENDOR_H */
1,409
C
.h
42
31.357143
84
0.74575
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,585
db.h
cleech_open-isns/db.h
/* * iSNS object database * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_DB_H #define ISNS_DB_H #include <libisns/attrs.h> typedef struct isns_db_backend isns_db_backend_t; /* * In-memory portion of object database. * Stable storage is provided by different * backends. */ struct isns_db { isns_object_list_t * id_objects; isns_object_list_t __id_objects; isns_relation_soup_t * id_relations; uint32_t id_last_eid; uint32_t id_last_index; isns_scope_t * id_global_scope; isns_scope_t * id_default_scope; isns_db_backend_t * id_backend; unsigned int id_in_transaction : 1; struct isns_db_trans * id_transact; /* This is for objects in limbo. When a client * calls DevAttrDereg, the object will first be * placed on the id_deferred list. * When we're done processing the message, we * invoke isns_db_purge, which looks at these * objects. * - if the reference count is 1, the object * is deleted. * - otherwise, we assume the object is referenced * by a discovery domain. In this case, we prune * the attribute list down to the key attr(s) * plus the index attribute, and move it to * the id_limbo list. */ isns_object_list_t id_deferred; isns_object_list_t id_limbo; }; struct isns_db_backend { char * idb_name; int (*idb_reload)(isns_db_t *); int (*idb_sync)(isns_db_t *); int (*idb_store)(isns_db_t *, const isns_object_t *); int (*idb_remove)(isns_db_t *, const isns_object_t *); }; extern isns_db_backend_t *isns_create_file_db_backend(const char *); extern isns_object_t * __isns_db_get_next(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *, const isns_attr_list_t *); extern isns_relation_soup_t *isns_relation_soup_alloc(void); extern isns_relation_t *isns_create_relation(isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2); extern void isns_relation_sever(isns_relation_t *); extern void isns_relation_release(isns_relation_t *); extern void isns_relation_add(isns_relation_soup_t *, isns_relation_t *); extern void isns_relation_remove(isns_relation_soup_t *, isns_relation_t *); extern isns_object_t * isns_relation_get_other(const isns_relation_t *, const isns_object_t *); extern isns_relation_t *isns_relation_find_edge(isns_relation_soup_t *, const isns_object_t *, const isns_object_t *, unsigned int); extern void isns_relation_halfspace(isns_relation_soup_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern void isns_relation_get_edge_objects(isns_relation_soup_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern int isns_relation_exists(isns_relation_soup_t *, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type); extern int isns_relation_is_dead(const isns_relation_t *); extern void isns_db_create_relation(isns_db_t *db, isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2); extern void isns_db_get_relationship_objects(isns_db_t *, const isns_object_t *, unsigned int relation_type, isns_object_list_t *); extern isns_object_t * isns_db_get_relationship_object(isns_db_t *, const isns_object_t *, const isns_object_t *, unsigned int relation_type); extern int isns_db_relation_exists(isns_db_t *db, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type); extern int isns_db_create_pg_relation(isns_db_t *, isns_object_t *); extern isns_scope_t * isns_scope_for_call(isns_db_t *, const isns_simple_t *); extern isns_scope_t * isns_scope_alloc(isns_db_t *); extern void isns_scope_release(isns_scope_t *); extern void isns_scope_add(isns_scope_t *, isns_object_t *); extern int isns_scope_remove(isns_scope_t *, isns_object_t *); extern int isns_scope_gang_lookup(isns_scope_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern isns_object_t * isns_scope_get_next(isns_scope_t *, isns_object_template_t *, const isns_attr_list_t *current, const isns_attr_list_t *scope); extern void isns_scope_get_related(isns_scope_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern isns_db_t * isns_scope_get_db(const isns_scope_t *); #endif /* ISNS_DB_H */
4,651
C
.h
128
32.914063
78
0.704263
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,590
util.h
cleech_open-isns/include/libisns/util.h
/* * Utility functions * * Copyright (C) 2006, 2007 Olaf Kirch <[email protected]> */ #ifndef UTIL_H #define UTIL_H #include <sys/types.h> #include <stdint.h> #include <stdio.h> #include <stddef.h> #include <string.h> // for strdup #include <signal.h> #include <libisns/types.h> #define array_num_elements(a) (sizeof(a) / sizeof((a)[0])) const char * isns_dirname(const char *); int isns_mkdir_recursive(const char *); extern const char *parser_separators; char * parser_get_next_line(FILE *); char * parser_get_next_word(char **); char * parser_get_rest_of_line(char **); int parser_split_line(char *, unsigned int, char **); unsigned long parse_size(const char *); unsigned int parse_count(const char *); int parse_int(const char *); long long parse_longlong(const char *); double parse_double(const char *); unsigned int parse_timeout(const char *); char * print_size(unsigned long); /* * for signal management */ static inline void signals_hold(void) { sighold(SIGTERM); sighold(SIGINT); } static inline void signals_release(void) { sigrelse(SIGTERM); sigrelse(SIGINT); } /* * Very simple and stupid string array. */ struct string_array { unsigned int count; char ** list; }; void isns_string_array_append(struct string_array *, const char *); void isns_string_array_destroy(struct string_array *); void isns_assign_string(char **, const char *); void isns_write_pidfile(const char *); void isns_update_pidfile(const char *); void isns_remove_pidfile(const char *); extern void isns_log_background(void); extern void isns_assert_failed(const char *, const char *, unsigned int); extern void isns_fatal(const char *, ...); extern void isns_warning(const char *, ...); extern void isns_error(const char *, ...); extern void isns_notice(const char *, ...); extern void isns_debug_general(const char *, ...); extern void isns_debug_socket(const char *, ...); extern void isns_debug_protocol(const char *, ...); extern void isns_debug_message(const char *, ...); extern void isns_debug_state(const char *, ...); extern void isns_debug_auth(const char *, ...); extern void isns_debug_scn(const char *, ...); extern void isns_debug_esi(const char *, ...); extern void isns_enable_debugging(const char *); extern int isns_debug_enabled(int); enum { DBG_GENERAL = 0, DBG_SOCKET, DBG_PROTOCOL, DBG_MESSAGE, DBG_STATE, DBG_AUTH, DBG_SCN, DBG_ESI, }; /* * There's no htonll yet */ #ifndef htonll # if defined(__GLIBC__) || defined(__linux__) # include <endian.h> # include <byteswap.h> # if __BYTE_ORDER == __BIG_ENDIAN # define htonll(x) (x) # define ntohll(x) (x) # elif __BYTE_ORDER == __LITTLE_ENDIAN # define htonll(x) __bswap_64(x) # define ntohll(x) __bswap_64(x) # endif # else # if defined(__FreeBSD__) # include <sys/endian.h> # else # include <endian.h> # endif # define htonll(x) htobe64(x) # define ntohll(x) be64toh(x) # endif #endif /* * FreeBSD's libc doesn't define this for userland code */ #ifndef s6_addr32 #define s6_addr32 __u6_addr.__u6_addr32 #endif /* * One of the those eternal staples of C coding: */ #ifndef MIN # define MIN(a, b) ((a) < (b)? (a) : (b)) # define MAX(a, b) ((a) > (b)? (a) : (b)) #endif #define DECLARE_BITMAP(name, NBITS) \ uint32_t name[(NBITS+31) >> 5] = { 0 } #define __BIT_INDEX(nr) (nr >> 5) #define __BIT_MASK(nr) (1 << (nr & 31)) static inline void set_bit(uint32_t *map, unsigned int nr) { map[__BIT_INDEX(nr)] |= __BIT_MASK(nr); } static inline void clear_bit(uint32_t *map, unsigned int nr) { map[__BIT_INDEX(nr)] &= ~__BIT_MASK(nr); } static inline int test_bit(const uint32_t *map, unsigned int nr) { return !!(map[__BIT_INDEX(nr)] & __BIT_MASK(nr)); } /* * Dynamically sized bit vector */ extern isns_bitvector_t *isns_bitvector_alloc(void); extern void isns_bitvector_init(isns_bitvector_t *); extern void isns_bitvector_destroy(isns_bitvector_t *); extern void isns_bitvector_free(isns_bitvector_t *); extern int isns_bitvector_test_bit(const isns_bitvector_t *, unsigned int); extern int isns_bitvector_set_bit(isns_bitvector_t *, unsigned int); extern int isns_bitvector_clear_bit(isns_bitvector_t *, unsigned int); extern int isns_bitvector_is_empty(const isns_bitvector_t *); extern int isns_bitvector_intersect(const isns_bitvector_t *a, const isns_bitvector_t *b, isns_bitvector_t *result); extern void isns_bitvector_print(const isns_bitvector_t *, isns_print_fn_t *); extern void isns_bitvector_foreach(const isns_bitvector_t *bv, int (*cb)(uint32_t, void *), void *user_data); /* * List manipulation primites */ typedef struct isns_list isns_list_t; struct isns_list { isns_list_t * next; isns_list_t * prev; }; #define ISNS_LIST_DECLARE(list) \ isns_list_t list = { &list, &list } static inline void isns_list_init(isns_list_t *head) { head->next = head->prev = head; } static inline void __isns_list_insert(isns_list_t *prev, isns_list_t *item, isns_list_t *next) { item->next = next; item->prev = prev; next->prev = item; prev->next = item; } static inline void isns_list_append(isns_list_t *head, isns_list_t *item) { __isns_list_insert(head->prev, item, head); } static inline void isns_list_insert(isns_list_t *head, isns_list_t *item) { __isns_list_insert(head, item, head->next); } static inline void isns_item_insert_before(isns_list_t *where, isns_list_t *item) { __isns_list_insert(where->prev, item, where); } static inline void isns_item_insert_after(isns_list_t *where, isns_list_t *item) { __isns_list_insert(where, item, where->next); } static inline void isns_list_del(isns_list_t *item) { isns_list_t *prev = item->prev; isns_list_t *next = item->next; prev->next = next; next->prev = prev; item->next = item->prev = item; } static inline int isns_list_empty(const isns_list_t *head) { return head == head->next; } static inline void isns_list_move(isns_list_t *dst, isns_list_t *src) { isns_list_t *prev, *next; isns_list_t *head, *tail; if (isns_list_empty(src)) return; prev = dst->prev; next = dst; head = src->next; tail = src->prev; next->prev = tail; prev->next = head; head->prev = prev; tail->next = next; src->next = src->prev = src; } #define isns_list_item(type, member, ptr) \ container_of(type, member, ptr) #define isns_list_foreach(list, __pos, __next) \ for (__pos = (list)->next; \ (__pos != list) && (__next = __pos->next, 1); \ __pos = __next) #if 0 /* This is defined in stddef */ #define offsetof(type, member) ((unsigned long) &(((type *) 0)->member)) #endif #define container_of(type, member, ptr) \ ((type *) (((unsigned char *) ptr) - offsetof(type, member))) /* * Use isns_assert instead of libc's assert, so that the * message can be captured and sent to syslog. */ #define isns_assert(condition) do { \ if (!(condition)) \ isns_assert_failed(#condition, \ __FILE__, __LINE__); \ } while (0) #ifndef MDEBUG # define isns_malloc(size) malloc(size) # define isns_calloc(n, size) calloc(n, size) # define isns_realloc(p, size) realloc(p, size) # define isns_strdup(s) strdup(s) # define isns_free(p) free(p) #else # define isns_malloc(size) isns_malloc_fn(size, __FILE__, __LINE__) # define isns_calloc(n, size) isns_calloc_fn(n, size, __FILE__, __LINE__) # define isns_realloc(p, size) isns_realloc_fn(p, size, __FILE__, __LINE__) # define isns_strdup(s) isns_strdup_fn(s, __FILE__, __LINE__) # define isns_free(p) isns_free_fn(p, __FILE__, __LINE__) extern void * (*isns_malloc_fn)(size_t, const char *, unsigned int); extern void * (*isns_calloc_fn)(unsigned int, size_t, const char *, unsigned int); extern void * (*isns_realloc_fn)(void *, size_t, const char *, unsigned int); extern char * (*isns_strdup_fn)(const char *, const char *, unsigned int); extern void (*isns_free_fn)(void *, const char *, unsigned int); #endif #endif /* UTIL_H */
7,896
C
.h
273
27.29304
76
0.690561
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,062,591
message.h
cleech_open-isns/include/libisns/message.h
/* * iSNS message definitions and functions * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_MESSAGE_H #define ISNS_MESSAGE_H #include <libisns/attrs.h> #include <libisns/source.h> #include <libisns/util.h> typedef struct isns_message_queue isns_message_queue_t; #ifdef SCM_CREDENTIALS /* Linux-style SCM_CREDENTIALS + struct ucred */ typedef struct ucred struct_cmsgcred_t; #define CMSGCRED_uid uid #define SCM_CREDENTIALS_portable SCM_CREDENTIALS #elif defined(SCM_CREDS) /* FreeBSD-style SCM_CREDS + struct cmsgcred_t */ typedef struct cmsgcred struct_cmsgcred_t; #define CMSGCRED_uid cmcred_euid #define SCM_CREDENTIALS_portable SCM_CREDS #else /* If a platform requires something else, this must be added * here. */ #error "Neither SCM_CREDENTIALS nor SCM_CREDS supported on your platform for credentials passing over AF_LOCAL sockets." #endif struct isns_simple { uint32_t is_function; isns_source_t * is_source; isns_policy_t * is_policy; uint16_t is_xid; unsigned int is_replace : 1; isns_attr_list_t is_message_attrs; isns_attr_list_t is_operating_attrs; }; struct isns_message { unsigned int im_users; isns_list_t im_list; struct sockaddr_storage im_addr; socklen_t im_addrlen; uint32_t im_xid; struct isns_hdr im_header; struct isns_buf * im_payload; isns_socket_t * im_socket; isns_principal_t * im_security; struct_cmsgcred_t * im_creds; isns_message_queue_t * im_queue; /* When to retransmit */ struct timeval im_resend_timeout; struct timeval im_timeout; void (*im_destroy)(isns_message_t *); void (*im_callback)(isns_message_t *, isns_message_t *); void * im_calldata; }; enum { ISNS_MQ_SORT_NONE, ISNS_MQ_SORT_RESEND_TIMEOUT, }; struct isns_message_queue { isns_list_t imq_list; size_t imq_count; }; struct isns_server { isns_source_t * is_source; isns_db_t * is_db; isns_scn_callback_fn_t *is_scn_callback; struct isns_service_ops *is_ops; }; extern isns_message_t * __isns_alloc_message(uint32_t, size_t, void (*)(isns_message_t *)); extern isns_security_t *isns_message_security(const isns_message_t *); extern isns_message_t * isns_message_queue_find(isns_message_queue_t *, uint32_t, const struct sockaddr_storage *, socklen_t); extern void isns_message_queue_insert_sorted(isns_message_queue_t *, int, isns_message_t *); extern void isns_message_queue_move(isns_message_queue_t *, isns_message_t *); extern void isns_message_queue_destroy(isns_message_queue_t *); extern isns_simple_t * isns_simple_create(uint32_t, isns_source_t *, const isns_attr_list_t *); extern void isns_simple_free(isns_simple_t *); extern int isns_simple_encode(isns_simple_t *, isns_message_t **result); extern int isns_simple_decode(isns_message_t *, isns_simple_t **); extern int isns_simple_encode_response(isns_simple_t *, const isns_message_t *, isns_message_t **); extern int isns_simple_response_get_objects(isns_simple_t *, isns_object_list_t *); extern const char * isns_function_name(uint32_t); extern isns_source_t * isns_simple_get_source(isns_simple_t *); extern int isns_process_registration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_query(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_getnext(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn_register(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_dd_registration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_dd_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_esi(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn(isns_server_t *, isns_simple_t *, isns_simple_t **); /* * Inline functions for message queues. */ static inline void isns_message_queue_init(isns_message_queue_t *q) { isns_list_init(&q->imq_list); q->imq_count = 0; } static inline isns_message_t * isns_message_queue_head(const isns_message_queue_t *q) { isns_list_t *pos = q->imq_list.next; if (pos == &q->imq_list) return NULL; return isns_list_item(isns_message_t, im_list, pos); } static inline void isns_message_queue_append(isns_message_queue_t *q, isns_message_t *msg) { isns_assert(msg->im_queue == NULL); isns_list_append(&q->imq_list, &msg->im_list); q->imq_count++; msg->im_queue = q; msg->im_users++; } static inline isns_message_t * isns_message_queue_remove(isns_message_queue_t *q, isns_message_t *msg) { isns_assert(msg->im_queue == q); isns_list_del(&msg->im_list); msg->im_queue = NULL; q->imq_count--; return msg; } static inline isns_message_t * isns_message_unlink(isns_message_t *msg) { if (msg->im_queue) return isns_message_queue_remove(msg->im_queue, msg); return NULL; } static inline isns_message_t * isns_message_dequeue(isns_message_queue_t *q) { isns_message_t *msg; if ((msg = isns_message_queue_head(q)) != NULL) { isns_list_del(&msg->im_list); msg->im_queue = NULL; q->imq_count--; } return msg; } /* * Iterator for looping over all messages in a queue */ static inline void isns_message_queue_begin(isns_message_queue_t *q, isns_list_t **pos) { *pos = q->imq_list.next; } static inline isns_message_t * isns_message_queue_next(isns_message_queue_t *q, isns_list_t **pos) { isns_list_t *next = *pos; if (next == &q->imq_list) return NULL; *pos = next->next; return isns_list_item(isns_message_t, im_list, next); } #define isns_message_queue_foreach(q, pos, item) \ for (isns_message_queue_begin(q, &pos); \ (item = isns_message_queue_next(q, &pos)) != NULL; \ ) #endif /* ISNS_MESSAGE_H */
5,918
C
.h
177
31.491525
120
0.721696
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,595
attrs.h
cleech_open-isns/include/libisns/attrs.h
/* * iSNS object attributes * * Copyright (C) 2007 Olaf Kirch <[email protected]> */ #ifndef ISNS_ATTRS_H #define ISNS_ATTRS_H #include <netinet/in.h> #include <libisns/buffer.h> #include <libisns/isns.h> /* * Type identifier */ enum { ISNS_ATTR_TYPE_NIL = 0, ISNS_ATTR_TYPE_OPAQUE, ISNS_ATTR_TYPE_STRING, ISNS_ATTR_TYPE_INT32, ISNS_ATTR_TYPE_UINT32, ISNS_ATTR_TYPE_UINT64, ISNS_ATTR_TYPE_IPADDR, ISNS_ATTR_TYPE_RANGE16, __ISNS_ATTR_TYPE_BUILTIN_MAX }; /* * Union holding an attribute value */ typedef struct isns_value { const struct isns_attr_type * iv_type; /* Data is stuffed into an anonymous union */ union { uint32_t iv_nil; struct __isns_opaque { void * ptr; size_t len; } iv_opaque; char * iv_string; int32_t iv_int32; uint32_t iv_uint32; uint64_t iv_uint64; struct in6_addr iv_ipaddr; struct { uint16_t min, max; } iv_range; }; } isns_value_t; #define __ISNS_ATTRTYPE(type) isns_attr_type_##type #define __ISNS_MEMBER(type) iv_##type #define ISNS_VALUE_INIT(type, value) \ (isns_value_t) { .iv_type = &__ISNS_ATTRTYPE(type), \ { .__ISNS_MEMBER(type) = (value) } } #define isns_attr_initialize(attrp, tag, type, value) do { \ isns_attr_t *__attr = (attrp); \ uint32_t __tag = (tag); \ __attr->ia_users = 1; \ __attr->ia_tag_id = (__tag); \ __attr->ia_tag = isns_tag_type_by_id(__tag); \ __attr->ia_value = ISNS_VALUE_INIT(type, value); \ } while (0) #define ISNS_ATTR_INIT(tag, type, value) (isns_attr_t) { \ .ia_users = 1, \ .ia_tag_id = (tag), \ .ia_tag = isns_tag_type_by_id(tag), \ .ia_value = ISNS_VALUE_INIT(type, value) \ } /* * Attribute type */ typedef struct isns_attr_type { uint32_t it_id; const char * it_name; void (*it_assign)(isns_value_t *, const isns_value_t *); int (*it_set)(isns_value_t *, const void *); int (*it_get)(isns_value_t *, void *); int (*it_match)(const isns_value_t *, const isns_value_t *); int (*it_compare)(const isns_value_t *, const isns_value_t *); int (*it_encode)(buf_t *, const isns_value_t *); int (*it_decode)(buf_t *, size_t, isns_value_t *); void (*it_destroy)(isns_value_t *); void (*it_print)(const isns_value_t *, char *, size_t); int (*it_parse)(isns_value_t *, const char *); } isns_attr_type_t; /* * Tag info: for each tag, provides a printable name, * and the attribute type associated with it. */ struct isns_tag_type { uint32_t it_id; const char * it_name; unsigned int it_multiple : 1, it_readonly : 1; isns_attr_type_t *it_type; int (*it_validate)(const isns_value_t *, const isns_policy_t *); void (*it_print)(const isns_value_t *, char *, size_t); int (*it_parse)(isns_value_t *, const char *); const char * (*it_help)(void); }; /* * Attribute */ struct isns_attr { unsigned int ia_users; uint32_t ia_tag_id; const isns_tag_type_t * ia_tag; isns_value_t ia_value; }; extern isns_attr_type_t isns_attr_type_nil; extern isns_attr_type_t isns_attr_type_opaque; extern isns_attr_type_t isns_attr_type_string; extern isns_attr_type_t isns_attr_type_int32; extern isns_attr_type_t isns_attr_type_uint32; extern isns_attr_type_t isns_attr_type_uint64; extern isns_attr_type_t isns_attr_type_ipaddr; extern isns_attr_type_t isns_attr_type_range16; extern isns_attr_t * isns_attr_alloc(uint32_t, const isns_tag_type_t *, const isns_value_t *); extern void isns_attr_list_append_value(isns_attr_list_t *, uint32_t tag, const isns_tag_type_t *, const isns_value_t *); extern void isns_attr_list_update_value(isns_attr_list_t *, uint32_t tag, const isns_tag_type_t *, const isns_value_t *); extern int isns_attr_list_get_value(const isns_attr_list_t *, uint32_t tag, isns_value_t *); extern int isns_attr_list_get_uint32(const isns_attr_list_t *, uint32_t tag, uint32_t *); extern int isns_attr_list_get_string(const isns_attr_list_t *, uint32_t tag, const char **); extern int isns_attr_list_validate(const isns_attr_list_t *, const isns_policy_t *, unsigned int function); extern int isns_attr_validate(const isns_attr_t *, const isns_policy_t *); extern void isns_attr_list_prune(isns_attr_list_t *, const uint32_t *, unsigned int); extern int isns_attr_list_remove_member(isns_attr_list_t *, const isns_attr_t *, const uint32_t *); extern void isns_attr_list_update_attr(isns_attr_list_t *, const isns_attr_t *); extern int isns_attr_decode(buf_t *, isns_attr_t **); extern int isns_attr_encode(buf_t *, const isns_attr_t *); extern int isns_attr_list_decode(buf_t *, isns_attr_list_t *); extern int isns_attr_list_decode_delimited(buf_t *, isns_attr_list_t *); extern int isns_attr_list_encode(buf_t *, const isns_attr_list_t *); extern int isns_encode_delimiter(buf_t *); extern const isns_tag_type_t *isns_tag_type_by_id(unsigned int); extern const isns_attr_type_t *isns_attr_type_by_id(unsigned int); typedef struct isns_quick_attr_list isns_quick_attr_list_t; struct isns_quick_attr_list { isns_attr_list_t iqa_list; isns_attr_t * iqa_attrs[1]; isns_attr_t iqa_attr; }; #define ISNS_QUICK_ATTR_LIST_DECLARE(qlist, tag, type, value) \ isns_quick_attr_list_t qlist = { \ .iqa_list = (isns_attr_list_t) { \ .ial_data = qlist.iqa_attrs, \ .ial_count = 1 \ }, \ .iqa_attrs = { &qlist.iqa_attr }, \ .iqa_attr = ISNS_ATTR_INIT(tag, type, value), \ } /* * The following is used to chop up an incoming attr list as * given in eg. a DevAttrReg message into separate chunks, * following the ordering constraints laid out in the RFC. * * isns_attr_list_scanner_init initializes the scanner state. * * isns_attr_list_scanner_next advances to the next object in * the list, returning the keys and attrs for one object. * * The isns_attr_list_scanner struct should really be opaque, but * we put it here so you can declare a scanner variable on the * stack. */ struct isns_attr_list_scanner { isns_source_t * source; isns_policy_t * policy; isns_object_t * key_obj; isns_attr_list_t orig_attrs; unsigned int pos; isns_attr_list_t keys; isns_attr_list_t attrs; isns_object_template_t *tmpl; unsigned int num_key_attrs; unsigned int entities; uint32_t pgt_next_attr; uint32_t pgt_value; const char * pgt_iscsi_name; isns_portal_info_t pgt_portal_info; isns_object_t * pgt_base_object; unsigned int index_acceptable : 1; }; extern void isns_attr_list_scanner_init(struct isns_attr_list_scanner *, isns_object_t *key_obj, const isns_attr_list_t *attrs); extern int isns_attr_list_scanner_next(struct isns_attr_list_scanner *); extern void isns_attr_list_scanner_destroy(struct isns_attr_list_scanner *); /* * The following is used to parse attribute lists given as * a bunch of strings. */ struct isns_attr_list_parser { struct isns_tag_prefix *prefix; const char * default_port; unsigned int multi_type_permitted : 1, nil_permitted : 1; isns_attr_t * (*load_key)(const char *); isns_attr_t * (*generate_key)(void); }; extern int isns_attr_list_split(char *line, char **argv, unsigned int argc_max); extern void isns_attr_list_parser_init(struct isns_attr_list_parser *, isns_object_template_t *); extern int isns_parse_attrs(unsigned int, char **, isns_attr_list_t *, struct isns_attr_list_parser *); extern int isns_parse_query_attrs(unsigned int, char **, isns_attr_list_t *, isns_attr_list_t *, struct isns_attr_list_parser *); extern void isns_attr_list_parser_help(struct isns_attr_list_parser *); extern isns_object_template_t *isns_attr_list_parser_context(const struct isns_attr_list_parser *); extern int isns_print_attrs(isns_object_t *, char **, unsigned int); #endif /* ISNS_ATTRS_H */
7,786
C
.h
229
31.532751
99
0.690058
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,062,598
isns.h
cleech_open-isns/include/libisns/isns.h
/* * iSNS implementation - library header file. * * Copyright (C) 2007 Olaf Kirch <[email protected]> * * This file contains all declarations and definitions * commonly required by users of libisns. */ #ifndef ISNS_H #define ISNS_H #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <stdio.h> #include <libisns/isns-proto.h> #include <libisns/types.h> #define ISNS_MAX_BUFFER 8192 #define ISNS_MAX_MESSAGE 8192 /* * Client handle */ typedef struct isns_client isns_client_t; struct isns_client { isns_source_t * ic_source; isns_socket_t * ic_socket; }; /* * Server operations */ typedef int isns_service_fn_t(isns_server_t *, isns_simple_t *, isns_simple_t **); typedef void isns_scn_callback_fn_t(isns_db_t *, uint32_t scn_bits, isns_object_template_t *node_type, const char *node_name, const char *recipient); struct isns_service_ops { isns_service_fn_t * process_registration; isns_service_fn_t * process_query; isns_service_fn_t * process_getnext; isns_service_fn_t * process_deregistration; isns_service_fn_t * process_scn_registration; isns_service_fn_t * process_scn_deregistration; isns_service_fn_t * process_scn_event; isns_service_fn_t * process_scn; isns_service_fn_t * process_dd_registration; isns_service_fn_t * process_dd_deregistration; isns_service_fn_t * process_esi; isns_service_fn_t * process_heartbeat; }; extern struct isns_service_ops isns_default_service_ops; extern struct isns_service_ops isns_callback_service_ops; /* * Output function */ void isns_print_stdout(const char *, ...); void isns_print_stderr(const char *, ...); /* * Database events */ struct isns_db_event { isns_object_t * ie_recipient; /* Recipient node or NULL */ isns_object_t * ie_object; /* Affected object */ isns_object_t * ie_trigger; /* Triggering object */ unsigned int ie_bits; /* SCN bitmask */ }; typedef void isns_db_callback_t(const isns_db_event_t *, void *user_data); /* * Handling of client objects */ extern isns_client_t * isns_create_default_client(isns_security_t *); extern isns_client_t * isns_create_client(isns_security_t *, const char *source_name); extern isns_client_t * isns_create_local_client(isns_security_t *, const char *source_name); extern int isns_client_call(isns_client_t *, isns_simple_t **inout); extern void isns_client_destroy(isns_client_t *); extern int isns_client_get_local_address(const isns_client_t *, isns_portal_info_t *); /* * Handling of server objects */ extern isns_server_t * isns_create_server(isns_source_t *, isns_db_t *, struct isns_service_ops *); extern void isns_server_set_scn_callback(isns_server_t *, isns_scn_callback_fn_t *); /* * Handling of source names */ extern int isns_init_names(void); extern const char * isns_default_source_name(void); extern isns_source_t * isns_source_create(isns_attr_t *); extern isns_source_t * isns_source_create_iscsi(const char *name); extern isns_source_t * isns_source_create_ifcp(const char *name); extern uint32_t isns_source_type(const isns_source_t *); extern const char * isns_source_name(const isns_source_t *); extern isns_attr_t * isns_source_attr(const isns_source_t *); extern isns_source_t * isns_source_get(isns_source_t *); extern isns_source_t * isns_source_from_object(const isns_object_t *); extern void isns_source_release(isns_source_t *); extern int isns_source_match(const isns_source_t *, const isns_source_t *); extern void isns_server_set_source(isns_source_t *); extern isns_message_t * isns_process_message(isns_server_t *, isns_message_t *); extern void isns_simple_print(isns_simple_t *, isns_print_fn_t *); extern int isns_simple_call(isns_socket_t *, isns_simple_t **); extern int isns_simple_transmit(isns_socket_t *, isns_simple_t *, const isns_portal_info_t *, unsigned int, void (*callback)(uint32_t, int, isns_simple_t *)); extern void isns_simple_free(isns_simple_t *); extern const isns_attr_list_t *isns_simple_get_attrs(isns_simple_t *); extern isns_simple_t * isns_create_query(isns_client_t *clnt, const isns_attr_list_t *query_key); extern isns_simple_t * isns_create_query2(isns_client_t *clnt, const isns_attr_list_t *query_key, isns_source_t *source); extern int isns_query_request_attr_tag(isns_simple_t *, uint32_t); extern int isns_query_request_attr(isns_simple_t *, isns_attr_t *); extern int isns_query_response_get_objects(isns_simple_t *qry, isns_object_list_t *result); extern isns_simple_t * isns_create_registration(isns_client_t *clnt, isns_object_t *key_object); extern isns_simple_t * isns_create_registration2(isns_client_t *clnt, isns_object_t *key_object, isns_source_t *source); extern void isns_registration_set_replace(isns_simple_t *, int); extern void isns_registration_add_object(isns_simple_t *, isns_object_t *object); extern void isns_registration_add_object_list(isns_simple_t *, isns_object_list_t *); extern int isns_registration_response_get_objects(isns_simple_t *, isns_object_list_t *); extern isns_simple_t * isns_create_getnext(isns_client_t *, isns_object_template_t *, const isns_attr_list_t *); extern int isns_getnext_response_get_object(isns_simple_t *, isns_object_t **); extern isns_simple_t * isns_create_getnext_followup(isns_client_t *, const isns_simple_t *, const isns_attr_list_t *); extern isns_simple_t * isns_create_deregistration(isns_client_t *clnt, const isns_attr_list_t *); extern isns_simple_t * isns_create_scn_registration(isns_client_t *clnt, unsigned int); extern isns_simple_t * isns_create_scn_registration2(isns_client_t *clnt, unsigned int, isns_source_t *); extern int isns_dd_load_all(isns_db_t *); extern void isns_dd_get_members(uint32_t, isns_object_list_t *, int); extern isns_simple_t * isns_create_dd_registration(isns_client_t *, const isns_attr_list_t *); extern isns_simple_t * isns_create_dd_deregistration(isns_client_t *, uint32_t, const isns_attr_list_t *); extern isns_object_t * isns_create_object(isns_object_template_t *, const isns_attr_list_t *, isns_object_t *); extern isns_object_t * isns_create_entity(int, const char *); extern isns_object_t * isns_create_entity_for_source(const isns_source_t *, const char *); extern const char * isns_entity_name(const isns_object_t *); extern isns_object_t * isns_create_portal(const isns_portal_info_t *, isns_object_t *parent); extern isns_object_t * isns_create_storage_node(const char *name, uint32_t type_mask, isns_object_t *parent); extern isns_object_t * isns_create_storage_node2(const isns_source_t *, uint32_t type_mask, isns_object_t *parent); extern isns_object_t * isns_create_iscsi_initiator(const char *name, isns_object_t *parent); extern isns_object_t * isns_create_iscsi_target(const char *name, isns_object_t *parent); extern const char * isns_storage_node_name(const isns_object_t *); extern isns_attr_t * isns_storage_node_key_attr(const isns_object_t *); extern isns_object_t * isns_create_portal_group(isns_object_t *portal, isns_object_t *iscsi_node, uint32_t pg_tag); extern isns_object_t * isns_create_default_portal_group(isns_db_t *, isns_object_t *portal, isns_object_t *node); extern void isns_get_portal_groups(isns_object_t *portal, isns_object_t *node, isns_object_list_t *result); extern const char * isns_object_template_name(isns_object_template_t *); extern int isns_object_set_attr(isns_object_t *, isns_attr_t *); extern int isns_object_set_attrlist(isns_object_t *, const isns_attr_list_t *); extern isns_object_t * isns_object_get(isns_object_t *); extern int isns_object_get_attrlist(isns_object_t *obj, isns_attr_list_t *result, const isns_attr_list_t *requested_attrs); extern int isns_object_get_key_attrs(isns_object_t *, isns_attr_list_t *); extern int isns_object_get_attr(const isns_object_t *, uint32_t, isns_attr_t **); extern void isns_object_get_related(isns_db_t *, isns_object_t *, isns_object_list_t *); extern void isns_object_get_descendants(const isns_object_t *, isns_object_template_t *, isns_object_list_t *); extern void isns_object_release(isns_object_t *); extern int isns_object_match(const isns_object_t *, const isns_attr_list_t *); extern isns_object_t * isns_object_get_entity(isns_object_t *); extern int isns_object_attr_valid(isns_object_template_t *, uint32_t); extern int isns_object_contains(const isns_object_t *, const isns_object_t *); extern int isns_object_delete_attr(isns_object_t *, uint32_t); extern int isns_object_is(const isns_object_t *, isns_object_template_t *); extern int isns_object_is_entity(const isns_object_t *); extern int isns_object_is_iscsi_node(const isns_object_t *); extern int isns_object_is_fc_port(const isns_object_t *); extern int isns_object_is_fc_node(const isns_object_t *); extern int isns_object_is_portal(const isns_object_t *); extern int isns_object_is_pg(const isns_object_t *); extern int isns_object_is_policy(const isns_object_t *); extern int isns_object_is_dd(const isns_object_t *); extern int isns_object_is_ddset(const isns_object_t *); extern void isns_object_print(isns_object_t *, isns_print_fn_t *); extern time_t isns_object_last_modified(const isns_object_t *); extern int isns_object_mark_membership(isns_object_t *, uint32_t); extern int isns_object_clear_membership(isns_object_t *, uint32_t); extern int isns_object_test_membership(const isns_object_t *, uint32_t); extern int isns_object_test_visibility(const isns_object_t *, const isns_object_t *); extern void isns_object_get_visible(const isns_object_t *, isns_db_t *, isns_object_list_t *); extern void isns_entity_touch(isns_object_t *); extern int isns_object_extract_keys(const isns_object_t *, isns_attr_list_t *); extern int isns_object_extract_all(const isns_object_t *, isns_attr_list_t *); extern int isns_object_extract_writable(const isns_object_t *, isns_attr_list_t *); extern int isns_object_set_nil(isns_object_t *obj, uint32_t tag); extern int isns_object_set_string(isns_object_t *obj, uint32_t tag, const char *value); extern int isns_object_set_uint32(isns_object_t *obj, uint32_t tag, uint32_t value); extern int isns_object_set_uint64(isns_object_t *obj, uint32_t tag, uint64_t value); extern int isns_object_set_ipaddr(isns_object_t *obj, uint32_t tag, const struct in6_addr *value); extern int isns_object_get_string(const isns_object_t *, uint32_t, const char **); extern int isns_object_get_ipaddr(const isns_object_t *, uint32_t, struct in6_addr *); extern int isns_object_get_uint32(const isns_object_t *, uint32_t, uint32_t *); extern int isns_object_get_uint64(const isns_object_t *, uint32_t, uint64_t *); extern int isns_object_get_opaque(const isns_object_t *, uint32_t, const void **, size_t *); extern int isns_object_find_descendants(isns_object_t *obj, isns_object_template_t *, const isns_attr_list_t *keys, isns_object_list_t *result); extern isns_object_t * isns_object_find_descendant(isns_object_t *obj, const isns_attr_list_t *keys); extern int isns_object_detach(isns_object_t *); extern int isns_object_attach(isns_object_t *, isns_object_t *); extern void isns_object_prune_attrs(isns_object_t *); extern void isns_mark_object(isns_object_t *, unsigned int); extern int isns_get_entity_identifier(isns_object_t *, const char **); extern int isns_get_entity_protocol(isns_object_t *, isns_entity_protocol_t *); extern int isns_get_entity_index(isns_object_t *, uint32_t *); extern int isns_get_portal_ipaddr(isns_object_t *, struct in6_addr *); extern int isns_get_portal_tcpudp_port(isns_object_t *, int *ipprotocol, uint16_t *port); extern int isns_get_portal_index(isns_object_t *, uint32_t *); extern int isns_get_address(struct sockaddr_storage *, const char *, const char *, int, int, int); extern char * isns_get_canon_name(const char *); extern isns_db_t * isns_db_open(const char *location); extern isns_db_t * isns_db_open_shadow(isns_object_list_t *); extern isns_object_t * isns_db_lookup(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *); extern isns_object_t * isns_db_vlookup(isns_db_t *, isns_object_template_t *, ...); extern int isns_db_gang_lookup(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern isns_object_t * isns_db_get_next(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *current, const isns_attr_list_t *scope, const isns_source_t *source); extern isns_object_t * isns_db_lookup_source_node(isns_db_t *, const isns_source_t *); extern void isns_db_get_domainless(isns_db_t *, isns_object_template_t *, isns_object_list_t *); extern uint32_t isns_db_allocate_index(isns_db_t *); extern void isns_db_insert(isns_db_t *, isns_object_t *); extern void isns_db_insert_limbo(isns_db_t *, isns_object_t *); extern int isns_db_remove(isns_db_t *, isns_object_t *); extern time_t isns_db_expire(isns_db_t *); extern void isns_db_purge(isns_db_t *); extern void isns_db_sync(isns_db_t *); extern const char * isns_db_generate_eid(isns_db_t *, char *, size_t); extern isns_object_t * isns_db_get_control(isns_db_t *); extern void isns_db_print(isns_db_t *, isns_print_fn_t *); extern void isns_db_begin_transaction(isns_db_t *); extern void isns_db_commit(isns_db_t *); extern void isns_db_rollback(isns_db_t *); extern void isns_object_event(isns_object_t *obj, unsigned int bits, isns_object_t *trigger); extern void isns_unicast_event(isns_object_t *dst, isns_object_t *obj, unsigned int bits, isns_object_t *trigger); extern void isns_register_callback(isns_db_callback_t *, void *); extern void isns_flush_events(void); extern const char * isns_event_string(unsigned int); extern void isns_add_timer(unsigned int, isns_timer_callback_t *, void *); extern void isns_add_oneshot_timer(unsigned int, isns_timer_callback_t *, void *); extern void isns_cancel_timer(isns_timer_callback_t *, void *); extern time_t isns_run_timers(void); extern void isns_object_list_init(isns_object_list_t *); extern void isns_object_list_destroy(isns_object_list_t *); extern int isns_object_list_contains(const isns_object_list_t *, isns_object_t *); extern void isns_object_list_append(isns_object_list_t *, isns_object_t *); extern void isns_object_list_append_list(isns_object_list_t *, const isns_object_list_t *); extern isns_object_t * isns_object_list_lookup(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *); extern int isns_object_list_gang_lookup(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern int isns_object_list_remove(isns_object_list_t *, isns_object_t *); extern void isns_object_list_uniq(isns_object_list_t *); extern void isns_object_list_print(const isns_object_list_t *, isns_print_fn_t *); isns_object_template_t *isns_object_template_for_key_attrs(const isns_attr_list_t *); isns_object_template_t *isns_object_template_for_tag(uint32_t); isns_object_template_t *isns_object_template_for_index_tag(uint32_t); isns_object_template_t *isns_object_template_find(uint32_t); extern int isns_attr_set(isns_attr_t *, const void *); extern isns_attr_t * isns_attr_get(isns_attr_t *); extern void isns_attr_release(isns_attr_t *); extern void isns_attr_print(const isns_attr_t *, isns_print_fn_t *); extern char * isns_attr_print_value(const isns_attr_t *, char *, size_t); extern int isns_attr_match(const isns_attr_t *, const isns_attr_t *); extern int isns_attr_compare(const isns_attr_t *, const isns_attr_t *); extern isns_attr_t * isns_attr_from_string(uint32_t, const char *); extern void isns_attr_list_print(const isns_attr_list_t *, isns_print_fn_t *); extern void isns_attr_list_init(isns_attr_list_t *); extern void isns_attr_list_copy(isns_attr_list_t *, const isns_attr_list_t *); extern void isns_attr_list_destroy(isns_attr_list_t *); extern int isns_attr_list_remove_tag(isns_attr_list_t *, uint32_t); extern void isns_attr_list_append_attr(isns_attr_list_t *, isns_attr_t *); extern void isns_attr_list_append_list(isns_attr_list_t *, const isns_attr_list_t *); extern int isns_attr_list_replace_attr(isns_attr_list_t *, isns_attr_t *); /* Warning: this does *NOT* return a reference to the attribute */ extern int isns_attr_list_get_attr(const isns_attr_list_t *, uint32_t tag, isns_attr_t **); extern void isns_attr_list_append_nil(isns_attr_list_t *, uint32_t tag); extern void isns_attr_list_append_string(isns_attr_list_t *, uint32_t tag, const char *value); extern void isns_attr_list_append_uint32(isns_attr_list_t *, uint32_t tag, uint32_t value); extern void isns_attr_list_append_uint64(isns_attr_list_t *, uint32_t, int64_t); extern void isns_attr_list_append_int32(isns_attr_list_t *, uint32_t tag, int32_t value); extern void isns_attr_list_append_opaque(isns_attr_list_t *, uint32_t tag, const void *ptr, size_t len); extern void isns_attr_list_append_ipaddr(isns_attr_list_t *, uint32_t tag, const struct in6_addr *); extern int isns_attr_list_append(isns_attr_list_t *, uint32_t tag, const void *); extern int isns_attr_list_update(isns_attr_list_t *, uint32_t tag, const void *); extern int isns_attr_list_contains(const isns_attr_list_t *, uint32_t tag); extern int isns_attr_list_compare(const isns_attr_list_t *, const isns_attr_list_t *); /* * Helper macros */ #define ISNS_ATTR_TYPE_CHECK(attr, type) \ ((attr)->ia_value.iv_type == &isns_attr_type_##type) #define ISNS_ATTR_IS_NIL(attr) \ ISNS_ATTR_TYPE_CHECK(attr, nil) #define ISNS_ATTR_IS_STRING(attr) \ ISNS_ATTR_TYPE_CHECK(attr, string) #define ISNS_ATTR_IS_IPADDR(attr) \ ISNS_ATTR_TYPE_CHECK(attr, ipaddr) #define ISNS_ATTR_IS_UINT32(attr) \ ISNS_ATTR_TYPE_CHECK(attr, uint32) #define ISNS_ATTR_IS_UINT64(attr) \ ISNS_ATTR_TYPE_CHECK(attr, uint64) #define ISNS_ATTR_IS_OPAQUE(attr) \ ISNS_ATTR_TYPE_CHECK(attr, opaque) extern isns_socket_t * isns_create_server_socket(const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_create_client_socket(const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_create_systemd_socket(int index); extern isns_socket_t * isns_create_bound_client_socket(const char *myaddr, const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_connect_to_portal(const isns_portal_info_t *); extern void isns_socket_set_report_failure(isns_socket_t *); extern void isns_socket_set_disconnect_fatal(isns_socket_t *); extern int isns_socket_get_local_addr(const isns_socket_t *, struct sockaddr_storage *); extern int isns_socket_get_portal_info(const isns_socket_t *, isns_portal_info_t *); extern void isns_socket_set_security_ctx(isns_socket_t *, isns_security_t *); extern isns_message_t * isns_recv_message(struct timeval *timeout); extern isns_message_t * isns_socket_call(isns_socket_t *, isns_message_t *, long); extern int isns_socket_send(isns_socket_t *, isns_message_t *); extern void isns_socket_free(isns_socket_t *); extern int isns_addr_get_port(const struct sockaddr *); extern void isns_addr_set_port(struct sockaddr *, unsigned int); extern isns_socket_t * isns_socket_find_server(const isns_portal_info_t *); extern isns_message_t * isns_create_message(uint16_t function, uint16_t flags); extern isns_message_t * isns_create_reply(const isns_message_t *); extern int isns_message_init(isns_message_t *, uint16_t, uint16_t, size_t); extern int isns_message_status(isns_message_t *); extern void isns_message_release(isns_message_t *); extern unsigned int isns_message_function(const isns_message_t *); extern isns_socket_t * isns_message_socket(const isns_message_t *); extern void isns_message_set_error(isns_message_t *, uint32_t); extern const char * isns_strerror(enum isns_status); extern const char * isns_function_name(unsigned int); /* * Security related functions */ extern int isns_security_init(void); extern isns_principal_t *isns_security_load_privkey(isns_security_t *, const char *filename); extern isns_principal_t *isns_security_load_pubkey(isns_security_t *, const char *filename); extern isns_security_t *isns_default_security_context(int server_only); extern isns_security_t *isns_control_security_context(int server_only); extern isns_security_t *isns_create_dsa_context(void); extern void isns_security_set_identity(isns_security_t *, isns_principal_t *); extern void isns_principal_free(isns_principal_t *); extern void isns_add_principal(isns_security_t *, isns_principal_t *); extern isns_keystore_t *isns_create_keystore(const char *); extern void isns_security_set_keystore(isns_security_t *, isns_keystore_t *); extern void isns_principal_set_name(isns_principal_t *, const char *); extern const char * isns_principal_name(const isns_principal_t *); extern isns_object_template_t isns_entity_template; extern isns_object_template_t isns_portal_template; extern isns_object_template_t isns_iscsi_node_template; extern isns_object_template_t isns_fc_port_template; extern isns_object_template_t isns_fc_node_template; extern isns_object_template_t isns_iscsi_pg_template; extern isns_object_template_t isns_dd_template; extern isns_object_template_t isns_ddset_template; /* * Config file parser */ struct isns_config { char * ic_host_name; char * ic_auth_name; char * ic_source_name; char * ic_source_suffix; char * ic_entity_name; char * ic_iqn_prefix; char * ic_server_name; char * ic_bind_address; char * ic_database; char * ic_auth_key_file; char * ic_server_key_file; char * ic_client_keystore; char * ic_control_socket; char * ic_pidfile; char * ic_local_registry_file; int ic_security; int ic_slp_register; char * ic_control_name; char * ic_control_key_file; unsigned int ic_registration_period; unsigned int ic_scn_timeout; unsigned int ic_scn_retries; char * ic_scn_callout; unsigned int ic_esi_max_interval; unsigned int ic_esi_min_interval; unsigned int ic_esi_retries; unsigned int ic_use_default_domain; struct { unsigned int policy; unsigned int replay_window; unsigned int timestamp_jitter; int allow_unknown_peers; } ic_auth; struct { unsigned int max_sockets; unsigned int connect_timeout; unsigned int reconnect_timeout; unsigned int call_timeout; unsigned int udp_retrans_timeout; unsigned int tcp_retrans_timeout; unsigned int idle_timeout; } ic_network; struct { char * param_file; unsigned int key_bits; } ic_dsa; }; extern struct isns_config isns_config; extern int isns_read_initiatorname(const char *); extern int isns_read_config(const char *); extern int isns_config_set(const char *, char *); /* * Reserved entity name for Policy information */ #define ISNS_ENTITY_CONTROL "CONTROL" /* * Helpers to deal with portal information */ struct isns_portal_info { struct sockaddr_in6 addr; int proto; }; extern void isns_portal_init(isns_portal_info_t *, const struct sockaddr *, int); extern int isns_portal_parse(isns_portal_info_t *portal, const char *addr_spec, const char *default_port); extern int isns_portal_from_attr_list(isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, const isns_attr_list_t *); extern int isns_portal_from_attr_pair(isns_portal_info_t *, const isns_attr_t *, const isns_attr_t *); extern int isns_portal_from_object(isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, const isns_object_t *); extern int isns_portal_from_sockaddr(isns_portal_info_t *, const struct sockaddr_storage *); extern int isns_portal_to_sockaddr(const isns_portal_info_t *, struct sockaddr_storage *); extern int isns_portal_to_attr_list(const isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, isns_attr_list_t *); extern int isns_portal_to_object(const isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, isns_object_t *); extern int isns_portal_is_wildcard(const isns_portal_info_t *); extern uint32_t isns_portal_tcpudp_port(const isns_portal_info_t *); extern char * isns_portal_string(const isns_portal_info_t *); extern int isns_portal_equal(const isns_portal_info_t *, const isns_portal_info_t *); extern int isns_enumerate_portals(isns_portal_info_t *, unsigned int); extern int isns_get_nr_portals(void); /* Local registry stuff */ extern int isns_local_registry_load(const char *, pid_t, isns_object_list_t *); extern int isns_local_registry_store(const char *, pid_t, const isns_object_list_t *); extern int isns_local_registry_purge(const char *, pid_t); /* Should go somwhere else .*/ extern int isns_esi_enabled; extern void isns_esi_init(isns_server_t *); extern void isns_esi_register(isns_object_t *); extern void isns_scn_init(isns_server_t *); extern time_t isns_scn_transmit_all(void); #endif /* ISNS_H */
25,481
C
.h
607
39.401977
92
0.726848
cleech/open-isns
2
28
0
LGPL-2.1
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
16,074,373
stm32f4_dac.h
guyt101z_codec2/stm32/inc/stm32f4_dac.h
/*---------------------------------------------------------------------------*\ FILE........: stm32f4_dac.h AUTHOR......: David Rowe DATE CREATED: 1 June 2013 DAC driver module for STM32F4. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2013 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. 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 Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef __STM32F4_DAC__ #define __STM32F4_DAC__ void dac_open(void); int dac_write(short buf[], int n); #endif
1,044
C
.c
24
40.791667
79
0.635644
guyt101z/codec2
2
41
0
LGPL-2.1
9/7/2024, 2:35:51 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,074,377
stm32f4_dac.c
guyt101z_codec2/stm32/src/stm32f4_dac.c
/*---------------------------------------------------------------------------*\ FILE........: stm32f4_dac.c AUTHOR......: David Rowe DATE CREATED: 1 June 2013 DAC driver module for STM32F4. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2013 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. 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 Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <stdlib.h> #include <string.h> #include "stm32f4xx.h" #include "codec2_fifo.h" #include "stm32f4_dac.h" #define DAC_DHR12R2_ADDRESS 0x40007414 #define DAC_DHR12L2_ADDRESS 0x40007418 #define DAC_BUF_SZ 320 #define FIFO_SZ 8000 #define DAC_MAX 4096 DAC_InitTypeDef DAC_InitStructure; struct FIFO *DMA1_Stream6_fifo; unsigned short dac_buf[DAC_BUF_SZ]; static void TIM6_Config(void); static void DAC_Ch2_Config(void); int dac_underflow; void dac_open(void) { memset(dac_buf, 32768, sizeof(short)*DAC_BUF_SZ); /* Create fifo */ DMA1_Stream6_fifo = fifo_create(FIFO_SZ); assert(DMA1_Stream6_fifo != NULL); /*!< At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup files (startup_stm32f40xx.s/startup_stm32f427x.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f4xx.c file */ /* Preconfiguration before using DAC----------------------------------------*/ GPIO_InitTypeDef GPIO_InitStructure; /* DMA1 clock enable */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE); /* GPIOA clock enable (to be used with DAC) */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* DAC Periph clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE); /* DAC channel 1 & 2 (DAC_OUT1 = PA.4)(DAC_OUT2 = PA.5) configuration */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA, &GPIO_InitStructure); /* TIM6 Configuration ------------------------------------------------------*/ TIM6_Config(); DAC_Ch2_Config(); } /* Accepts signed 16 bit samples */ int dac_write(short buf[], int n) { return fifo_write(DMA1_Stream6_fifo, buf, n); } /** * @brief TIM6 Configuration * @note TIM6 configuration is based on APB1 frequency * @note TIM6 Update event occurs each TIM6CLK/256 * @param None * @retval None */ static void TIM6_Config(void) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; /* TIM6 Periph clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE); /* -------------------------------------------------------- TIM3 input clock (TIM6CLK) is set to 2 * APB1 clock (PCLK1), since APB1 prescaler is different from 1 (see system_stm32f4xx.c and Fig 13 clock tree figure in DM0031020.pdf). Sample rate Fs = 2*PCLK1/TIM_ClockDivision = (HCLK/2)/TIM_ClockDivision ----------------------------------------------------------- */ /* Time base configuration */ TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = 5250; TIM_TimeBaseStructure.TIM_Prescaler = 0; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM6, &TIM_TimeBaseStructure); /* TIM6 TRGO selection */ TIM_SelectOutputTrigger(TIM6, TIM_TRGOSource_Update); /* TIM6 enable counter */ TIM_Cmd(TIM6, ENABLE); } /** * @brief DAC Channel2 SineWave Configuration * @param None * @retval None */ static void DAC_Ch2_Config(void) { DMA_InitTypeDef DMA_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; /* DAC channel2 Configuration */ DAC_InitStructure.DAC_Trigger = DAC_Trigger_T6_TRGO; DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None; DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable; DAC_Init(DAC_Channel_2, &DAC_InitStructure); /* DMA1_Stream6 channel7 configuration **************************************/ DMA_DeInit(DMA1_Stream6); DMA_InitStructure.DMA_Channel = DMA_Channel_7; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)DAC_DHR12L2_ADDRESS; DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)dac_buf; DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral; DMA_InitStructure.DMA_BufferSize = DAC_BUF_SZ; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_Priority = DMA_Priority_High; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA1_Stream6, &DMA_InitStructure); /* Enable DMA Half & Complete interrupts */ DMA_ITConfig(DMA1_Stream6, DMA_IT_TC | DMA_IT_HT, ENABLE); /* Enable the DMA Stream IRQ Channel */ NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream6_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable DMA1_Stream6 */ DMA_Cmd(DMA1_Stream6, ENABLE); /* Enable DAC Channel2 */ DAC_Cmd(DAC_Channel_2, ENABLE); /* Enable DMA for DAC Channel2 */ DAC_DMACmd(DAC_Channel_2, ENABLE); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f40xx.s/startup_stm32f427x.s). */ /******************************************************************************/ /* This function handles DMA Stream interrupt request. */ void DMA1_Stream6_IRQHandler(void) { int i, sam; short signed_buf[DAC_BUF_SZ/2]; /* Transfer half empty interrupt */ if(DMA_GetITStatus(DMA1_Stream6, DMA_IT_HTIF6) != RESET) { /* fill first half from fifo */ if (fifo_read(DMA1_Stream6_fifo, signed_buf, DAC_BUF_SZ/2) == -1) { memset(signed_buf, 0, sizeof(short)*DAC_BUF_SZ/2); dac_underflow++; } /* convert to unsigned */ for(i=0; i<DAC_BUF_SZ/2; i++) { sam = (int)signed_buf[i] + 32768; dac_buf[i] = (unsigned short)(sam); } /* Clear DMA Stream Transfer Complete interrupt pending bit */ DMA_ClearITPendingBit(DMA1_Stream6, DMA_IT_HTIF6); } /* Transfer complete interrupt */ if(DMA_GetITStatus(DMA1_Stream6, DMA_IT_TCIF6) != RESET) { /* fill second half from fifo */ if (fifo_read(DMA1_Stream6_fifo, signed_buf, DAC_BUF_SZ/2) == -1) { memset(signed_buf, 0, sizeof(short)*DAC_BUF_SZ/2); dac_underflow++; } /* convert to unsigned */ for(i=0; i<DAC_BUF_SZ/2; i++) { sam = (int)signed_buf[i] + 32768; dac_buf[i+DAC_BUF_SZ/2] = (unsigned short)(sam); } /* Clear DMA Stream Transfer Complete interrupt pending bit */ DMA_ClearITPendingBit(DMA1_Stream6, DMA_IT_TCIF6); } }
8,644
C
.c
190
39.142105
83
0.637175
guyt101z/codec2
2
41
0
LGPL-2.1
9/7/2024, 2:35:51 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,074,383
stm32f4_adc.c
guyt101z_codec2/stm32/src/stm32f4_adc.c
/*---------------------------------------------------------------------------*\ FILE........: stm32f4_adc.c AUTHOR......: David Rowe DATE CREATED: 4 June 2013 ADC driver module for STM32F4. TODO: [X] just get ADC to run at all, prove its sampling something.... [X] as above with DMA [X] half and finished interrupts, ISR [ ] timer config to drive ADC conversion, measure sample rate and confirm 16kHz + larger ADC DMA buffer + fifos + work out a way to unit test [ ] ADC working at same time as DAC [ ] remove (or make optional) the TIM_Config() code that sends PWM output to pins [ ] check comments still valid \*---------------------------------------------------------------------------*/ /* Copyright (C) 2013 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. 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 Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <stdlib.h> #include <string.h> #include "stm32f4xx_adc.h" #include "stm32f4xx_gpio.h" #include "stm32f4xx_rcc.h" #include "codec2_fifo.h" #include "gdb_stdio.h" #define ADC_BUF_SZ 320 #define FIFO_SZ 8000 struct FIFO *DMA2_Stream0_fifo; unsigned short adc_buf[ADC_BUF_SZ]; int adc_overflow; int half,full; #define ADCx_DR_ADDRESS ((uint32_t)0x4001204C) #define DMA_CHANNELx DMA_Channel_0 #define DMA_STREAMx DMA2_Stream0 #define ADCx ADC1 #define TIM1_CCR3_ADDRESS 0x4001223C TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; uint16_t uhTimerPeriod; uint16_t aSRC_Buffer[3] = {0, 0, 0}; void Timer1Config(); void adc_configure(); #define REC_TIME_SECS 30 #define N 2000 #define FS 16000 int main(void){ short buf[N]; FILE *frec; int i, bufs; DMA2_Stream0_fifo = fifo_create(FIFO_SZ); assert(DMA2_Stream0_fifo != NULL); Timer1Config(); adc_configure(); ADC_SoftwareStartConv(ADC1); frec = fopen("stm_out.raw", "wb"); if (frec == NULL) { printf("Error opening input file: stm_out.raw\n\nTerminating....\n"); exit(1); } bufs = FS*REC_TIME_SECS/N; printf("Starting!\n"); for(i=0; i<bufs; i++) { //ConvertedValue = adc_convert(); //printf("ConvertedValue = %d\n", ConvertedValue); printf("adc_buf: %d %d half: %d full: %d adc_overflow: %d\n", adc_buf[0],adc_buf[ADC_BUF_SZ-1], half, full, adc_overflow); while(fifo_read(DMA2_Stream0_fifo, buf, N) == -1); fwrite(buf, sizeof(short), N, frec); } fclose(frec); printf("Finished!\n"); } /* DR: TIM_Config configures a couple of I/O pins for PWM output from Timer1 Channel 3. Note I dont think any of this is needed, except perhaps to check timer frequency. Can be removed down the track. */ /** * @brief Configure the TIM1 Pins. * @param None * @retval None */ static void TIM_Config(void) { GPIO_InitTypeDef GPIO_InitStructure; /* GPIOA and GPIOB clock enable */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB, ENABLE); /* GPIOA Configuration: Channel 3 as alternate function push-pull */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 ; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_TIM1); /* GPIOB Configuration: Channel 3N as alternate function push-pull */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_TIM1); } void Timer1Config() { /* TIM Configuration */ TIM_Config(); /* TIM1 example ------------------------------------------------- TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), since APB2 prescaler is different from 1. TIM1CLK = 2 * PCLK2 PCLK2 = HCLK / 2 => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock SystemCoreClock is set to 168 MHz for STM32F4xx devices. The objective is to configure TIM1 channel 3 to generate complementary PWM signal with a frequency equal to F KHz: - TIM1_Period = (SystemCoreClock / F) - 1 The number of this repetitive requests is defined by the TIM1 Repetion counter, each 3 Update Requests, the TIM1 Channel 3 Duty Cycle changes to the next new value defined by the aSRC_Buffer. Note: SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file. Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate() function to update SystemCoreClock variable value. Otherwise, any configuration based on this variable will be incorrect. -----------------------------------------------------------------------------*/ /* Compute the value to be set in ARR regiter to generate signal frequency at 16.00 Khz */ uhTimerPeriod = (SystemCoreClock / 16000 ) - 1; /* Compute CCR1 value to generate a duty cycle at 50% */ aSRC_Buffer[0] = (uint16_t) (((uint32_t) 5 * (uhTimerPeriod - 1)) / 10); /* Compute CCR1 value to generate a duty cycle at 37.5% */ aSRC_Buffer[1] = (uint16_t) (((uint32_t) 375 * (uhTimerPeriod - 1)) / 1000); /* Compute CCR1 value to generate a duty cycle at 25% */ aSRC_Buffer[2] = (uint16_t) (((uint32_t) 25 * (uhTimerPeriod - 1)) / 100); /* TIM1 Peripheral Configuration -------------------------------------------*/ /* TIM1 clock enable */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); /* Time Base configuration */ TIM_DeInit(TIM1); TIM_TimeBaseStructure.TIM_Prescaler = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStructure.TIM_Period = uhTimerPeriod; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); /* Channel 3 Configuration in PWM mode */ /* I think we just ned to enable channel 3 somehow, but without (or optionally with) actual ouput to a GPIO pin. */ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; TIM_OCInitStructure.TIM_Pulse = aSRC_Buffer[0]; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; TIM_OC3Init(TIM1, &TIM_OCInitStructure); /* Enable preload feature */ TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable); /* TIM1 counter enable */ TIM_Cmd(TIM1, ENABLE); /* Main Output Enable */ TIM_CtrlPWMOutputs(TIM1, ENABLE); } void adc_configure(){ ADC_InitTypeDef ADC_init_structure; GPIO_InitTypeDef GPIO_initStructre; DMA_InitTypeDef DMA_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; // Clock configuration RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1ENR_GPIOCEN,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE); // Analog pin configuration GPIO_initStructre.GPIO_Pin = GPIO_Pin_0; // ADC Channel 10 is connected to PC0 GPIO_initStructre.GPIO_Mode = GPIO_Mode_AN; GPIO_initStructre.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOC,&GPIO_initStructre); // ADC structure configuration ADC_DeInit(); ADC_init_structure.ADC_DataAlign = ADC_DataAlign_Left; ADC_init_structure.ADC_Resolution = ADC_Resolution_12b; ADC_init_structure.ADC_ContinuousConvMode = DISABLE; ADC_init_structure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC3; ADC_init_structure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_Rising; ADC_init_structure.ADC_NbrOfConversion = 1; ADC_init_structure.ADC_ScanConvMode = DISABLE; ADC_Init(ADCx,&ADC_init_structure); // Select the channel to be read from ADC_RegularChannelConfig(ADCx,ADC_Channel_10,1,ADC_SampleTime_144Cycles); /* DMA configuration **************************************/ DMA_DeInit(DMA_STREAMx); DMA_InitStructure.DMA_Channel = DMA_CHANNELx; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADCx_DR_ADDRESS; DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)adc_buf; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory; DMA_InitStructure.DMA_BufferSize = ADC_BUF_SZ; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_Priority = DMA_Priority_High; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA_STREAMx, &DMA_InitStructure); /* Enable DMA request after last transfer (Single-ADC mode) */ ADC_DMARequestAfterLastTransferCmd(ADCx, ENABLE); /* Enable ADC1 DMA */ ADC_DMACmd(ADCx, ENABLE); /* DMA2_Stream0 enable */ DMA_Cmd(DMA_STREAMx, ENABLE); /* Enable DMA Half & Complete interrupts */ DMA_ITConfig(DMA2_Stream0, DMA_IT_TC | DMA_IT_HT, ENABLE); /* Enable the DMA Stream IRQ Channel */ NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); // Enable ADC conversion ADC_Cmd(ADC1,ENABLE); } /* This function handles DMA Stream interrupt request. */ void DMA2_Stream0_IRQHandler(void) { int i, sam; short signed_buf[ADC_BUF_SZ/2]; /* Half transfer interrupt */ if(DMA_GetITStatus(DMA2_Stream0, DMA_IT_HTIF0) != RESET) { half++; /* convert to signed */ for(i=0; i<ADC_BUF_SZ/2; i++) { sam = (int)adc_buf[i] - 32768; //sam = (int)adc_buf[i]; signed_buf[i] = sam; } /* write first half to fifo */ if (fifo_write(DMA2_Stream0_fifo, signed_buf, ADC_BUF_SZ/2) == -1) { adc_overflow++; } /* Clear DMA Stream Transfer Complete interrupt pending bit */ DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_HTIF0); } /* Transfer complete interrupt */ if(DMA_GetITStatus(DMA2_Stream0, DMA_IT_TCIF0) != RESET) { full++; /* convert to signed */ for(i=0; i<ADC_BUF_SZ/2; i++) { sam = (int)adc_buf[ADC_BUF_SZ/2 + i] - 32768; //sam = (int)adc_buf[ADC_BUF_SZ/2 + i]; signed_buf[i] = sam; } /* write second half to fifo */ if (fifo_write(DMA2_Stream0_fifo, signed_buf, ADC_BUF_SZ/2) == -1) { adc_overflow++; } /* Clear DMA Stream Transfer Complete interrupt pending bit */ DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_TCIF0); } }
12,213
C
.c
273
39.252747
95
0.672245
guyt101z/codec2
2
41
0
LGPL-2.1
9/7/2024, 2:35:51 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,186,644
delta_run.c
tilaksidduram_android_packages_apps_OpenDelta/jni/delta_run.c
/* * Copyright (C) 2013 Jorrit "Chainfire" Jongma * Copyright (C) 2013 The OmniROM Project */ /* * This file is part of OpenDelta. * * OpenDelta 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. * * OpenDelta 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 OpenDelta. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <string.h> #include <fcntl.h> #include "delta.h" int main(int argc, char *argv[]) { if (argc >= 4) { dedelta(argv[1], argv[2], argv[3]); return 0; } printf("dedelta - Copyright (c) 2013 Jorrit Jongma (Chainfire)\n"); printf("\n"); printf("Usage: dedelta source delta output\n"); return 0; }
1,111
C
.c
34
30.735294
71
0.727866
tilaksidduram/android_packages_apps_OpenDelta
2
110
0
GPL-3.0
9/7/2024, 2:36:19 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,186,648
delta.c
tilaksidduram_android_packages_apps_OpenDelta/jni/delta.c
/* * Copyright (C) 2013 Jorrit "Chainfire" Jongma * Copyright (C) 2013 The OmniROM Project */ /* * This file is part of OpenDelta. * * OpenDelta 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. * * OpenDelta 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 OpenDelta. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include "xdelta3-3.0.7/xdelta3.h" #include "delta.h" static int xerror(char* message) { fprintf(stderr, "%s\n", message); return 0; } int dedelta(char* filenameSource, char* filenameDelta, char* filenameOut) { int ok = 0; int fsource = open(filenameSource, O_RDONLY); int fdelta = open(filenameDelta, O_RDONLY); unlink(filenameOut); int fout = open(filenameOut, O_CREAT | O_WRONLY, 0644); if ((fsource >= 0) && (fdelta >= 0) && (fout >= 0)) { int CHUNK = 256 * 1024; unsigned char* bsource = (unsigned char*)malloc(CHUNK); if (bsource == NULL) return xerror("Malloc failed"); unsigned char* bdelta = (unsigned char*)malloc(CHUNK); if (bdelta == NULL) return xerror("Malloc failed"); int ret; xd3_stream stream; xd3_config config; xd3_init_config (&config, 0 /* flags */); config.winsize = 32768; ret = xd3_config_stream (&stream, &config); if (ret != 0) return xerror("Error #1"); xd3_source source; source.name = filenameSource; source.ioh = NULL; source.blksize = CHUNK; source.curblkno = (xoff_t) -1; source.curblk = bsource; source.max_winsize = CHUNK; ret = xd3_set_source (&stream, &source); if (ret != 0) return xerror("Error #2"); int eof = 0; do { size_t r = read(fdelta, bdelta, CHUNK); if (r <= 0) { eof = 1; xd3_set_flags (&stream, XD3_FLUSH); } xd3_avail_input (&stream, bdelta, r); process: ret = xd3_decode_input (&stream); switch (ret) { case XD3_INPUT: continue; case XD3_OUTPUT: /* write data */ if (stream.avail_out > 0) if (write(fout, stream.next_out, stream.avail_out) != stream.avail_out) return xerror("Write error"); xd3_consume_output(&stream); goto process; case XD3_GETSRCBLK: /* set source block */ if (lseek(fsource, source.blksize * source.getblkno, SEEK_SET) == (off_t)-1) return xerror("Seek error"); source.onblk = read(fsource, bsource, source.blksize); source.curblkno = source.getblkno; goto process; case XD3_GOTHEADER: case XD3_WINSTART: case XD3_WINFINISH: /* no action necessary */ goto process; default: /* error */ return xerror("Error #3"); } } while (!eof); free(bsource); free(bdelta); xd3_close_stream(&stream); xd3_free_stream(&stream); ok = 1; } if (fsource >= 0) close(fsource); if (fdelta >= 0) close(fdelta); if (fout >= 0) close(fout); if (!ok) unlink(filenameOut); return ok; }
3,288
C
.c
104
28.528846
131
0.683412
tilaksidduram/android_packages_apps_OpenDelta
2
110
0
GPL-3.0
9/7/2024, 2:36:19 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,186,693
delta.h
tilaksidduram_android_packages_apps_OpenDelta/jni/delta.h
/* * Copyright (C) 2013 Jorrit "Chainfire" Jongma * Copyright (C) 2013 The OmniROM Project */ /* * This file is part of OpenDelta. * * OpenDelta 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. * * OpenDelta 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 OpenDelta. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __DELTA_H #define __DELTA_H int dedelta(char* filenameSource, char* filenameDelta, char* filenameOut); #endif
899
C
.h
24
35.583333
74
0.756881
tilaksidduram/android_packages_apps_OpenDelta
2
110
0
GPL-3.0
9/7/2024, 2:36:19 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,186,694
zipadjust.h
tilaksidduram_android_packages_apps_OpenDelta/jni/zipadjust.h
/* * Copyright (C) 2013 Jorrit "Chainfire" Jongma * Copyright (C) 2013 The OmniROM Project */ /* * This file is part of OpenDelta. * * OpenDelta 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. * * OpenDelta 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 OpenDelta. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __ZIPADJUST_H #define __ZIPADJUST_H int zipadjust(char* filenameIn, char* filenameOut, int decompress); #endif
900
C
.h
24
35.625
71
0.758305
tilaksidduram/android_packages_apps_OpenDelta
2
110
0
GPL-3.0
9/7/2024, 2:36:19 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,237
usb-tablet.c
OpenXT_input/usb-tablet.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #define NEW_X_RESOLUTION 32767 #define NEW_Y_RESOLUTION 32767 #define btnleft_newlypressed 2 struct tablet_scaling_params { double x_mult; double y_mult; int x_offs; int y_offs; uint8_t subtype; uint8_t btnleft; int tool; }; static struct tablet_scaling_params tscale[N_DEVS]; static int ignore_events[N_DEVS]; #ifndef ABS_MT_SLOT #define ABS_MT_SLOT 0x2f #endif #define ABS_MT_TRACKING_ID 0x39 #define MAXSLOTS 3 static int handle_gestures (struct input_event *e) { static int silence = 0; static int goSilent = 0; static int trackID[MAXSLOTS] = { -1, -1, -1 }; static int x[MAXSLOTS] = { -1, -1, -1 }; static int y[MAXSLOTS] = { -1, -1, -1 }; static int slot = -1; static int distance = 0; static int track_change = 0; int new_slot = -1; if ((e->type == EV_SYN) && (e->code == SYN_DROPPED)) { // Drop state distance = 0; track_change = 0; return 1; } if ((e->type == EV_ABS) && (e->code == ABS_MT_SLOT)) new_slot = e->value; if (slot < MAXSLOTS) { if (e->type == EV_ABS) { switch (e->code) { case ABS_MT_POSITION_X: distance += abs (x[slot] - e->value); x[slot] = e->value; break; case ABS_MT_POSITION_Y: distance += abs (y[slot] - e->value); y[slot] = e->value; break; case ABS_MT_TRACKING_ID: if ((trackID[slot] < 0) != (e->value < 0)) { track_change = 1; trackID[slot] = e->value; } break; } } if (((new_slot != -1) || ((e->type == EV_SYN) && (e->code == SYN_REPORT))) && ((slot < MAXSLOTS) && (slot >= 0))) { if (track_change || (distance > 1)) { goSilent = gesture_handler (slot, x[slot], y[slot], (track_change) ? ((trackID[slot] >= 0) ? 1 : 0) : -1); } /* reset vars for next set */ distance = 0; track_change = 0; } /* end new slot or syn_report */ } if (new_slot != -1) slot = new_slot; if ((e->type == EV_SYN) && (e->code == SYN_REPORT)) silence = goSilent; return (!silence); } /* endproc */ void set_and_inject_event(int slot, struct input_event* ev, int type, int code, int value) { ev->type = type; ev->code = code; ev->value = value; check_and_inject_event(ev,slot, HID_TYPE_TABLET); } void handle_usb_tablet_event (struct input_event *ev, int slot) { static int pen_inrange=0; struct input_event new_ev; new_ev.time = ev->time; new_ev.type = ev->type; new_ev.code = ev->code; new_ev.value = ev->value; struct tablet_scaling_params* t = &(tscale[slot]); if (new_ev.type == EV_ABS) { if (!pen_inrange || (t->subtype!=SUBTYPE_MONOTOUCH)) { if ((new_ev.code == ABS_X) || (new_ev.code == ABS_MT_POSITION_X)) new_ev.value = floor ( (new_ev.value - t->x_offs) * t->x_mult); else if ((new_ev.code == ABS_Y) || (new_ev.code == ABS_MT_POSITION_Y)) new_ev.value = floor ( (new_ev.value - t->y_offs) * t->y_mult); } else return; } else if (new_ev.type == EV_KEY) { /* Translate tablet codes into mouse codes, so it can be understood by drivers */ switch (new_ev.code) { case BTN_TOOL_PEN: if (new_ev.value) t->tool = BTN_LEFT; pen_inrange=new_ev.value; break; case BTN_TOOL_FINGER: if (new_ev.value) t->tool = BTN_TOOL_FINGER; break; case BTN_TOOL_RUBBER: if (new_ev.value) t->tool = BTN_RIGHT; pen_inrange=new_ev.value; break; case BTN_TOUCH: if (t->tool == BTN_TOOL_FINGER) { if (new_ev.value) { if ((t->btnleft==0) && (!pen_inrange)) t->btnleft=btnleft_newlypressed; break; } else if (t->btnleft) { new_ev.code=BTN_LEFT; t->btnleft=0; } else break; } else new_ev.code = t->tool; break; case BTN_STYLUS: new_ev.code = BTN_MIDDLE; break; } } if (new_ev.type == EV_SYN && new_ev.code == SYN_REPORT) { if (t->btnleft==btnleft_newlypressed) { t->btnleft=1; check_and_inject_event (&new_ev, slot, HID_TYPE_TABLET); set_and_inject_event(slot, &new_ev, EV_KEY, BTN_LEFT,1); set_and_inject_event(slot, &new_ev, EV_SYN, SYN_REPORT,0); return; } } // Check for SYN_DROPPED. Indicates buffer overrun, so no point forwarding any more of packet until next syn_report // Note that as any packets before the syn_dropped have already been transmitted, syn_dropped must still be transmitted // so that client knows to ignore them. if (new_ev.type == EV_SYN && new_ev.code == SYN_DROPPED) { ignore_events[slot] = 1; info ("Ignoring events from event%d until next packet begins", slot); } else if (ignore_events[slot]) { if (new_ev.type == EV_SYN && new_ev.code == SYN_REPORT) { ignore_events[slot] = 0; info ("End of dropped packet from event%d", slot); } else return; } if ((new_ev.type == EV_KEY) && (new_ev.code != ev->code)) { /* we want to send bot the mouse version and pen version */ check_and_inject_event (ev, slot, HID_TYPE_TABLET); } if (handle_gestures (&new_ev)) check_and_inject_event (&new_ev, slot, HID_TYPE_TABLET); } int init_usb_tablet (int fd, int slot, uint8_t subtype) { struct input_absinfo absinfo_x; struct input_absinfo absinfo_y; int ret = 0; int i; int diff; struct input_id id; struct tablet_scaling_params* t = &(tscale[slot]); ignore_events[slot] = 0; t->subtype = subtype; t->btnleft=0; t->tool=0; if (ioctl (fd, EVIOCGID, &id) == -1) return -1; if ((id.vendor==0x56a) && (id.product==0xed) && (subtype==SUBTYPE_MONOTOUCH)) // device lies { absinfo_x.minimum=380; absinfo_x.maximum=3820; absinfo_y.minimum=290; absinfo_y.maximum=3620; } else { if ((ret = ioctl (fd, EVIOCGABS (ABS_X), &absinfo_x)) < 0) return ret; if ((ret = ioctl (fd, EVIOCGABS (ABS_Y), &absinfo_y)) < 0) return ret; } t->x_offs = absinfo_x.minimum; diff = absinfo_x.maximum - absinfo_x.minimum; if (diff != 0) t->x_mult = ((double) NEW_X_RESOLUTION) / ((double) diff); else return -1; t->y_offs = absinfo_y.minimum; diff = absinfo_y.maximum - absinfo_y.minimum; if (diff != 0) t->y_mult = ((double) NEW_Y_RESOLUTION) / ((double) diff); else return -1; return 0; }
7,841
C
.c
249
24.562249
123
0.565217
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,239
xen_event.c
OpenXT_input/xen_event.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" static int xen_event_write_page(struct xen_vkbd_device *dev, union xenkbd_in_event *event) { uint32_t prod; struct xenkbd_page *page = dev->page; if (!page) return -1; prod = page->in_prod; xen_mb(); XENKBD_IN_RING_REF(page, prod) = *event; xen_wmb(); page->in_prod = prod + 1; return backend_evtchn_notify(dev->backend, dev->devid); } /* Send a keyboard (or mouse button) event */ static int xen_event_send_key(struct xen_vkbd_backend *backend, bool down, int keycode) { union xenkbd_in_event event; memset(&event, 0, XENKBD_IN_EVENT_SIZE); event.type = XENKBD_TYPE_KEY; event.key.pressed = down ? 1 : 0; event.key.keycode = keycode; if (keycode >= BTN_LEFT && keycode <= BTN_TASK) /* This is a mouse click, sending to the absolute device. */ return xen_event_write_page(backend->abs_device, &event); else return xen_event_write_page(backend->device, &event); } /* Send a relative mouse movement */ static int xen_event_send_motion(struct xen_vkbd_backend *backend, int rel_x, int rel_y, int rel_z) { union xenkbd_in_event event; memset(&event, 0, XENKBD_IN_EVENT_SIZE); event.type = XENKBD_TYPE_MOTION; event.motion.rel_x = rel_x; event.motion.rel_y = rel_y; event.motion.rel_z = rel_z; return xen_event_write_page(backend->device, &event); } /* Send an absolute mouse movement */ static int xen_event_send_position(struct xen_vkbd_backend *backend, int abs_x, int abs_y, int z) { union xenkbd_in_event event; memset(&event, 0, XENKBD_IN_EVENT_SIZE); event.type = XENKBD_TYPE_POS; event.pos.abs_x = abs_x; event.pos.abs_y = abs_y; event.pos.rel_z = z; return xen_event_write_page(backend->abs_device, &event); } void xen_event_send(struct xen_vkbd_backend *backend, uint16_t type, uint16_t code, int32_t value) { static int absolute_x=0, absolute_y=0, absolute_z=0, absolute=0; static int relative_x=0, relative_y=0, relative_z=0, relative=0; if (type == EV_KEY) xen_event_send_key(backend, value, code); /* Mouse motion */ if (type == EV_REL) { switch (code) { case REL_X: relative_x = value; break; case REL_Y: relative_y = value; break; case REL_WHEEL: relative_z = -value; break; } relative++; } if (type == EV_ABS) { switch (code) { case ABS_X: absolute_x = value; break; case ABS_Y: absolute_y = value; break; case ABS_WHEEL: absolute_z = -value; break; } absolute++; } if (type == EV_SYN && code == SYN_REPORT) { if (relative) { xen_event_send_motion(backend, relative_x, relative_y, relative_z); relative = relative_x = relative_y = relative_z = 0; } if (absolute) { xen_event_send_position(backend, absolute_x, absolute_y, absolute_z); absolute = absolute_z = 0; } } }
4,107
C
.c
129
25.193798
88
0.610564
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,240
putpic.c
OpenXT_input/putpic.c
/* * Copyright (c) 2010 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" static unsigned int intel_width = 0; static unsigned int intel_height = 0; static unsigned int intel_pitch = 0; static void *framebuffer = NULL; static struct blit_info { int x_off, y_off; int image_w, image_h; int min_w, min_h; } blit_i; static void png_blit_row(int row_num, unsigned char *src) { int y, x; unsigned char *dst; y = blit_i.y_off + row_num; if (y >= intel_height) return; dst = framebuffer + intel_pitch * y; for (x = 0; x < intel_width; ++x) { if (x >= blit_i.x_off && x < blit_i.min_w + blit_i.x_off) { *dst++ = src[2]; *dst++ = src[1]; *dst++ = src[0]; *dst++ = 0x00; src += 3; } else { *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; } } } static int png_blit_file(const char *file_name) { char header[8]; png_structp png_ptr; png_infop info_ptr; int width, height, color_type, bit_depth; /* open file and test for it being a png */ FILE *fp = fopen(file_name, "rb"); if (!fp) { fprintf(stderr, "[read_png_file] File %s could not be opened for reading\n", file_name); return 0; } fread(header, 1, 8, fp); if (png_sig_cmp(header, 0, 8)) { fprintf(stderr, "[read_png_file] File %s is not recognized as a PNG file\n", file_name); return 0; } /* initialize stuff */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fprintf(stderr, "[read_png_file] png_create_read_struct failed\n"); return 0; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { fprintf(stderr, "[read_png_file] png_create_info_struct failed\n"); return 0; } png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); width = info_ptr->width; height = info_ptr->height; color_type = info_ptr->color_type; bit_depth = info_ptr->bit_depth; if (color_type != PNG_COLOR_TYPE_RGB) { fprintf(stderr, "[read_png_file] wrong color type, expected PNG_COLOR_TYPE_RGB\n"); return 0; } png_read_update_info(png_ptr, info_ptr); blit_i.min_w = intel_width < width ? intel_width : width; blit_i.min_h = intel_height < height ? intel_height : height; blit_i.image_w = width; blit_i.image_h = height; /* offsets required to center image */ blit_i.y_off = ((int)intel_height - height) / 2; blit_i.x_off = ((int)intel_width - width) / 2; if (blit_i.x_off < 0) blit_i.x_off = 0; if (blit_i.y_off < 0) blit_i.y_off = 0; int y, x; unsigned char *dst = NULL; /* Pad top of screen with black */ for (y = 0; y < blit_i.y_off; ++y) { dst = framebuffer + intel_pitch*y; for (x = 0; x < intel_width; ++x) { *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; } } /* blit image rows */ png_bytep row = malloc(info_ptr->width*3); for (y = 0; y < info_ptr->height; ++y) { png_read_row(png_ptr, row, NULL); png_blit_row(y, row); } /* Pad bottom of screen with black */ for (y = blit_i.min_h + blit_i.y_off; y < intel_height; ++y) { dst = framebuffer + intel_pitch*y; for (x = 0; x < intel_width; ++x) { *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; *dst++ = 0x00; } } /* free png memory */ free(row); fclose(fp); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 1; } int main(int argc, char **argv) { const char *filename = NULL; if (argc != 2) { fprintf(stdout, "Usage: putpic IMAGE\n\n"); fprintf(stdout, "... where IMAGE is a filename of PNG image\n"); exit(1); } filename = argv[1]; if (intel_get_res(&intel_width, &intel_height, &intel_pitch)) { fprintf(stderr, "Failed to initialise gpu access\n"); exit(1); } framebuffer = intel_get_framebuffer(); if (!framebuffer) { fprintf(stderr,"No framebuffer\n"); exit(1); } png_blit_file(filename); return 0; }
5,096
C
.c
155
26.974194
96
0.584706
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,241
focus.c
OpenXT_input/focus.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #define DEATH_WINDOW_LENGTH 30 #define NSLOTS 11 struct slot { int domid; struct timeval death_window; int pvm; }; static struct slot slots[NSLOTS] = {}; void focus_expect_death (struct domain *d) { if (!d) return; if (d->slot < 0 || d->slot >= NSLOTS) return; gettimeofday (&slots[d->slot].death_window, NULL); } void focus_dont_expect_death (struct domain *d) { if (!d) return; if (d->slot < 0 || d->slot >= NSLOTS) return; slots[d->slot].death_window.tv_sec = 0; } static int expecting_death (int slot) { struct timeval now, diff; gettimeofday (&now, NULL); timersub (&now, &slots[slot].death_window, &diff); if (diff.tv_sec < 0) return 0; if (diff.tv_sec > DEATH_WINDOW_LENGTH) return 0; return 1; } static void focus_initial_switch(struct domain *d) { struct timeval now; /* switch to VM if its either a PVM or matches the focus uuid */ char *focus_uuid = NULL; focus_uuid = xenstore_read("/local/domain/0/switcher/focus-uuid"); if (d->is_pvm || (focus_uuid && d->uuid && !strcmp(focus_uuid, d->uuid))) { info("focus switch on domain creation to uuid=%s domid=%d", d->uuid, d->domid); switcher_switch(d, 0, 0); } free( focus_uuid ); gettimeofday(&now,NULL); d->last_input_event = now; } void focus_update_domain (struct domain *d) { if (!d) return; if (d->slot < 0 || d->slot >= NSLOTS) return; if ((slots[d->slot].domid != d->domid) || (slots[d->slot].pvm != d->is_pvm)) { info ("new incumbent for slot %d, last_domid=%d new_domid=%d last_was_pvm=%d, new_is_pvm=%d", d->slot, slots[d->slot].domid, d->domid, slots[d->slot].pvm, d->is_pvm); } /*Cancel any pending reboot timers */ focus_dont_expect_death (d); /*Update the pvm status: XXX note that this will be wrong for a just connected VM, but we don't care */ slots[d->slot].pvm = d->is_pvm; focus_initial_switch(d); } void focus_domain_gone (struct domain *d) { if (!d->is_pvm) return; info ("*** Trouble brewing - a non focused pvm died ***"); if ((d->slot < 0) || (d->slot >= NSLOTS)) return; if (expecting_death (d->slot)) { info ("- but it's rebooting so that's ok"); return; } switcher_switch (domain_uivm (), 0, 0); }
3,136
C
.c
107
25.943925
105
0.663004
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,243
secure_scripts.c
OpenXT_input/secure_scripts.c
/* * Copyright (c) 2010 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" int sec_check_pass(const char *uname, const char *userpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-check-pass"; int status; info("going to call %s with %s, %s", bin, uname, userpass_fname); switch (pid=fork()) { case 0: execl(bin, bin, uname, userpass_fname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_mount(const char *uname, const char *userpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-mount"; int status; info("going to call %s with %s, %s", bin, uname, userpass_fname); switch (pid=fork()) { case 0: execl(bin, bin, uname, userpass_fname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_check_pass_and_mount(const char *user, const char *userpass_fname) { int status; /* test if password is ok */ status = sec_check_pass(user, userpass_fname); if (status != 0) { error("check_pass for user '%s' failed: %d", user, status); return status; } /* try to mount key partition */ status = sec_mount(user, userpass_fname); if (status != 0) { error("try_mount for user '%s' failed: %d", user, status); return status; } return 0; } int sec_new_user(const char *uname, const char *userpass_fname, const char *serverpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-new-user"; int status; info("going to call %s with %s, %s, %s", bin, uname, userpass_fname, serverpass_fname); switch (pid=fork()) { case 0: execl(bin, bin, uname, userpass_fname, serverpass_fname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_rm_user(const char *uname) { pid_t pid; const char *bin = "/usr/bin/sec-rm-user"; int status; info("going to call %s with %s", bin, uname); switch (pid=fork()) { case 0: execl(bin, bin, uname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_change_pass(const char *uname, const char *userpass_fname, const char *serverpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-change-pass"; int status; info("going to call %s with %s, %s, %s", bin, uname, userpass_fname, serverpass_fname); switch (pid=fork()) { case 0: execl(bin, bin, uname, userpass_fname, serverpass_fname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_change_recovery(const char *uname, const char *userpass_fname, const char *serverpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-change-recovery"; int status; info("going to call %s with %s, %s, %s", bin, uname, userpass_fname, serverpass_fname); switch (pid=fork()) { case 0: execl(bin, bin, uname, userpass_fname, serverpass_fname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int sec_check_user(const char *uname) { pid_t pid; const char *bin = "/usr/bin/sec-check-user"; int status; info("going to call %s with %s", bin, uname); switch (pid=fork()) { case 0: execl(bin, bin, uname, (char*)NULL); error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } /** oldpass_fname can be NULL if root password is currently not set */ int sec_change_root_credentials(const char *newpass_fname, const char *oldpass_fname) { pid_t pid; const char *bin = "/usr/bin/sec-change-root-credentials"; int status; info("going to call %s", bin); switch (pid=fork()) { case 0: if ( oldpass_fname != NULL ) { execl( bin, bin, newpass_fname, oldpass_fname, NULL ); } else { execl( bin, bin, newpass_fname, NULL ); } error("execl failed for %s", bin); _exit(1); case -1: error("fork failed"); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); }
6,176
C
.c
208
24.100962
100
0.606901
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,245
xen_vkbd.c
OpenXT_input/xen_vkbd.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #include "keyboard.h" static struct event backend_xenstore_event; static void xen_vkbd_handle_led(struct input_event *event, struct domain *d) { if (event->type != EV_KEY || event->value == 0) return; int led_code = 0; switch (event->code) { case KEY_CAPSLOCK: led_code = LED_CODE_CAPSLOCK; break; case KEY_NUMLOCK: led_code = LED_CODE_NUMLOCK; break; case KEY_SCROLLLOCK: led_code = LED_CODE_SCROLLLOCK; break; } if (0 == led_code) return; if ((d->keyboard_led_code & led_code) == led_code) d->keyboard_led_code &= (~led_code); else d->keyboard_led_code |= led_code; input_led_code(d->keyboard_led_code, d->domid); } void xen_vkbd_send_event(struct domain *d, struct input_event *event) { xen_vkbd_handle_led(event, d); xen_event_send(d->vkbd_backend, event->type, event->code, event->value); } /* Backend device operations */ static xen_device_t xen_vkbd_alloc(xen_backend_t backend, int devid, void *priv) { struct xen_vkbd_backend *back = priv; struct xen_vkbd_device *dev; dev = malloc(sizeof (*dev)); memset(dev, 0, sizeof(*dev)); dev->devid = devid; dev->backend = backend; if (devid == 0) /* keyboard and relative mouse events device */ back->device = dev; else if (devid == 1) /* absolute mouse events device */ back->abs_device = dev; else warning("Unknown vkbd device id #%d\n", devid); return dev; } static int xen_vkbd_init(xen_device_t xendev) { struct xen_vkbd_device *dev = xendev; if (dev->devid == 1) backend_print(dev->backend, dev->devid, "feature-abs-pointer", "%d", 1); return 0; } static void xen_vkbd_evtchn_handler(int fb, short event, void *priv) { backend_evtchn_handler(priv); } static int xen_vkbd_connect(xen_device_t xendev) { struct xen_vkbd_device *dev = xendev; struct xenkbd_page *page; int fd; fd = backend_bind_evtchn(dev->backend, dev->devid); if (fd < 0) return -1; event_set(&dev->evtchn_event, fd, EV_READ | EV_PERSIST, xen_vkbd_evtchn_handler, backend_evtchn_priv(dev->backend, dev->devid)); event_add(&dev->evtchn_event, NULL); dev->page = backend_map_shared_page(dev->backend, dev->devid); if (!dev->page) return -1; return 0; } static void xen_vkbd_disconnect(xen_device_t xendev) { struct xen_vkbd_device *dev = xendev; event_del(&dev->evtchn_event); backend_unbind_evtchn(dev->backend, dev->devid); if (dev->page) { backend_unmap_shared_page(dev->backend, dev->devid, dev->page); dev->page = NULL; } } static void xen_vkbd_free(xen_device_t xendev) { struct xen_vkbd_device *dev = xendev; xen_vkbd_disconnect(dev); // FIXME : Tell xen_vkbd_backend we are gone ? free(dev); } static struct xen_backend_ops xen_vkbd_backend_ops = { xen_vkbd_alloc, xen_vkbd_init, xen_vkbd_connect, xen_vkbd_disconnect, NULL, NULL, NULL, xen_vkbd_free }; /* Backend creation function */ void xen_vkbd_backend_create(struct domain *d) { struct xen_vkbd_backend *backend; backend = malloc(sizeof (*backend)); backend->domid = d->domid; backend->backend = backend_register("vkbd", d->domid, &xen_vkbd_backend_ops, backend); if (!backend->backend) { error("%s: failed to register VKBD backend for dom%u!", __func__, d->domid); free(backend); return; } d->vkbd_backend = backend; } void xen_vkbd_backend_release(struct domain *d) { // Will trigger the disconnect callback on every device bound to this backend // and free(3) backend->backend. backend_release(d->vkbd_backend->backend); d->vkbd_backend = NULL; } /* Backend init functions */ static void xen_backend_handler(int fd, short event, void *priv) { backend_xenstore_handler(priv); } void xen_backend_init(int dom0) { int rc; rc = backend_init(dom0); if (rc) { warning("Failed to initialize libxenbackend"); return; } event_set(&backend_xenstore_event, backend_xenstore_fd(), EV_READ | EV_PERSIST, xen_backend_handler, NULL); event_add(&backend_xenstore_event, NULL); } void xen_backend_close(void) { /* FIXME: it's not complete */ event_del(&backend_xenstore_event); backend_close(); }
5,388
C
.c
186
24.086022
90
0.651398
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,246
server.c
OpenXT_input/server.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" extern void handle_switcher_abs(void *priv, struct msg_switcher_abs *msg, size_t msglen); extern void handle_switcher_leds(void *priv, struct msg_switcher_leds *msg, size_t msglen); extern void handle_switcher_shutdown(void *priv, struct msg_switcher_shutdown *msg, size_t msglen); void server_kill_domain(struct domain *d) { event_del(&(d->server_recv_event)); /* close(d->socket); */ domain_gone(d); } static struct dmbus_rpc_ops input_rpc_ops = { .switcher_abs = handle_switcher_abs, .switcher_leds = handle_switcher_leds, .switcher_shutdown = handle_switcher_shutdown }; static struct event rpc_connect_event; static void rpc_handler (int fd, short event, void *priv) { struct domain *d = priv; dmbus_handle_events(d->client); } static int rpc_connect (dmbus_client_t client, int domain, DeviceType type, int dm_domain, int fd, struct dmbus_rpc_ops **ops, void **priv) { struct domain *d; info("input_server: DM connected. domid %d device type %d\n", domain, type); switch (type) { case DEVICE_TYPE_INPUT: case DEVICE_TYPE_INPUT_PVM: d = domain_create(client, domain, type); if (!d) { info("input_server: Failed to create domain.\n"); return -1; } *ops = &input_rpc_ops; break; default: info("input_server: Bad device type %d\n", type); return -1; } event_set (&d->server_recv_event, fd, EV_READ | EV_PERSIST, rpc_handler, d); event_add (&d->server_recv_event, NULL); *priv = d; return 0; } static void rpc_disconnect (dmbus_client_t client, void *priv) { struct domain *d = priv; info("input_server: DM %d disconnected\n", d->domid); event_del (&d->server_recv_event); server_kill_domain (d); } static struct dmbus_service_ops service_ops = { .connect = rpc_connect, .disconnect = rpc_disconnect, }; int server_init (void) { int fd; info("input_server: dmbus_init\n"); fd = dmbus_init (DMBUS_SERVICE_INPUT, &service_ops); if (fd == -1) { info("input_server: dmbus_init failed\n"); error ("Failed to initialize dmbus"); return fd; } event_set (&rpc_connect_event, fd, EV_READ | EV_PERSIST, (void *) dmbus_handle_connect, NULL); event_add (&rpc_connect_event, NULL); return 0; }
3,178
C
.c
99
28.10101
99
0.682145
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,247
pm.c
OpenXT_input/pm.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" /* Input values defined here because RPC tool cannot generate enum values * from IDL yet. */ #define XCPMD_INPUT_SLEEP 1 #define XCPMD_INPUT_BRIGHTNESSUP 2 #define XCPMD_INPUT_BRIGHTNESSDOWN 3 static int increase_brightness_binding(void *opaque) { com_citrix_xenclient_xcpmd_indicate_input_(xcbus_conn, XCPMD_SERVICE, XCPMD_PATH, XCPMD_INPUT_BRIGHTNESSUP); return 0; } static int decrease_brightness_binding(void *opaque) { com_citrix_xenclient_xcpmd_indicate_input_(xcbus_conn, XCPMD_SERVICE, XCPMD_PATH, XCPMD_INPUT_BRIGHTNESSDOWN); return 0; } static int sleep_binding(void *opaque) { com_citrix_xenclient_xcpmd_indicate_input_(xcbus_conn, XCPMD_SERVICE, XCPMD_PATH, XCPMD_INPUT_SLEEP); return 0; } int host_pmop_in_progress(void) { char *pmact = NULL; int r = 0; pmact = xenstore_read( "/xenmgr/pm-current-action" ); r = pmact != NULL; free( pmact ); return r; } void pm_init(void) { int brightness_up[] = { KEY_BRIGHTNESSUP, -1 }; /* 225 */ int brightness_down[] = { KEY_BRIGHTNESSDOWN, -1 }; /* 224 */ int sleep[] = { KEY_SLEEP, -1 }; /* 142 */ /* install the input bindings */ input_add_binding(brightness_up, increase_brightness_binding, NULL,(void *) 0); input_add_binding(brightness_down, decrease_brightness_binding, NULL,(void *) 0); input_add_binding(sleep, sleep_binding, NULL,(void *) 0); info("pm: installed brightness and sleep binding handlers."); }
2,311
C
.c
59
36.305085
114
0.716451
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,248
switch.h
OpenXT_input/switch.h
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ enum switcher_state { SWITCHER_IDLE = 0, SWITCHER_OP_START = 1, SWITCHER_OP_COMPLETE = 2, SWITCHER_OP_ERROR = 3, }; #define MOUSE_SWITCH_PREV -2 #define KEYFOLLOWMOUSE 1 #define CLICKHOLDFOCUS 2 #define CLONEEVENTS 4 #define FOCUSMODE_MAX 7 struct timer_t; struct divert_info_t; struct domain { bool initialised; dmbus_client_t client; int domid; long slot; int keyboard_led_code; int is_pvm; int is_in_s3; int abs_enabled; enum switcher_state enter; enum switcher_state leave; enum switcher_state pre_enter; enum switcher_state post_leave; int prev_keyb_domid; struct domain *prev_keyb_domain_ptr; int disabled_surface; char *uuid; int sstate; struct { int left; int right; } mouse_switch; int vgpu_enabled; struct event server_recv_event; struct timeval last_input_event; struct timeval time_of_s3; int is_pv_domain; struct xen_vkbd_backend *vkbd_backend; struct divert_info_t *divert_info; int last_devslot; int has_secondary_gpu; struct sock_plugin* plugin; double rel_x_mult; double rel_y_mult; int desktop_xres; int desktop_yres; int num_active_adapters; }; struct callbacklist { void (*callback)(struct domain *d); struct callbacklist* next; }; static struct callbacklist* domainstart_callback = NULL; #define MAX_MODS 20 struct keypairs { uint32_t mod_bits; uint32_t keycode; }; struct divert_info_t { uint32_t modifers[MAX_MODS]; uint32_t mod_bits; struct keypairs* keylist; int num_keys; uint32_t focusmode; struct domain* key_domain; struct domain* mouse_domain; uint32_t sframe_x1; uint32_t sframe_x2; uint32_t sframe_y1; uint32_t sframe_y2; uint32_t dframe_x1; uint32_t dframe_x2; uint32_t dframe_y1; uint32_t dframe_y2; }; struct event_record { uint32_t magic; uint16_t itype; uint16_t icode; uint32_t ivalue; } __attribute__((__packed__)); #define buffersize (sizeof(struct event_record)*100) struct dev_event { uint8_t slot; bool remove; bool add; }; struct sock_plugin { char buffer[buffersize]; unsigned int bytes_remaining; int position; struct domain* src; struct domain* dest; int s; int slot; int recived_slot; int dropped; int slot_dropped; int delayed; char partialBuffer[sizeof(struct event_record)]; int resetall; int deq_size; struct dev_event* dev_events; uint32_t error; };
3,805
C
.c
134
25.149254
81
0.62051
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,249
touchpad.c
OpenXT_input/touchpad.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #define ABS_MT_PRESSURE 0x3a /* Pressure on contact area */ #define MOVE_MULT 0.02 #define SCROLL_MULT 0.04 #define PRESSURE_UP_MULT 0.12 #define PRESSURE_DOWN_MULT 0.098 #define NUM_MOVE_HISTORY_REC 4 #define AUTOSCROLL_TIMEOUT_USEC 200000 #define TAP_DRAG_TIMEOUT_USEC 180000 #define TIMEVAL_MAX_USEC 1000000 #define HIST(a) (ts->move_hist[((ts->move_hist_index - (a) + NUM_MOVE_HISTORY_REC) % NUM_MOVE_HISTORY_REC)]) static void wrapper_send_autoscroll_event(int fd, short event , void *opaque); static int gSlot = -2; enum tap_state { TS_START = 0, TS_TOUCH, TS_MOVE, TS_SINGLE_TAP_PENDING, TS_POSSIBLE_DRAG, TS_DRAG }; enum edge_type { NO_EDGE = 0, RIGHT_EDGE = 1, BOTTOM_EDGE = 2, TOP_EDGE = 4 }; enum scroll_type { SCROLL_UP = 0, SCROLL_DOWN }; struct touchpad_packet { int x; /* X position of finger. */ int y; /* X position of finger. */ int pressure; /* Finger pressure. */ int button_mask; /* Left or right button click. */ int btn_touch; /* Value for BTN_TOUCH reporting contact. */ struct timeval timestamp; int fingertouching; }; struct move_history_rec { int x; int y; struct timeval timestamp; }; struct scroll_data { int up; int down; int left; int right; }; struct touchpad_state { int last_x; /* Last valid value of x - used when packets without an x value are recd. */ int last_y; /* Last valid value of y - used when packets without an y value are recd. */ int last_fingertouching; enum tap_state tapstate; struct move_history_rec move_hist[NUM_MOVE_HISTORY_REC]; int move_hist_index; int packet_count_move; struct scroll_data scrolldata; int vert_scroll_on; int scroll_y; int scroll_packet_count; double autoscroll_yspd; double autoscroll_y; double frac_x; double frac_y; int touchpad_off; /* Is the touchpad enabled or disabled. */ }; struct touchpad_limits { int minx; /* Minimum valid value of x. */ int maxx; /* Maximum valid value of x. */ int miny; /* Minimum valid value of y. */ int maxy; /* Maximum valid value of y. */ int min_pressure; /* Minimum valid value of pressure. */ int max_pressure; /* Maximum valid value of pressure. */ int right_edge; /* Right edge begins here. */ int bottom_edge; /* Bottom edge begins here. */ int top_edge; /* Top edge begins here. */ int tap_move; /* Minimum distance to move, for a move event to be generated. */ int no_x; /* Used when no x value is received in packet. */ int no_y; /* Used when no y value is received in packet. */ int no_pressure; /* Used when no pressure value is received in packet. */ int scroll_dist_vert; /* Minimum vertical scroll distance. */ double speed; int is_clickpad; /* Maximum x value for left button clicks. */ int clickpad_left_button_maxx; /* True when the clickpad is pressed on the bottom edge. */ int is_clickpad_pressed; }; struct touchpad_config { int tap_to_click_enabled; int scrolling_enabled; int speed; }; static const int left_button_down = 0x01; static const int left_button_up = 0x02; static const int right_button_down = 0x04; static const int right_button_up = 0x08; static const int left_button_id = 1; static struct touchpad_packet tpacket; static struct touchpad_state tstate; static struct touchpad_limits tlimits; static struct touchpad_config tconfig; static const int default_diag = 5024; static struct event autoscroll_event; static enum scroll_type current_scroll_type; static int set_timer_only = 1; static int is_autoscroll_timer_set = 0; static struct event left_click_event; /* get configured setting - true/false */ int touchpad_get_tap_to_click_enabled(void) { char buf[16]; db_read(buf, sizeof(buf), "/touchpad/tap-to-click-enable"); return strcmp("true", buf) == 0; } /* get configured setting - true/false */ int touchpad_get_scrolling_enabled(void) { char buf[16]; db_read(buf, sizeof(buf), "/touchpad/scrolling-enable"); return strcmp("true", buf) == 0; } /* get configured setting - int value */ int touchpad_get_speed(void) { char buf[16]; db_read(buf, sizeof(buf), "/touchpad/speed"); return strtol(buf, NULL, 10); } void touchpad_set_scrolling_enabled(int enabled) { db_write("/touchpad/scrolling-enable", enabled ? "true" : "false"); touchpad_reread_config(); } void touchpad_set_tap_to_click_enabled(int enabled) { db_write("/touchpad/tap-to-click-enable", enabled ? "true" : "false"); touchpad_reread_config(); } void touchpad_set_speed(int speed) { char buf[16]; sprintf(buf, "%d", speed); db_write("/touchpad/speed", buf); touchpad_reread_config(); } static void reset_touchpad_packet(struct touchpad_packet *tp, struct touchpad_limits *tl) { tp->x = tl->no_x; tp->y = tl->no_y; tp->pressure = tl->no_pressure; tp->button_mask = 0; tp->timestamp.tv_sec = 0; tp->timestamp.tv_usec = 0; tp->fingertouching = 0; } static enum edge_type detect_edge(int x, int y, int right_edge, int bottom_edge, int top_edge) { enum edge_type etype = NO_EDGE; if (x > right_edge) etype |= RIGHT_EDGE; if (y > bottom_edge) { etype |= BOTTOM_EDGE; } else if (y < top_edge) { etype |= TOP_EDGE; } return etype; } static int detect_finger(const struct touchpad_packet *tp, const struct touchpad_limits *tl) { static int fingertouching = 0; int range = tl->max_pressure - tl->min_pressure; if (!range) { fingertouching = tp->btn_touch; return fingertouching; } if (tp->pressure == tl->no_pressure) return fingertouching; if (!fingertouching) { if (tp->pressure > (tl->min_pressure + (range * PRESSURE_UP_MULT))) fingertouching = 1; } else { if (tp->pressure < (tl->min_pressure + (range * PRESSURE_DOWN_MULT))) fingertouching = 0; } return fingertouching; } static void populate_input_event(struct input_event *ev, int type, int code, int value) { struct timeval now; gettimeofday(&now,NULL); ev->time = now; ev->type = type; ev->code = code; ev->value = value; } static void event_sync(void) { struct input_event sync_ev; populate_input_event(&sync_ev, EV_SYN, SYN_REPORT, 0); check_and_inject_event(&sync_ev, gSlot, HID_TYPE_TOUCHPAD); } static void event_button_change(int button_id, int value) { struct input_event ev; if ((button_id < left_button_id) || (button_id > (BTN_TASK - BTN_LEFT))) return; populate_input_event(&ev, EV_KEY, button_id + BTN_LEFT - 1, value); check_and_inject_event(&ev, gSlot, HID_TYPE_TOUCHPAD); /* Generate a sync event. */ event_sync(); } static void event_relative_move(int dist_x, int dist_y) { struct input_event ev[2]; if (dist_x != 0) { populate_input_event(&(ev[0]), EV_REL, REL_X, dist_x); check_and_inject_event(&(ev[0]), gSlot, HID_TYPE_TOUCHPAD); } if (dist_y != 0) { populate_input_event(&(ev[1]), EV_REL, REL_Y, dist_y); check_and_inject_event(&(ev[1]), gSlot, HID_TYPE_TOUCHPAD); } /* Generate a sync event. */ if ((dist_x != 0) || (dist_y != 0)) event_sync(); } static void event_scroll(enum scroll_type scroll) { struct input_event ev; int event_code = -1; int value = 0; switch (scroll) { case SCROLL_UP: event_code = REL_WHEEL; value = 1; break; case SCROLL_DOWN: event_code = REL_WHEEL; value = -1; break; default: break; } populate_input_event(&ev, EV_REL, event_code, value); check_and_inject_event(&ev, gSlot, HID_TYPE_TOUCHPAD); /* Generate a sync event. */ event_sync(); } /* Note: the maximum value of timeout_usec that this function can handle is 999,999, which is the maximum value of tv_usec in struct timeval. */ static void add_timeout_usec(struct timeval *tv, uint32_t timeout_usec) { uint32_t diff; diff = TIMEVAL_MAX_USEC - tv->tv_usec; if (diff <= timeout_usec) { tv->tv_usec = timeout_usec - diff; tv->tv_sec += 1; } else { tv->tv_usec += timeout_usec; } } static void delete_left_click_timer(void) { if (event_initialized(&left_click_event)) { evtimer_del(&left_click_event); } } static void send_left_click_event(void *opaque) { struct touchpad_state *ts = (struct touchpad_state *) opaque; const int button_down = 1; const int button_up = 0; if (ts->tapstate == TS_SINGLE_TAP_PENDING) { event_button_change(left_button_id, button_down); event_button_change(left_button_id, button_up); ts->tapstate = TS_START; } delete_left_click_timer(); } static void wrapper_send_left_click_event(int fd, short event, void *opaque) { send_left_click_event(opaque); } static void set_left_click_timer(struct touchpad_state *ts, uint32_t timeout_usec) { struct timeval tv = {0, 0}; if (!event_initialized(&left_click_event)) { evtimer_set(&left_click_event, wrapper_send_left_click_event, ts); } add_timeout_usec(&tv, timeout_usec); evtimer_add(&left_click_event, &tv); } static void handle_gestures(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl, struct touchpad_config *tc) { static int touch_on_x = 0; static int touch_on_y = 0; static enum edge_type touch_on_edge = NO_EDGE; int button = left_button_id; int touch = 0; int release = 0; int move = 0; int dx = 0; int dy = 0; const int button_down = 1; const int button_up = 0; touch = (tp->fingertouching) && !(ts->last_fingertouching); release = !(tp->fingertouching) && (ts->last_fingertouching); if (tp->fingertouching) { if (touch) move = 0; else if ( ((tp->x != tl->no_x) && (abs(tp->x - touch_on_x) >= tl->tap_move)) || ((tp->y != tl->no_y) && (abs(tp->y - touch_on_y) >= tl->tap_move)) ) move = 1; } if (touch) { if (tp->x != tl->no_x) touch_on_x = tp->x; else touch_on_x = ts->last_x; if (tp->y != tl->no_y) touch_on_y = tp->y; else touch_on_y = ts->last_y; touch_on_edge = detect_edge(touch_on_x, touch_on_y, tl->right_edge, tl->bottom_edge, tl->top_edge); } switch (ts->tapstate) { case TS_START: if (touch) ts->tapstate = TS_TOUCH; ts->frac_x = 0; ts->frac_y = 0; break; case TS_TOUCH: if (move) { ts->tapstate = TS_MOVE; } else if(release) { ts->tapstate = TS_START; /* Generate left button click if configured. For clickpads, do not generate tap clicks on the bottom edge, otherwise a press-and-release button click results in a double-click. */ if ( tc->tap_to_click_enabled && (!(tl->is_clickpad && (touch_on_edge & BOTTOM_EDGE))) ) { /* Do not generate the left click immediately, otherwise a double tap and drag gesture results in a double click. The windows and ubuntu drivers seem to check the time diff between 2 left button down events, rather than 2 left button up events, for a double click. So in case of double tap and drag, we will not send the first tap. */ set_left_click_timer(ts, TAP_DRAG_TIMEOUT_USEC); ts->tapstate = TS_SINGLE_TAP_PENDING; } } break; case TS_MOVE: if (release) { ts->tapstate = TS_START; } break; case TS_SINGLE_TAP_PENDING: if (touch) { delete_left_click_timer(); if ( tc->tap_to_click_enabled && (!(tl->is_clickpad && (touch_on_edge & BOTTOM_EDGE))) ) { ts->tapstate = TS_POSSIBLE_DRAG; } else { /* Send the left click that was pending. */ event_button_change(button, button_down); event_button_change(button, button_up); ts->tapstate = TS_TOUCH; } } ts->frac_x = 0; ts->frac_y = 0; break; case TS_POSSIBLE_DRAG: if (move) { /* Generate a left button down event. Tap clicks will be enabled if we are here. */ event_button_change(button, button_down); ts->tapstate = TS_DRAG; } else if(release) { ts->tapstate = TS_START; /* It is not a drag, just a double tap. Generate two left clicks. Tap clicks will be enabled if we are here. */ event_button_change(button, button_down); event_button_change(button, button_up); event_button_change(button, button_down); event_button_change(button, button_up); } break; case TS_DRAG: if (release) { ts->tapstate = TS_START; /* Generate a left button up event. Tap clicks will be enabled if we are here. */ event_button_change(button, button_up); } break; default: break; } } static void handle_button_clicks(struct touchpad_packet *tp) { int button_id; int mask; const int button_down = 1; const int button_up = 0; const int num_buttons = BTN_TASK - BTN_LEFT; /* Generate button click events, if any. */ for (button_id = 1, mask = 1; button_id <= num_buttons; mask = mask << 1, button_id++) { if (tp->button_mask & mask) { event_button_change(button_id, button_down); } mask = mask << 1; if (tp->button_mask & mask) { event_button_change(button_id, button_up); } } } static void store_history(struct touchpad_state *ts, int x, int y, struct timeval timestamp) { int idx = (ts->move_hist_index + 1) % NUM_MOVE_HISTORY_REC; ts->move_hist[idx].x = x; ts->move_hist[idx].y = y; ts->move_hist[idx].timestamp = timestamp; ts->move_hist_index = idx; } static double estimate_delta(double x0, double x1, double x2, double x3) { return x0 * 0.3 + x1 * 0.1 - x2 * 0.1 - x3 * 0.3; } static double estimate_delta_previous(double x0, double x1) { return ((x0 - x1) * 0.4); } static void compute_deltas(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl, int *delta_x, int *delta_y) { const int min_packet_count_move = 3; int x_value = tp->x; int y_value = tp->y; double dx = 0; double dy = 0; double integral = 0; if (x_value == tl->no_x) { x_value = ts->last_x; } if (y_value == tl->no_y) { y_value = ts->last_y; } if ((ts->tapstate == TS_MOVE || ts->tapstate == TS_DRAG) && !(ts->vert_scroll_on)) { ts->packet_count_move++; if (ts->packet_count_move > min_packet_count_move) { dx = estimate_delta(x_value, HIST(0).x, HIST(1).x, HIST(2).x); dy = estimate_delta(y_value, HIST(0).y, HIST(1).y, HIST(2).y); } else if (ts->packet_count_move > 1) { dx = estimate_delta_previous(x_value, HIST(0).x); dy = estimate_delta_previous(y_value, HIST(0).y); } /* Adjust deltas according to speed. */ dx = (dx * (tl->speed)) + (ts->frac_x); ts->frac_x = modf(dx, &integral); dx = integral; dy = (dy * (tl->speed)) + (ts->frac_y); ts->frac_y = modf(dy, &integral); dy = integral; } else { ts->packet_count_move = 0; } *delta_x = (int) dx; *delta_y = (int) dy; store_history(ts, x_value, y_value, tp->timestamp); } static void send_autoscroll_event(void *unused) { struct timeval tv = {0, 0}; /* Send scroll event. */ if (!set_timer_only) { event_scroll(current_scroll_type); } if (!event_initialized(&autoscroll_event)) { evtimer_set(&autoscroll_event, wrapper_send_autoscroll_event, NULL); } add_timeout_usec(&tv, AUTOSCROLL_TIMEOUT_USEC); evtimer_add(&autoscroll_event, &tv); is_autoscroll_timer_set = 1; } static void wrapper_send_autoscroll_event(int fd, short event , void *opaque) { send_autoscroll_event(opaque); } static void reset_autoscroll_timer(void) { struct timeval tv = {0, 0}; if (is_autoscroll_timer_set) { add_timeout_usec(&tv, AUTOSCROLL_TIMEOUT_USEC); evtimer_add(&autoscroll_event, &tv); } } static void free_autoscroll_timer(void) { if (is_autoscroll_timer_set) { evtimer_del(&autoscroll_event); is_autoscroll_timer_set = 0; } } static void reset_scroll_data(struct scroll_data *sd) { sd->up = 0; sd->down = 0; sd->left = 0; sd->right = 0; } static void start_corner_scrolling(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl) { struct timeval diff; double elapsed_secs; double dy; int y_value = tp->y; double delta = tl->scroll_dist_vert; ts->autoscroll_y = 0; /* Turn on autoscroll only when we reach a corner while scrolling, not when we start scrolling from a corner. */ if (ts->scroll_packet_count > 3) { if (tp->y == tl->no_y) y_value = ts->last_y; timersub(&(HIST(0).timestamp), &(HIST(3).timestamp), &diff); elapsed_secs = (diff.tv_sec) + (diff.tv_usec / 1000000.0); dy = (HIST(0).y) - (HIST(3).y); if ((elapsed_secs > 0) && (delta > 0)) { ts->autoscroll_yspd = (dy / elapsed_secs) / delta; ts->autoscroll_y = (y_value - ts->scroll_y) / delta; } /* Alps touchpads stop sending events soon after the finger stops moving, even if it is still pressed. To handle this, we will generate scroll events with the help of a timer. */ set_timer_only = 1; send_autoscroll_event(NULL); set_timer_only = 0; if (y_value < ts->scroll_y) current_scroll_type = SCROLL_UP; else current_scroll_type = SCROLL_DOWN; } ts->scroll_packet_count = 0; } static void stop_corner_scrolling(struct touchpad_state *ts) { ts->autoscroll_yspd = 0; ts->scroll_packet_count = 0; } static void handle_scrolling(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl, struct touchpad_config *tc, enum edge_type edge) { int x_value = tp->x; int y_value = tp->y; int delta; int is_corner = 0; double dsecs; struct timeval diff; const double timeout_secs = 0.2; struct scroll_data *sd = &(ts->scrolldata); if (!(tc->scrolling_enabled)) return; if (tp->x == tl->no_x) x_value = ts->last_x; if (tp->y == tl->no_y) y_value = ts->last_y; reset_scroll_data(sd); /* Reset the autoscroll timer whenever a packet is received. */ reset_autoscroll_timer(); if ((tp->fingertouching) && !(ts->last_fingertouching)) { stop_corner_scrolling(ts); if (edge & RIGHT_EDGE) { ts->vert_scroll_on = 1; ts->scroll_y = y_value; } } if (ts->vert_scroll_on && (!(edge & RIGHT_EDGE) || !(tp->fingertouching))) ts->vert_scroll_on = 0; /* If we were corner scrolling, but no longer in a corner, or raised finger then stop corner scrolling. */ is_corner = ((edge & RIGHT_EDGE) && (edge & (TOP_EDGE | BOTTOM_EDGE))); if ((ts->autoscroll_yspd) && (!(tp->fingertouching) || !(is_corner))) { stop_corner_scrolling(ts); } /* If we are no longer in a corner, or raised finger then free the autoscroll timer. Note that yspd may have been zero when we were corner scrolling. */ if (!(tp->fingertouching) || !(is_corner)) { free_autoscroll_timer(); } /* If hitting a corner (top or bottom) while vertical scrolling is on, start corner scrolling. */ if ((ts->vert_scroll_on) && is_corner && (ts->autoscroll_yspd == 0)) { start_corner_scrolling(ts, tp, tl); } if (ts->vert_scroll_on) { (ts->scroll_packet_count)++; } if (ts->vert_scroll_on) { delta = tl->scroll_dist_vert; if (delta > 0) { while ((y_value - ts->scroll_y) > delta) { (sd->down)++; ts->scroll_y += delta; } while ((y_value - ts->scroll_y) < -delta) { (sd->up)++; ts->scroll_y -= delta; } } } if (ts->autoscroll_yspd) { timersub(&(tp->timestamp), &(HIST(0).timestamp), &diff); dsecs = (diff.tv_sec) + (diff.tv_usec / 1000000.0); /* If dsecs is not less than timeout_secs, an autoscroll event will already have been generated by the timer, so do not generate it again. */ if (dsecs < timeout_secs) { ts->autoscroll_y += (ts->autoscroll_yspd * dsecs); while (ts->autoscroll_y > 1.0) { sd->down++; ts->autoscroll_y -= 1.0; } while (ts->autoscroll_y < -1.0) { sd->up++; ts->autoscroll_y += 1.0; } } } /* Generate scroll events. */ while ((sd->up)-- > 0) { event_scroll(SCROLL_UP); } while ((sd->down)-- > 0) { event_scroll(SCROLL_DOWN); } } static void save_previous_packet_values(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl) { ts->last_fingertouching = tp->fingertouching; if (tp->x != tl->no_x) { ts->last_x = tp->x; } if (tp->y != tl->no_y) { ts->last_y = tp->y; } } static void handle_clickpad(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl, enum edge_type edge) { static int button_down_x = -1; if (edge & BOTTOM_EDGE) { /* clickpad reports only left button, and we need to fake the right button depending on the touch position. */ if (tp->button_mask & left_button_down) { tl->is_clickpad_pressed = 1; if (tp->x != tl->no_x) button_down_x = tp->x; else button_down_x = ts->last_x; if (button_down_x > tl->clickpad_left_button_maxx) tp->button_mask = (tp->button_mask & (!left_button_down)) | right_button_down; } else if (tp->button_mask & left_button_up) { tl->is_clickpad_pressed = 0; if (button_down_x > tl->clickpad_left_button_maxx) tp->button_mask = (tp->button_mask & (!left_button_up)) | right_button_up; button_down_x = -1; } handle_button_clicks(tp); } } /* QUIRK: * Some touchpads report values outside of the boundaries they pretend to * honor. This would be handled with a quirk (e.g. hwdb + libevdev), but in * this case, it would require a lot of refactoring to support something even * similar. * Instead, adjust limits if a value overflows by less than ~10% of the axis * range. Anything above is considered spurious input (which happens with some * multitouch input). */ static void adjust_overflow(struct touchpad_packet *tp, struct touchpad_limits *tl) { int xrange = tl->maxx - tl->minx; int yrange = tl->maxy - tl->miny; if ((tp->x > tl->maxx) && ((tp->x - (xrange / 10)) <= tl->maxx)) { /* Preserve the reported zone size for lack of a better idea. */ tl->right_edge = tp->x - (xrange - tl->right_edge); tl->maxx = tp->x; } if ((tp->y > tl->maxy) && ((tp->y - (yrange / 10)) <= tl->maxy)) { tl->bottom_edge = tp->y - (yrange - tl->bottom_edge); tl->maxy = tp->y; } } static void process_packet(struct touchpad_state *ts, struct touchpad_packet *tp, struct touchpad_limits *tl, struct touchpad_config *tc) { int x_value = tp->x; int y_value = tp->y; int dx; int dy; enum edge_type edge; if (tl->is_clickpad == 0) handle_button_clicks(tp); /* If the touchpad has been disabled, only generate button clicks. Do not handle moves, scrolling etc. */ if (ts->touchpad_off == 1) return; if (tp->x == tl->no_x) x_value = ts->last_x; if (tp->y == tl->no_y) y_value = ts->last_y; adjust_overflow(tp, tl); edge = detect_edge(x_value, y_value, tl->right_edge, tl->bottom_edge, tl->top_edge); tp->fingertouching = detect_finger(tp, tl); if (tl->is_clickpad) handle_clickpad(ts, tp, tl, edge); handle_gestures(ts, tp, tl, tc); handle_scrolling(ts, tp, tl, tc, edge); compute_deltas(ts, tp, tl, &dx, &dy); /* Generate move events. */ if (dx || dy) { /* Do not generate move events if the clickpad is pressed on the bottom edge. */ if (!(tl->is_clickpad_pressed && (edge & BOTTOM_EDGE))) { event_relative_move(dx, dy); } } /* Save the values of some state variables. */ save_previous_packet_values(ts, tp, tl); } void handle_touchpad_event(struct input_event *ev,int slot) { static int sync_recd = 1; gSlot=slot; if (sync_recd == 1) { reset_touchpad_packet(&tpacket, &tlimits); sync_recd = 0; } if ((ev->type == EV_SYN) && (ev->code == SYN_REPORT)) { /* Packet is complete, now process it. */ tpacket.timestamp = ev->time; sync_recd = 1; process_packet(&tstate, &tpacket, &tlimits, &tconfig); } else if (ev->type == EV_ABS) { if ((ev->code == ABS_X) || (ev->code == ABS_MT_POSITION_X)) tpacket.x = ev->value; else if ((ev->code == ABS_Y) || (ev->code == ABS_MT_POSITION_Y)) tpacket.y = ev->value; else if ((ev->code == ABS_PRESSURE) || (ev->code ==ABS_MT_PRESSURE)) tpacket.pressure = ev->value; } else if (ev->type == EV_KEY) { if ((ev->code >=BTN_LEFT) && (ev->code <=BTN_TASK)) { int bitpair = (ev->code - BTN_LEFT) << 1; tpacket.button_mask |= 1 << ( bitpair + (ev->value?0:1)); } if (ev->code == BTN_TOUCH) tpacket.btn_touch = ev->value; } } static void init_touchpad_state(struct touchpad_state *ts) { ts->last_x = 0; ts->last_y = 0; ts->last_fingertouching = 0; ts->tapstate = TS_START; ts->move_hist_index = -1; ts->packet_count_move = 0; ts->vert_scroll_on = 0; ts->scroll_y = 0; ts->scroll_packet_count = 0; ts->autoscroll_yspd = 0; ts->autoscroll_y = 0; ts->frac_x = 0; ts->frac_y = 0; ts->touchpad_off = 0; reset_scroll_data(&(ts->scrolldata)); } static void disable_touchpad(void) { tstate.touchpad_off = 1; } static void enable_touchpad(void) { init_touchpad_state(&tstate); } static int disable_touchpad_cb(void *opaque) { disable_touchpad(); return 0; } static int enable_touchpad_cb(void *opaque) { enable_touchpad(); return 0; } void toggle_touchpad_status(void) { if (tstate.touchpad_off == 1) enable_touchpad(); else disable_touchpad(); } /* For the HP8440p, keyboard events are generated when the touchpad on/off * button is pressed, so handle those. */ static void add_touchpad_bindings(void) { { int touchpad_off[] = { KEY_PROG2, -1 }; input_add_binding (touchpad_off, disable_touchpad_cb, NULL, (void *) 0); } { int touchpad_on[] = { KEY_HELP, -1 }; input_add_binding (touchpad_on, enable_touchpad_cb, NULL, (void *) 0); } } static void compute_touchpad_speed(struct touchpad_config *tc, struct touchpad_limits *tl) { const double default_speed = 0.15; const double min_speed = 0.1; const double max_speed = 0.9; const int default_config_speed = 5; const int min_config_speed = 1; const int max_config_speed = 10; double units; int width; int height; int diag; width = abs(tl->maxx - tl->minx); height = abs(tl->maxy - tl->miny); diag = sqrt(width * width + height * height); tl->speed = default_speed; if ((diag != default_diag) && (diag > 0)) { tl->speed = (default_speed * default_diag) / (double)diag; if (tl->speed > max_speed) tl->speed = max_speed; if (tl->speed < min_speed) tl->speed = min_speed; } /* Adjust the speed according to the configuration. */ if ((tc->speed < min_config_speed) || (tc->speed > max_config_speed)) { info("touchpad speed out of range, setting it to %d", default_config_speed); tc->speed = default_config_speed; } if (tc->speed == default_config_speed) return; units = ((tl->speed) / (double)default_config_speed); if (tc->speed < default_config_speed) { tl->speed = tl->speed - (units * (default_config_speed - tc->speed)) ; } else { tl->speed = tl->speed + (units * (tc->speed - default_config_speed)) ; } } int init_touchpad(int fd) { const double default_edge_mult = 0.17; const double edge_mult_low_res = 0.20; const double clickpad_bottom_edge_mult = 0.20; const double clickpad_left_button_maxx_mult = 0.50; struct input_absinfo absinfo; int ret = 0; int width; int height; int diag; double edge_width; double edge_mult = default_edge_mult; unsigned long keybits[NBITS(KEY_MAX)]; struct stat stat_buf; const char *disable_touchpad_file = "/config/disable-touchpad"; /* Check if the touchpad needs to be disabled. */ if (stat(disable_touchpad_file, &stat_buf) == 0) { info("Disabling touchpad due to presence of file %s", disable_touchpad_file); return -1; } memset(keybits, 0, sizeof(keybits)); if ((ret = ioctl(fd, EVIOCGABS(ABS_X), &absinfo)) < 0) return ret; tlimits.minx = absinfo.minimum; tlimits.maxx = absinfo.maximum; if ((ret = ioctl(fd, EVIOCGABS(ABS_Y), &absinfo)) < 0) return ret; tlimits.miny = absinfo.minimum; tlimits.maxy = absinfo.maximum; if ((ret = ioctl(fd, EVIOCGABS(ABS_PRESSURE), &absinfo)) < 0) return ret; tlimits.min_pressure = absinfo.minimum; tlimits.max_pressure = absinfo.maximum; if ((ret = ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits)) < 0) return ret; /* Clickpads only report left button. */ if (TEST_BIT(BTN_LEFT, keybits) && !TEST_BIT(BTN_RIGHT, keybits) && !TEST_BIT(BTN_MIDDLE, keybits)) { tlimits.is_clickpad = 1; } else { tlimits.is_clickpad = 0; } tlimits.is_clickpad_pressed = 0; /* Calculate minimum distance for a move event to be generated. */ width = abs(tlimits.maxx - tlimits.minx); height = abs(tlimits.maxy - tlimits.miny); diag = sqrt(width * width + height * height); tlimits.tap_move = diag * MOVE_MULT; /* Calculate edge widths. */ if (diag < default_diag) { edge_mult = edge_mult_low_res; } edge_width = width * edge_mult; tlimits.right_edge = tlimits.maxx - edge_width; edge_width = height * edge_mult; tlimits.bottom_edge = tlimits.maxy - edge_width; tlimits.top_edge = tlimits.miny + edge_width; if (tlimits.is_clickpad) { edge_width = height * clickpad_bottom_edge_mult; tlimits.bottom_edge = tlimits.maxy - edge_width; edge_width = width * clickpad_left_button_maxx_mult; tlimits.clickpad_left_button_maxx = tlimits.minx + edge_width; } else { tlimits.clickpad_left_button_maxx = tlimits.minx - 1; } /* Calculate the minimum horizontal and vertical scroll distance. */ tlimits.scroll_dist_vert = diag * SCROLL_MULT; /* If the event has no x, y or pressure values, use these instead. */ tlimits.no_x = tlimits.minx - 1; tlimits.no_y = tlimits.miny - 1; tlimits.no_pressure = tlimits.min_pressure - 1; /* Initialise the touchpad state. */ init_touchpad_state(&tstate); /* Get the touchpad configuration. */ touchpad_reread_config(); add_touchpad_bindings(); if (tlimits.is_clickpad) { info("device on fd %d is a clickpad", fd); } return 0; } void touchpad_reread_config(void) { tconfig.tap_to_click_enabled = touchpad_get_tap_to_click_enabled(); tconfig.scrolling_enabled = touchpad_get_scrolling_enabled(); tconfig.speed = touchpad_get_speed(); compute_touchpad_speed(&tconfig, &tlimits); }
35,613
C
.c
1,091
25.512374
108
0.576769
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,252
user.c
OpenXT_input/user.c
/* * Copyright (c) 2010 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #include "user.h" int user_create( const char *hash, const char *name, const char *password_file, const char *recovery_file ) { int error = sec_new_user( hash, password_file, recovery_file ); if (error) { return error; } return user_assoc( hash, name ); } int user_assoc( const char *hash, const char *name ) { char path[256] = "/platform/username-map/"; strncat( path, hash, sizeof(path)-strlen(path) ); db_write( path, name ); return 0; } int user_get_name( const char *hash, char *name ) { char path[256] = "/platform/username-map/"; strncat( path, hash, sizeof(path)-strlen(path) ); if (!db_read( name, NAME_LEN, path)) { return -1; } return 0; }
1,541
C
.c
43
32.72093
107
0.702142
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,254
util.c
OpenXT_input/util.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" void helper_exec(const char *bin, int domid) { char buff[12]={0}; struct stat s; pid_t pid; if (stat(bin, &s) == -1) return; snprintf(buff,sizeof(buff)-1,"%d",domid); switch ((pid=fork())) { //wait is mopped up by sigchld in main case 0: execl(bin,bin,buff,(char *) 0); error("execl failed for %s",bin); _exit(1); break; case -1: error("fork failed"); break; } waitpid(pid,NULL,0); } static void bt (void) { #if 0 #if 0 unsigned int level = 0; void *addr; Dl_info info; for (;;) { addr = __builtin_return_address (level); if (!addr) return; fprintf (stderr, "%d: %p", level, addr); if (dladdr (addr, &info)) { char *base, *offset; base = info.dli_saddr; offset = addr; fprintf (stderr, "(%s %s+0x%x)", info.dli_fname, info.dli_sname, (unsigned int) (offset - base)); } fprintf (stderr, "\n"); level++; } #else void *ba[256]; Dl_info info; int i; int n = backtrace (ba, sizeof (ba) / sizeof (ba[0])); if (!n) return; for (i = 0; i < n; ++i) { fprintf (stderr, "%d: %p", i, ba[i]); if (dladdr (ba[i], &info)) { char *base, *offset; base = info.dli_saddr; offset = ba[i]; fprintf (stderr, "(%s %s+0x%x)", info.dli_fname, info.dli_sname, (unsigned int) (offset - base)); } fprintf (stderr, "\n"); } #endif #endif } void message (int flags, const char *file, const char *function, int line, const char *fmt, ...) { char buf[1024]={0}; const char *level = "Info"; va_list ap; int len; if (flags & MESSAGE_WARNING) { level = "Warning"; } else if (flags & MESSAGE_ERROR) { level = "Error"; } else if (flags & MESSAGE_FATAL) { level = "Fatal"; } va_start (ap, fmt); len=vsnprintf(buf,sizeof(buf)-1,fmt,ap); va_end (ap); if ((len>0) &&(buf[len-1]=='\n')) buf[len-1]=0; syslog(LOG_ERR, "%s:%s:%s:%d:%s", level, file, function, line,buf); if (flags & MESSAGE_FATAL) { bt (); abort (); } } void log_dbus_error (const char *file, const char *function, int line, const char *err, const char *fmt, ...) { char buf[128]={0}; va_list ap; int len; va_start (ap, fmt); len=vsnprintf(buf,sizeof(buf)-1,fmt,ap); va_end (ap); if ((len>0) &&(buf[len-1]=='\n')) buf[len-1]=0; syslog(LOG_ERR, "Info:%s:%s:%d threw error %s : %s", file, function, line,err,buf); }
3,632
C
.c
128
22.117188
109
0.556677
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,255
socket.c
OpenXT_input/socket.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" #define MAGIC 0xAD9CBCE9 #define EVENT_SIZE sizeof(struct event_record) #define EV_VM 0x7 #define VM_SEND_TO 0x1 #define VM_TAKE_FROM 0x2 #define VM_ERROR 0x3 struct sock_plugin buffers; static struct event server_accept_event; static long server_sock_fd; static void process_event(struct event_record* r, struct sock_plugin* b); void send_event(struct sock_plugin* plug, int t, int c, int v); void kill_connection(struct sock_plugin* buf); int send_to_plugin(struct sock_plugin* plug,struct event_record* e); struct event_record* findnext(struct sock_plugin* b) { struct event_record* r = NULL; int start=b->position; // Skip junk while (b->bytes_remaining >= EVENT_SIZE && (r = (struct event_record*) &b->buffer[b->position]) && r->magic != MAGIC) { b->bytes_remaining--; b->position++; } if (start!=b->position) info("Warning: Encountered %d bytes of junk.\n", b->position - start); if (b->bytes_remaining >= EVENT_SIZE) { b->bytes_remaining-= EVENT_SIZE; b->position+=EVENT_SIZE; return r; } else return NULL; } struct event server_recv_event; static void wrapper_server_recv(int fd, short event, void *opaque) { int n; struct sock_plugin* buf = (struct sock_plugin*) opaque; char *b = buf->buffer; memmove(b, &b[buf->position] , buf->bytes_remaining); buf->position=0; do { n=recv(fd, &b[buf->bytes_remaining], buffersize- buf->bytes_remaining,0); } while ((n<0) && (errno==EINTR)); if (n>0) { struct event_record* r = NULL; buf->bytes_remaining+=n; while ((r=findnext(buf))!=NULL) { process_event(r,buf); } } else if (n) { info("Recv failed with %s",strerror(errno)); kill_connection(buf); } else { kill_connection(buf); info("Client disconnected"); } } void kill_connection(struct sock_plugin* buf) { event_del(&server_recv_event); close(buf->s); if (buf->src) { buf->src->plugin=NULL; buf->src=NULL; } buf->s=-1; free(buf->dev_events); } #define E_BADDOMAIN 0x1 #define E_BADCODE 0x2 #define NONE -1 static void send_error(struct sock_plugin* plug, uint8_t code, uint8_t type, uint8_t domain) { struct event_record e; e.magic= MAGIC; e.itype=EV_VM; e.icode=VM_ERROR; e.ivalue= code << (3*8) | type << (2*8) | domain << (1*8); if (!send_to_plugin(plug ,&e)) { if (!plug->error) plug->error=e.ivalue; } } static void send_slot(struct sock_plugin* plug, int slot) { struct event_record er; er.magic= MAGIC; if (plug->dropped) { er.itype=EV_SYN; er.icode=SYN_DROPPED; er.ivalue=0; plug->dropped = ! send_to_plugin(plug, &er); if (plug->dropped) { plug->slot_dropped=true; return; } } er.magic= MAGIC; er.itype=EV_DEV; er.icode=DEV_SET; er.ivalue=slot; if (send_to_plugin(plug, &er)) { plug->slot=slot; /* If we prevously droppend the slot number, then we know we also dropped the first packet from that slot, hence we should set dropped. If not, then we've already dealt with dropped, so it should be false. */ plug->dropped = plug->slot_dropped; plug->slot_dropped=false; } else plug->slot_dropped=true; } // called from input.c, when devices are added or removed. void add_queue_dev_event_conf(struct sock_plugin* plug, int slot) { struct dev_event* dev_events = plug->dev_events; int i; int size = plug->deq_size; for (i=0; i<size; i++) if (dev_events[i].slot==slot) { dev_events[i].add=true; return; } dev_events = realloc(dev_events, (size+1)*sizeof(struct dev_event)); dev_events[size].slot=slot; dev_events[size].remove=0; dev_events[size].add=1; plug->deq_size=size+1; plug->dev_events=dev_events; } static void add_queue_dev_event_reset(struct sock_plugin* plug, int slot) { int size = plug->deq_size; int i; struct dev_event* dv; if (slot==0xFF) { plug->resetall=true; return; } for (i=0; i < size; i++) { dv = &plug->dev_events[i]; if (dv->slot==slot) { if ( dv->add) { dv->add =false; return; } dv->remove=true; return; } } dv = realloc(plug->dev_events, (size+1)*sizeof(struct dev_event)); dv[size].slot=slot; dv[size].remove=1; dv[size].add=0; plug->dev_events=dv; plug->deq_size=size+1; } static int flush_queued_dev_events(struct sock_plugin* plug) { int size = plug->deq_size; int i; struct event_record er; er.magic= MAGIC; er.itype=EV_DEV; struct dev_event* dv; for (i=size-1; i>-1; i--) { dv = &plug->dev_events[i]; er.ivalue=dv->slot; if (dv->remove) { er.icode=DEV_RESET; if(!send_to_plugin(plug, &er)) return false; dv->remove=false; } if (dv->add) { er.icode=DEV_CONF; if(!send_to_plugin(plug, &er)) return false; dv->add=false; } plug->deq_size--; plug->dev_events=realloc(plug->dev_events, plug->deq_size *sizeof(struct dev_event)); } return true; } void send_plugin_dev_event(struct sock_plugin* plug, int code, int value) { struct event_record er; er.magic= MAGIC; er.itype=EV_DEV; bool problem=false; if (plug->resetall) { er.icode=DEV_RESET; er.ivalue=0xFF; } else { er.icode=code; er.ivalue=value; } if ((code==DEV_RESET) && (value==0xFF)) { plug->deq_size=0; free(plug->dev_events); plug->dev_events=NULL; } else if (plug->deq_size) { problem = !flush_queued_dev_events(plug); } if (problem || !send_to_plugin(plug, &er)) { switch (code) { case DEV_CONF: add_queue_dev_event_conf(plug,value); break; case DEV_RESET: add_queue_dev_event_reset(plug,value); break; } } else if (plug->resetall) { // If resetall, we just transmitted a reset_all event, so now need to // transmit the original code we where invoked to send. plug->resetall=false; send_plugin_dev_event(plug,code,value); } } // send_delayed_to_plugin - calledfrom send_to_plugin // sends remaining of partial sends. static int send_delayed_to_plugin(struct sock_plugin* plug) { int r; do { r = send(plug->s, plug->partialBuffer, plug->delayed, MSG_NOSIGNAL | MSG_DONTWAIT); if (r>0) { plug->delayed-=r; if (plug->delayed) memmove(&plug->partialBuffer, ((char*) ( &plug->partialBuffer)) + r, plug->delayed); } } while ( ((r==-1) && (errno==EINTR)) || ((r>0) && (plug->delayed)) ); if (r==-1) { if ((errno != EAGAIN) && (errno != EWOULDBLOCK)) { info(strerror(errno)); kill_connection(plug); } return false; } return true; } // sends raw event to plugin. Partial sends are delt with. int send_to_plugin(struct sock_plugin* plug,struct event_record* e) { int r; if (plug->delayed) { r = send_delayed_to_plugin(plug); if (!r) { return false; } } do { r = send(plug->s, e, sizeof(struct event_record), MSG_NOSIGNAL | MSG_DONTWAIT); } while ((r==-1) && (errno==EINTR)); if (r==-1) { if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { // PACKET LOST; return false; } else { info(strerror(errno)); kill_connection(plug); } } else if (r< (int) sizeof(struct event_record)) // partial send { plug->delayed=sizeof(struct event_record) - r; memcpy(&plug->partialBuffer, ((char*)e) + r , plug->delayed); send_delayed_to_plugin(plug); } return true; } // sends an event, on the given slot, to the plugin void send_plugin_event(struct domain *d,int slot, struct input_event *e) { struct sock_plugin* plug=d->plugin; struct event_record er; er.magic= MAGIC; if (plug->error) { er.itype=EV_VM; er.icode=VM_ERROR; er.ivalue=plug->error; if (!send_to_plugin(plug, &er)) goto cantsend; plug->error=0; } if (plug->resetall) { er.itype=EV_DEV; er.icode=DEV_RESET; er.ivalue=0xFF; if (!send_to_plugin(plug, &er)) goto cantsend; plug->resetall=false; } if (plug->deq_size) if (!flush_queued_dev_events(plug)) goto cantsend; if (plug->slot!=slot) send_slot(plug, slot); if (plug->dropped) { er.itype=EV_SYN; er.icode=SYN_DROPPED; er.ivalue=0; plug->dropped = ! send_to_plugin(plug, &er); if (plug->dropped) return; } er.itype=e->type; er.icode=e->code; er.ivalue=e->value; if (!send_to_plugin(plug, &er)) { plug->dropped=true; } return; cantsend: if (plug->slot!=slot) plug->slot_dropped=true; else plug->dropped=true; return; } static void process_event(struct event_record* r, struct sock_plugin* plug) { if (r->itype == EV_VM) { struct domain* d; switch(r->icode) { case VM_SEND_TO: if ( !( plug->dest=domain_with_domid(r->ivalue)) ) { send_error(plug, E_BADDOMAIN, r->icode , r->ivalue); } else if (plug->dest->is_pv_domain) { send_error(plug, E_BADDOMAIN, r->icode , r->ivalue); plug->dest=NULL; } else { // Do we have the right dev slot? int devslot=plug->recived_slot; if ((devslot!=INPUTSLOT_INVALID) && (plug->dest->last_devslot!=devslot)) { send_event(plug, EV_DEV,DEV_SET, devslot); plug->dest->last_devslot=devslot; } } break; case VM_TAKE_FROM: if (plug->src) plug->src->plugin=NULL; d=domain_with_domid(r->ivalue); if (!d) { send_error(plug, E_BADDOMAIN, r->icode , r->ivalue); } else { d->plugin=plug; plug->src=d; sock_plugin_sendconfig(plug); } break; default: send_error(plug,E_BADCODE, r->icode, 0); } } else if (plug->dest) send_event(plug, r->itype, r->icode, r->ivalue); else send_error(plug, E_BADDOMAIN, 0 , 0xff); } void send_event(struct sock_plugin* plug, int t, int c, int v) { struct msg_dom0_input_event msg; struct domain* d = plug->dest; if ((NULL==d) || (NULL == d->client)) return; if (t==EV_DEV) { if(c==DEV_SET) { plug->recived_slot=v; d->last_devslot=v; } else // We don't want config events progated, since the VM will already know about it. return; } msg.type = t; msg.code = c; msg.value = v; dom0_input_event(d->client, &msg, sizeof(msg)); } static void server_accept(int fd, short event, void *opaque) { int s = (long)opaque; int s2; socklen_t t; struct sockaddr_un remote; t = sizeof (remote); if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) { info("Accept failed with %s",strerror(errno)); return; } if (buffers.s==-1) { buffers.src=NULL; buffers.dest=NULL; buffers.slot=INPUTSLOT_INVALID; buffers.bytes_remaining=0; buffers.position=0; buffers.recived_slot=INPUTSLOT_INVALID; buffers.dropped=false; buffers.slot_dropped=false; buffers.error=0; buffers.resetall=0; buffers.deq_size=0; buffers.dev_events=NULL; buffers.delayed=0; buffers.s=s2; info("Accepting client for Unix domain socket."); event_set (&server_recv_event, s2, EV_READ | EV_PERSIST, wrapper_server_recv, (void*)&buffers); event_add (&server_recv_event, NULL); } else { info("Second connection not allowed\n"); close(s2); } } void socket_server_init(void) { int len; struct sockaddr_un local; const char sock_path[]="/var/run/input_socket"; info("Opening Unix domain socket in %s",sock_path); buffers.s=-1; if ((server_sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { info("socket failed with %s",strerror(errno)); return; } local.sun_family = AF_UNIX; strcpy(local.sun_path, sock_path); unlink(local.sun_path); len = strlen(local.sun_path) + sizeof(local.sun_family); if (bind(server_sock_fd, (struct sockaddr *)&local, len) == -1) { info("bind failed with %s",strerror(errno)); close(server_sock_fd); return; } if (listen(server_sock_fd, 5) == -1) { info("listen failed with %s",strerror(errno)); close(server_sock_fd); return; } event_set (&server_accept_event, server_sock_fd, EV_READ | EV_PERSIST, server_accept, (void*)server_sock_fd); event_add (&server_accept_event, NULL); } void socket_server_close() { close(server_sock_fd); free(buffers.dev_events); }
14,217
C
.c
531
21.013183
114
0.596538
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,256
keymap.c
OpenXT_input/keymap.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <ctype.h> #include "project.h" #define NUM_MODIFIER_COLS 2 static int fd = -1; static int modifiers[][NUM_MODIFIER_COLS] = { {0, 0}, {KEY_RIGHTSHIFT, KEY_LEFTSHIFT}, {KEY_RIGHTALT, 0}, {0, 0}, {KEY_RIGHTCTRL, KEY_LEFTCTRL}, {0, 0}, {0, 0}, {0, 0}, {KEY_LEFTALT, 0}, }; static int get_bind(u_char index, u_char table) { struct kbentry ke; ke.kb_index = index; ke.kb_table = table; if (ioctl(fd, KDGKBENT, (unsigned long)&ke)) return 0; return ke.kb_value & 0xff; } int keycode2ascii(int keycode) { int i, j; int table = 0; int value; if (fd == -1) fd = open("/dev/tty0", O_RDWR); for (i = 0; i <= 8; i++) for (j = 0; (j < NUM_MODIFIER_COLS) && (modifiers[i][j]); j++) if (key_status_get(modifiers[i][j])) table |= i; value = get_bind(keycode, table); return (isprint(value) || (value >= 128 && value <= 255)) ? value : 0; } /** Return current keymap from the config file (free the returned string yourself), or NULL */ char *get_configured_keymap( void ) { char *rval = NULL; FILE *f = NULL; char line[256] = { 0 }; f = fopen(KEYMAP_CONF_FILE, "r"); if (!f) goto error; if (fgets(line, sizeof(line), f) == NULL) goto error; char *text = strstr(line, "KEYBOARD='"); if (!text) goto error; char *quoteend = strstr(text + strlen("KEYBOARD='"), "'"); if (!quoteend) goto error; unsigned long beg = (unsigned long)text + strlen("KEYBOARD='"); unsigned long len = (unsigned long)quoteend - beg; char layout[32] = { 0 }; strncpy( layout, (char*)beg, MIN(len, sizeof(layout)) ); rval = strdup( layout ); goto success; error: rval = NULL; success: if (f) { fclose(f); } return rval; } /** * For the moment only fd leak hunt is opened, the moment leak hunt is not * opened. * */ static void leak_hunt(void) { int i; int maxfd = sysconf(_SC_OPEN_MAX); for (i = 3; i < maxfd; ++i) { close(i); } } /** Change current keymap */ int loadkeys(const char *keymap) { pid_t pid; const char *bin = "/usr/bin/loadkeys"; int status; /* invoke loadkeys */ info("going to call %s with %s", bin, keymap); pid = fork(); if (pid == 0) { /* child */ leak_hunt(); execl(bin, bin, keymap, NULL); error("execl failed for %s with error %s", bin, strerror (errno)); exit (1); } else if (pid == -1) { error("failed to fork: %s", strerror (errno)); return -1; } waitpid(pid, &status, 0); if (!WIFEXITED(status)) { return -1; } int exitstatus = WEXITSTATUS(status); if (exitstatus!=0) return exitstatus; #if 0 /* Silly fork to check that fd was close */ pid = fork(); if (pid == 0) { /* child */ leak_hunt(); while (1); exit(1); } #endif /* write keymap to conf file */ FILE *f = fopen(KEYMAP_CONF_FILE, "w"); if (f) { fprintf(f, "KEYBOARD='%s'\n", keymap); fflush( f ); fsync( fileno(f) ); fclose( f ); } /* write keymap to xenstore */ xenstore_write( keymap, "/xenclient/keyboard/layout" ); /* permission misery */ char perm[16] = { 0 }; snprintf(perm, sizeof(perm), "r0"); xenstore_chmod ( perm, 1, "/xenclient/keyboard/layout" ); /* success */ return 0; } void keymap_init( ) { char *keys = get_configured_keymap( ); if (keys) { info("configuring initial keymap: %s", keys); loadkeys( keys ); free( keys ); } }
4,428
C
.c
156
23.775641
94
0.60193
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,258
superhidplugin.c
OpenXT_input/superhidplugin.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <stdint.h> #include <event.h> #include <linux/input.h> #include <fcntl.h> #define SOCK_PATH "/var/run/input_socket" #define MAGIC 0xAD9CBCE9 #define EVENT_SIZE (sizeof(struct event_record)) #define buffersize (EVENT_SIZE*20) /* Report IDs for the various devices */ #define REPORT_ID_KEYBOARD 0x01 #define REPORT_ID_MOUSE 0x02 #define REPORT_ID_TABLET 0x03 #define REPORT_ID_MULTITOUCH 0x04 #define REPORT_ID_STYLUS 0x05 #define REPORT_ID_PUCK 0x06 #define REPORT_ID_FINGER 0x07 #define REPORT_ID_MT_MAX_COUNT 0x10 #define REPORT_ID_CONFIG 0x11 #define REPORT_ID_INVALID 0xff /* Shouldn't that be defined somewhere already? */ #define ABS_MT_SLOT 0x2f #define EV_DEV 0x06 #define DEV_SET 0x01 /* All the following is specific to the superhid digitizer */ #define TIP_SWITCH 0x01 #define IN_RANGE 0x02 #define DATA_VALID 0x04 #define FINGER_1 0x08 #define FINGER_2 0x10 #define FINGER_3 0x18 #define LOW_X 0 #define HIGH_X 0xFFF #define LOW_Y 0 #define HIGH_Y 0xFFF /* This is actually 8, but we don't want to segv if input_server sends 10 */ #define MAX_FINGERS 10 struct event_record { uint32_t magic; uint16_t itype; uint16_t icode; uint32_t ivalue; } __attribute__ ((__packed__)); struct buffer_t { char buffer[buffersize]; unsigned int bytes_remaining; int position; int s; int copy; int block; } buffers; struct superhid_report { uint8_t report_id; uint8_t misc; uint16_t x; uint16_t y; } __attribute__ ((__packed__)); int hid_fd; struct event recv_event; static void stop () { event_del (&recv_event); } /* Some OSes swap the x,y coordinates for some reason... */ static uint16_t swap_bytes(uint16_t n) { uint16_t res; res = ((n << 8) & 0xFF00) + (n >> 8); return res; } /* This function simulates a touchscreen from a mouse. */ /* Useful to debug the driver without a tablet handy! */ static int process_relative_event(uint16_t itype, uint16_t icode, uint32_t ivalue, char left, char middle, char right) { struct superhid_report report; static uint16_t x = LOW_X; static uint16_t y = LOW_Y; /* Don't process if this is not a mouse/trackpad move/clic */ if (itype != EV_REL && itype != EV_ABS && !(itype == EV_KEY && (icode == BTN_LEFT || icode == BTN_RIGHT || icode == BTN_MIDDLE))) return 0; if (itype == EV_REL && icode == REL_X && x + ivalue > LOW_X && x + ivalue < HIGH_X) x += ivalue; if (itype == EV_REL && icode == REL_Y && y + ivalue > LOW_Y && y + ivalue < HIGH_Y) y += ivalue; if (itype == EV_ABS && icode == ABS_X && ivalue / 10 > LOW_X && ivalue / 10 < HIGH_X) x = ivalue / 10; if (itype == EV_ABS && icode == ABS_Y && ivalue / 10 > LOW_Y && ivalue / 10 < HIGH_Y) y = ivalue / 10; report.report_id = REPORT_ID_MULTITOUCH; report.misc = 0; report.misc |= FINGER_1; if (left) report.misc |= TIP_SWITCH; report.misc |= IN_RANGE; report.misc |= DATA_VALID; /* report.x = swap_bytes(x); */ /* report.y = swap_bytes(y); */ report.x = x; report.y = y; write(hid_fd, &report, 6); if (middle) { report.misc |= TIP_SWITCH; report.misc &= 0xF7; report.misc |= FINGER_2; report.x = report.x + 50; write(hid_fd, &report, 6); } if (right) { report.misc |= TIP_SWITCH; report.misc &= 0xE7; report.misc |= FINGER_3; if (middle) report.x = report.x + 50; else report.x = report.x + 100; write(hid_fd, &report, 6); } return 1; } static void process_absolute_event(uint16_t itype, uint16_t icode, uint32_t ivalue) { static struct superhid_report report[MAX_FINGERS] = { 0 }; static int finger = 0; int i; static char just_syned = 0; /* Initialize the report array */ if (report[finger].report_id == 0) { for (i = 0; i < MAX_FINGERS; ++i) { report[i].report_id = REPORT_ID_MULTITOUCH; report[i].misc = 0; /* TODO: use that flag(s) properly :) */ report[i].misc |= IN_RANGE; report[i].misc |= DATA_VALID; /* Setting the finger ID */ report[i].misc |= (i << 3) & 0xF8; /* Finger touching by default? */ /* report[i].misc |= TIP_SWITCH; */ } } switch (itype) { case EV_ABS: switch (icode) { /* case ABS_X: */ case ABS_MT_POSITION_X: report[finger].x = ivalue >> 3; break; /* case ABS_Y: */ case ABS_MT_POSITION_Y: report[finger].y = ivalue >> 3; break; case ABS_MT_SLOT: /* We force a SYN_REPORT on ABS_MT_SLOT, because the device is serial. */ /* However, we don't want to send twice the same event for nothing... */ if (!just_syned) write(hid_fd, &(report[finger]), 6); finger = ivalue; break; case ABS_MT_TRACKING_ID: if (ivalue == 0xFFFFFFFF) report[finger].misc &= ~TIP_SWITCH; else report[finger].misc |= TIP_SWITCH; default: break; } break; case EV_KEY: switch (icode) { default: break; } break; case EV_SYN: switch (icode) { case SYN_REPORT: write(hid_fd, &(report[finger]), 6); just_syned = 1; /* re-init */ /* Nothing to do? */ return; break; default: break; } default: break; } just_syned = 0; } static void process_event (struct event_record *r, struct buffer_t *b) { uint16_t itype; uint16_t icode; uint32_t ivalue; static int dev_set; static char left = 0; static char middle = 0; static char right = 0; int relatived = 0; itype = r->itype; icode = r->icode; ivalue = r->ivalue; if (itype == EV_KEY && icode == BTN_LEFT) left = !!ivalue; if (itype == EV_KEY && icode == BTN_MIDDLE) middle = !!ivalue; if (itype == EV_KEY && icode == BTN_RIGHT) right = !!ivalue; /* Uncomment the following line to emulate a touchscreen from a mouse */ /* relatived = process_relative_event(itype, icode, ivalue, left, middle, right); */ if (relatived) return; if (itype == EV_DEV && icode == DEV_SET) { dev_set = ivalue; printf("DEV_SET %d\n", dev_set); } if (dev_set != 6) { /* process_relative_event() didn't do anything, and this is not a * touchscreen event (device 6). * At this point we'd want to just send that event to the guest * unmodified. Unfortunately, event sending seems to be broken... */ #if 0 if (itype == EV_KEY) { r->magic = MAGIC; send(b->s, r, sizeof(struct event_record), 0); } #endif return; } process_absolute_event(itype, icode, ivalue); } struct event_record *findnext (struct buffer_t *b) { struct event_record *r = NULL; int start = b->position; /* Skip junk */ while (b->bytes_remaining >= EVENT_SIZE && (r = (struct event_record *) &b->buffer[b->position]) && r->magic != MAGIC) { printf("SKIPPED!\n"); b->bytes_remaining--; b->position++; } if (start != b->position) printf ("Warning: Encountered %d bytes of junk.\n", b->position - start); if (b->bytes_remaining >= EVENT_SIZE) { b->bytes_remaining -= EVENT_SIZE; b->position += EVENT_SIZE; return r; } else return NULL; } static void recv_callback (int fd, short event, void *opaque) { int n; struct buffer_t *buf = &buffers; char *b = buf->buffer; memmove (b, &b[buf->position], buf->bytes_remaining); buf->position = 0; size_t nbytes = 0; n = recv (fd, &b[buf->bytes_remaining], buffersize - buf->bytes_remaining, 0); if (n > 0) { struct event_record *r = NULL; buf->bytes_remaining += n; while ((r = findnext (buf)) != NULL) process_event (r, buf); } else if (n) printf ("Error %d\n", n); else stop(); } /* This function tells input_server to send us the events for the domain */ void suck (int s, int d) { struct event_record e; e.magic = MAGIC; e.itype = 7; e.icode = 0x2; e.ivalue = d; if (send (s, &e, sizeof (struct event_record), 0) == -1) { perror ("send"); exit (1); } } int main (int argc, char** argv) { int s, t, len; struct sockaddr_un remote; char str[100]; pthread_t output_thread_var; if (argc != 2) { printf("Usage: superhidplugin <domid>\n"); exit(1); } /* Trying to connect to input_server to get events */ if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) == -1) { perror ("socket"); exit (1); } printf ("Trying to connect...\n"); remote.sun_family = AF_UNIX; strcpy (remote.sun_path, SOCK_PATH); len = strlen (remote.sun_path) + sizeof (remote.sun_family); if (connect (s, (struct sockaddr *) &remote, len) == -1) { perror ("connect"); exit (1); } printf ("Connected.\n"); buffers.bytes_remaining = 0; buffers.position = 0; buffers.copy = 0; buffers.block = 0; buffers.s = s; /* Now connect to the superhid device */ hid_fd = open("/dev/hidg0", O_RDWR, 0666); if (hid_fd == -1) { perror("/dev/hidg0"); exit(1); } event_init (); event_set (&recv_event, s, EV_READ | EV_PERSIST, recv_callback, NULL); event_add (&recv_event, NULL); suck (s, strtol(argv[1], NULL, 0)); event_dispatch (); close (s); return 0; }
10,201
C
.c
374
23.652406
93
0.632797
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,262
lid.c
OpenXT_input/lid.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" struct lid_switch *lid_switch_public; struct lid_switch_private { struct lid_switch public; struct event device_event; int fd; int status; }; static void wrapper_lid_read(int fd, short unused, void *opaque) { struct lid_switch_private *lid_switch = opaque;; int read_sz = 0; struct input_event event; /* paranoia */ if (fd != lid_switch->fd) return; memset(&event, 0, sizeof (event)); if ((read_sz = read(lid_switch->fd, &event, sizeof (event))) <= 0) { event_del(&lid_switch->device_event); close(fd); free(lid_switch); return; } if (event.type == EV_SW && event.value != lid_switch->status) { xenstore_write(event.value ? "0" : "1", "/pm/lid_state"); lid_switch->status = event.value; notify_com_citrix_xenclient_input_lid_state_changed(xcbus_conn, XCPMD_SERVICE, XCPMD_PATH); } } static int lid_get_lid_state(struct lid_switch *lid_public) { struct lid_switch_private *lid_switch = (struct lid_switch_private*) lid_public; return !lid_switch->status; } void lid_create_switch_event(int fd) { struct lid_switch_private *lid_switch; long bitmask; lid_switch = malloc(sizeof (struct lid_switch_private)); memset(lid_switch, 0x0, sizeof (struct lid_switch_private)); lid_switch->fd = fd; event_set(&lid_switch->device_event, fd, EV_READ | EV_PERSIST, wrapper_lid_read, (void*) lid_switch); event_add(&lid_switch->device_event, NULL); ioctl(fd, EVIOCGSW(sizeof (bitmask)), &bitmask); xenstore_write(bitmask ? "0" : "1", "/pm/lid_state"); lid_switch->status = bitmask; lid_switch->public.get_lid_state = lid_get_lid_state; lid_switch_public = &lid_switch->public; } void lid_switch_release(bool infork) { struct lid_switch_private *lid_switch = (struct lid_switch_private *) lid_switch_public; (void) infork; if (!lid_switch) return; /* FIXME: For the moment only close file descriptor */ close(lid_switch->fd); }
2,921
C
.c
83
30.939759
99
0.673875
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,263
xc_input_socket_protocol.h
OpenXT_input/xc_input_socket_protocol.h
/* * Copyright (c) 2011 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _XC_INPUT_SOCKET_PROTOCOL_H_ #define _XC_INPUT_SOCKET_PROTOCOL_H_ #define SWITCHER_SHUTDOWN_REBOOT 0 #define SWITCHER_SHUTDOWN_S3 3 #define SWITCHER_SHUTDOWN_S4 4 #define SWITCHER_SHUTDOWN_S5 5 enum switcher_opt { SWITCHER_OPT_PVM = 1 }; #endif
1,059
C
.c
28
35.821429
81
0.767057
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,265
encapsulate.c
OpenXT_input/encapsulate.c
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" static struct domain *keyb_dest = NULL; void set_keyb_dest(struct domain *d) { if (keyb_dest != d) { keyb_dest = d; input_set_focus_change(); } } struct domain *get_keyb_dest(void) { return keyb_dest; }
1,057
C
.c
31
31.322581
81
0.728963
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,266
main.c
OpenXT_input/main.c
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "project.h" int main(int argc,char *argv[]) { event_init(); bus_init(); xenstore_init(); input_init(); domains_init(); server_init(); switcher_init(); keymap_init(); pm_init(); xen_backend_init(0); socket_server_init(); info ("Dispatching events (Event lib v%s. Method %s)",event_get_version (),event_get_method ()); event_dispatch(); socket_server_close(); return 0; }
1,253
C
.c
36
31.25
100
0.70598
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,296
keyboard.h
OpenXT_input/keyboard.h
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KEYBOARD_H #define KEYBOARD_H #define LED_CODE_SCROLLLOCK 0x01 #define LED_CODE_NUMLOCK 0x02 #define LED_CODE_CAPSLOCK 0x04 #endif
944
C
.h
23
39.086957
81
0.765795
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,298
lid.h
OpenXT_input/lid.h
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LID_H_ #define LID_H_ struct lid_switch; typedef int(*get_lid_state_ptr)(struct lid_switch *lid_public); struct lid_switch { get_lid_state_ptr get_lid_state; }; #endif /* LID_H_ */
995
C
.h
26
36.192308
81
0.751037
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,301
xen_vkbd.h
OpenXT_input/xen_vkbd.h
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef XEN_VKBD_H_ #define XEN_VKBD_H_ /* External includes */ #include <xen/io/kbdif.h> #include <xenbackend.h> #include <fb2if.h> /* Structures definitions */ struct xen_vkbd_device { xen_backend_t backend; int devid; void *page; struct event evtchn_event; }; struct xen_vkbd_backend { xen_backend_t backend; int domid; /* Device used for keyboard and relative mouse events */ struct xen_vkbd_device *device; /* Device used for absolute mouse events */ struct xen_vkbd_device *abs_device; }; #endif /* XEN_VKBD_H_ */
1,364
C
.h
41
30.658537
81
0.735562
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,304
gesture.h
OpenXT_input/gesture.h
/* * Copyright (c) 2012 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GESTURE_H #define GESTURE_H typedef enum gesture_position { eNa_p, eGiven_p1, eGiven_p2, eAbsPosition, eLeft, eRight, eTop, eBottom, eTop_Left, eTop_Right, eBottom_Left, eBottom_Right } gesture_position; enum action_type { eEnd, eContact, eRelease, eMove, }; typedef enum post_movement { eNa_m, eDontMove, eMoveAnywhere, eMoveLeft, eMoveRight, eMoveUp, eMoveDown, eMoveLeftDown, eMoveRightDown, eMoveLeftUp, eMoveRighUp, eGiven_m1, eGiven_m2, } post_movement; struct smallaction_slot { enum action_type action; int finger; enum gesture_position pos; int timel; enum post_movement pmove; }; struct smallaction_list { struct smallaction_slot *actions; gesture_position p1; gesture_position p2; post_movement m1; post_movement m2; int timelimit; }; typedef struct gesture { struct smallaction_list *actionlist; void (*callback) (void); int act; int sub_act; char name[10]; } gesture; #endif
1,885
C
.h
83
19.168675
81
0.71676
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,305
bus.h
OpenXT_input/bus.h
/* * Copyright (c) 2011 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define OBJ_PATH "/" #define INTERFACE "com.citrix.xenclient.input" #define SERVICE "com.citrix.xenclient.input" #define SURFMAN_SERVICE "com.citrix.xenclient.surfman" #define SURFMAN_PATH "/" #define XENMGR_SERVICE "com.citrix.xenclient.xenmgr" #define XENMGR_VMS_OBJPATH "/com/citrix/xenclient/xenmgr/vms" #define XENMGR_HOST_OBJPATH "/host" #define DB_SERVICE "com.citrix.xenclient.db" #define DB_PATH "/" #define XCPMD_SERVICE "com.citrix.xenclient.xcpmd" #define XCPMD_PATH "/"
1,300
C
.h
29
43
81
0.760664
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,306
user.h
OpenXT_input/user.h
/* * Copyright (c) 2010 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef USER_H_ #define USER_H_ #define NAME_LEN 512 int user_create( const char *hash, const char *name, const char *password_file, const char *recovery_file ); int user_assoc( const char *hash, const char *name ); int user_get_name( const char *hash, char *name ); #endif
1,075
C
.h
24
42.833333
108
0.753582
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,310
input.h
OpenXT_input/input.h
/* * Copyright (c) 2013 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ typedef int (*input_binding_cb_t)(void *); #define N_DEVS 64 #define INPUTSLOT_DEFAULT -1 #define INPUTSLOT_INVALID -2 #define EV_DEV 0x6 #define DEV_SET 0x1 #define DEV_CONF 0x2 #define DEV_RESET 0x3 #ifndef SYN_DROPPED # define SYN_DROPPED 0x3 #endif
1,082
C
.h
28
36.857143
81
0.744053
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
16,259,311
timer.h
OpenXT_input/timer.h
/* * Copyright (c) 2010 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ struct timer_t; typedef void (*fd_handler_read_t)(void *); typedef void (*timer_callback_t)(void *);
901
C
.h
20
42.95
81
0.753986
OpenXT/input
2
14
0
LGPL-2.1
9/7/2024, 2:37:12 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true