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 
30 static 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  {
38  die(1, "allocating merge path buffer");
39  }
40  return path;
41 }
42 
43 char* search_program(const char *progname)
44 {
45  char *launch = NULL;
46  char *cwd;
47 
48  if (progname[0] == '/')
49  {
50  launch = strdup(progname);
51  if (!launch)
52  {
53  die(1, "allocating program name buffer");
54  }
55  }
56  else if (strchr(progname, '/') != NULL)
57  {
58  cwd = get_current_dir_name();
59  launch = merge_paths(cwd, progname);
60  free(cwd);
61  }
62  else
63  {
64  char *path = getenv("PATH");
65  char *saveptr = NULL;
66  char *token;
67 
68  if (path == NULL)
69  {
70  die(1, "could not get PATH environment variable");
71  }
72  path = strdup(path);
73 
74  for (token = strtok_r(path, ":", &saveptr); token != NULL; token = strtok_r(NULL, ":", &saveptr))
75  {
76  launch = merge_paths(token, progname);
77 
78  if (access(launch, X_OK) == 0)
79  break;
80 
81  free(launch);
82  launch = NULL;
83  }
84 
85  free(path);
86 
87  if (launch == NULL)
88  {
89  die(1, "could not locate program \"%s\" to launch \n", progname);
90  }
91 
92  if (launch[0] != '/')
93  {
94  char *relative = launch;
95 
96  cwd = get_current_dir_name();
97  launch = merge_paths(cwd, relative);
98 
99  free(cwd);
100  free(relative);
101  }
102  }
103  return launch;
104 }
105 
char * search_program(const char *progname)
Definition: search.c:43
static char * merge_paths(const char *base_path, const char *rel_path)
Definition: search.c:30