+int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
+ struct hsearch_data *htab)
+{
+ unsigned int idx;
+ size_t key_len = strlen(match);
+
+ for (idx = last_idx + 1; idx < htab->size; ++idx) {
+ if (htab->table[idx].used <= 0)
+ continue;
+ if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
+ *retval = &htab->table[idx].entry;
+ return idx;
+ }
+ }
+
+ __set_errno(ESRCH);
+ *retval = NULL;
+ return 0;
+}
+
+/*
+ * Compare an existing entry with the desired key, and overwrite if the action
+ * is ENTER. This is simply a helper function for hsearch_r().
+ */
+static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
+ ENTRY **retval, struct hsearch_data *htab, int flag,
+ unsigned int hval, unsigned int idx)
+{
+ if (htab->table[idx].used == hval
+ && strcmp(item.key, htab->table[idx].entry.key) == 0) {
+ /* Overwrite existing value? */
+ if ((action == ENTER) && (item.data != NULL)) {
+ /* check for permission */
+ if (htab->change_ok != NULL && htab->change_ok(
+ &htab->table[idx].entry, item.data,
+ env_op_overwrite, flag)) {
+ debug("change_ok() rejected setting variable "
+ "%s, skipping it!\n", item.key);
+ __set_errno(EPERM);
+ *retval = NULL;
+ return 0;
+ }
+
+ /* If there is a callback, call it */
+ if (htab->table[idx].entry.callback &&
+ htab->table[idx].entry.callback(item.key,
+ item.data, env_op_overwrite, flag)) {
+ debug("callback() rejected setting variable "
+ "%s, skipping it!\n", item.key);
+ __set_errno(EINVAL);
+ *retval = NULL;
+ return 0;
+ }
+
+ free(htab->table[idx].entry.data);
+ htab->table[idx].entry.data = strdup(item.data);
+ if (!htab->table[idx].entry.data) {
+ __set_errno(ENOMEM);
+ *retval = NULL;
+ return 0;
+ }
+ }
+ /* return found entry */
+ *retval = &htab->table[idx].entry;
+ return idx;
+ }
+ /* keep searching */
+ return -1;
+}
+