+/* Given a program name, search the PATH environment variable and
+ * return the first absolute path to 'program'.
+ *
+ * Returns: A string talloc'ed to 'ctx'.
+ *
+ * Note: This function aborts the current program if 'program' cannot
+ * be located by searching PATH.
+ */
+static char *
+search_path_for_program (void *ctx, const char *program)
+{
+ char *orig_path, *path, *colon, *dir, *candidate;
+ void *local = talloc_new (ctx);
+
+ /* If the program name already contains a slash, then this is
+ * an absolute (or relative) path. Either way, we don't search
+ * PATH, since we can directly open this filename. */
+ if (strchr (program, '/'))
+ return talloc_strdup (ctx, program);
+
+ orig_path = path = getenv ("PATH");
+
+ while (*path) {
+ colon = strchr (path, ':');
+
+ if (colon) {
+ dir = talloc_strndup (local, path, colon - path);
+ path = colon + 1;
+ } else {
+ dir = path;
+ path = path + strlen (path);
+ }
+
+ candidate = talloc_asprintf(local, "%s/%s", dir, program);
+
+ if (exists (candidate)) {
+ talloc_steal (ctx, candidate);
+ talloc_free (local);
+ return candidate;
+ } else {
+ talloc_free (candidate);
+ }
+ }
+
+ fprintf (stderr, "Cannot find program %s (looked in %s)\n",
+ program, orig_path);
+ exit (1);
+}
+