1// SPDX-License-Identifier: GPL-3.0-or-later
2#include "mossh.hpp"
3
4#include <filesystem>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <sys/stat.h>
9#include <sys/wait.h>
10#include <vector>
11
12const std::vector<std::filesystem::path> &get_paths(bool force)
13{
14 static std::vector<std::filesystem::path> paths;
15 static bool paths_initialized = false;
16
17 if (paths_initialized && !force)
18 return paths;
19
20 paths.clear();
21 const char *path = getenv(name: "PATH");
22 if (!path)
23 paths_initialized = true;
24
25 std::string p = path;
26 size_t start = 0;
27 size_t end = p.find(c: ':');
28 while (end != std::string::npos)
29 {
30 paths.push_back(x: p.substr(pos: start, n: end - start));
31 start = end + 1;
32 end = p.find(c: ':', pos: start);
33 }
34
35 paths.push_back(x: p.substr(pos: start));
36 paths_initialized = true;
37 return paths;
38}
39
40std::string string_trim(const std::string &in)
41{
42 std::string out = in;
43
44 // trim trailing spaces, tabs, and newlines
45 out.erase(pos: out.find_last_not_of(s: " \n\r\t") + 1);
46
47 // trim leading spaces, tabs, and newlines
48 size_t startpos = out.find_first_not_of(s: " \n\r\t");
49 if (std::string::npos != startpos)
50 out = out.substr(pos: startpos);
51
52 return out;
53}
54
55std::pair<int, int> wait_for_pid(pid_t pid, int flags)
56{
57 std::pair<int, int> exit_code_signal;
58
59 int status = 0;
60 waitpid(pid, status: &status, flags);
61 if (WIFEXITED(status))
62 {
63 exit_code_signal.first = WEXITSTATUS(status);
64 }
65 else if (WIFSIGNALED(status))
66 {
67 exit_code_signal.second = WTERMSIG(status);
68 }
69
70 return exit_code_signal;
71}
72