applauncherd
search.c
Go to the documentation of this file.
1/***************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (directui@nokia.com)
6**
7** This file is part of applauncherd
8**
9** If you have questions regarding the use of this file, please contact
10** Nokia at directui@nokia.com.
11**
12** This library is free software; you can redistribute it and/or
13** modify it under the terms of the GNU Lesser General Public
14** License version 2.1 as published by the Free Software Foundation
15** and appearing in the file LICENSE.LGPL included in the packaging
16** of this file.
17**
18****************************************************************************/
19
20#define _GNU_SOURCE
21
22#include <stdlib.h>
23#include <stdio.h>
24#include <unistd.h>
25#include <string.h>
26
27#include "report.h"
28#include "search.h"
29
30static char* merge_paths(const char *base_path, const char *rel_path)
31{
32 char *path;
33
34 if (asprintf(&path, "%s%s%s", base_path,
35 (base_path[strlen(base_path) - 1] == '/' ? "" : "/"),
36 rel_path) < 0) {
37 die(1, "allocating merge path buffer");
38 }
39 return path;
40}
41
42char* search_program(const char *progname)
43{
44 char *launch = NULL;
45 char *cwd;
46
47 if (progname[0] == '/') {
48 launch = strdup(progname);
49 if (!launch) {
50 die(1, "allocating program name buffer");
51 }
52 } else if (strchr(progname, '/') != NULL) {
53 cwd = get_current_dir_name();
54 launch = merge_paths(cwd, progname);
55 free(cwd);
56 } else {
57 char *path = getenv("PATH");
58 char *saveptr = NULL;
59 char *token;
60
61 if (path == NULL) {
62 die(1, "could not get PATH environment variable");
63 }
64 path = strdup(path);
65
66 for (token = strtok_r(path, ":", &saveptr); token != NULL; token = strtok_r(NULL, ":", &saveptr)) {
67 launch = merge_paths(token, progname);
68
69 if (access(launch, X_OK) == 0)
70 break;
71
72 free(launch);
73 launch = NULL;
74 }
75
76 free(path);
77
78 if (launch == NULL) {
79 die(1, "could not locate program \"%s\" to launch \n", progname);
80 }
81
82 if (launch[0] != '/') {
83 char *relative = launch;
84
85 cwd = get_current_dir_name();
86 launch = merge_paths(cwd, relative);
87
88 free(cwd);
89 free(relative);
90 }
91 }
92
93 return launch;
94}
static char * merge_paths(const char *base_path, const char *rel_path)
Definition search.c:30
char * search_program(const char *progname)
Definition search.c:42