utilunix.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. /*
  2. Various utilities - Unix variants
  3. Copyright (C) 1994-2021
  4. Free Software Foundation, Inc.
  5. Written by:
  6. Miguel de Icaza, 1994, 1995, 1996
  7. Janne Kukonlehto, 1994, 1995, 1996
  8. Dugan Porter, 1994, 1995, 1996
  9. Jakub Jelinek, 1994, 1995, 1996
  10. Mauricio Plaza, 1994, 1995, 1996
  11. The mc_realpath routine is mostly from uClibc package, written
  12. by Rick Sladkey <jrs@world.std.com>
  13. This file is part of the Midnight Commander.
  14. The Midnight Commander is free software: you can redistribute it
  15. and/or modify it under the terms of the GNU General Public License as
  16. published by the Free Software Foundation, either version 3 of the License,
  17. or (at your option) any later version.
  18. The Midnight Commander is distributed in the hope that it will be useful,
  19. but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. GNU General Public License for more details.
  22. You should have received a copy of the GNU General Public License
  23. along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. */
  25. /** \file utilunix.c
  26. * \brief Source: various utilities - Unix variant
  27. */
  28. #include <config.h>
  29. #include <ctype.h>
  30. #include <errno.h>
  31. #include <limits.h>
  32. #include <signal.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #ifdef HAVE_SYS_PARAM_H
  38. #include <sys/param.h>
  39. #endif
  40. #include <sys/types.h>
  41. #include <sys/stat.h>
  42. #ifdef HAVE_SYS_SELECT_H
  43. #include <sys/select.h>
  44. #endif
  45. #include <sys/wait.h>
  46. #include <pwd.h>
  47. #include <grp.h>
  48. #include "lib/global.h"
  49. #include "lib/unixcompat.h"
  50. #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
  51. #include "lib/strutil.h" /* str_move() */
  52. #include "lib/util.h"
  53. #include "lib/widget.h" /* message() */
  54. #include "lib/vfs/xdirentry.h"
  55. #ifdef HAVE_CHARSET
  56. #include "lib/charsets.h"
  57. #endif
  58. #include "utilunix.h"
  59. /*** global variables ****************************************************************************/
  60. struct sigaction startup_handler;
  61. /*** file scope macro definitions ****************************************************************/
  62. #define UID_CACHE_SIZE 200
  63. #define GID_CACHE_SIZE 30
  64. /* Pipes are guaranteed to be able to hold at least 4096 bytes */
  65. /* More than that would be unportable */
  66. #define MAX_PIPE_SIZE 4096
  67. /*** file scope type declarations ****************************************************************/
  68. typedef struct
  69. {
  70. int index;
  71. char *string;
  72. } int_cache;
  73. typedef enum
  74. {
  75. FORK_ERROR = -1,
  76. FORK_CHILD,
  77. FORK_PARENT,
  78. } my_fork_state_t;
  79. typedef struct
  80. {
  81. struct sigaction intr;
  82. struct sigaction quit;
  83. struct sigaction stop;
  84. } my_system_sigactions_t;
  85. /*** file scope variables ************************************************************************/
  86. static int_cache uid_cache[UID_CACHE_SIZE];
  87. static int_cache gid_cache[GID_CACHE_SIZE];
  88. /* --------------------------------------------------------------------------------------------- */
  89. /*** file scope functions ************************************************************************/
  90. /* --------------------------------------------------------------------------------------------- */
  91. static char *
  92. i_cache_match (int id, int_cache * cache, int size)
  93. {
  94. int i;
  95. for (i = 0; i < size; i++)
  96. if (cache[i].index == id)
  97. return cache[i].string;
  98. return 0;
  99. }
  100. /* --------------------------------------------------------------------------------------------- */
  101. static void
  102. i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
  103. {
  104. g_free (cache[*last].string);
  105. cache[*last].string = g_strdup (text);
  106. cache[*last].index = id;
  107. *last = ((*last) + 1) % size;
  108. }
  109. /* --------------------------------------------------------------------------------------------- */
  110. static my_fork_state_t
  111. my_fork (void)
  112. {
  113. pid_t pid;
  114. pid = fork ();
  115. if (pid < 0)
  116. {
  117. fprintf (stderr, "\n\nfork () = -1\n");
  118. return FORK_ERROR;
  119. }
  120. if (pid == 0)
  121. return FORK_CHILD;
  122. while (TRUE)
  123. {
  124. int status = 0;
  125. if (waitpid (pid, &status, 0) > 0)
  126. return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
  127. if (errno != EINTR)
  128. return FORK_ERROR;
  129. }
  130. }
  131. /* --------------------------------------------------------------------------------------------- */
  132. static void
  133. my_system__save_sigaction_handlers (my_system_sigactions_t * sigactions)
  134. {
  135. struct sigaction ignore;
  136. memset (&ignore, 0, sizeof (ignore));
  137. ignore.sa_handler = SIG_IGN;
  138. sigemptyset (&ignore.sa_mask);
  139. sigaction (SIGINT, &ignore, &sigactions->intr);
  140. sigaction (SIGQUIT, &ignore, &sigactions->quit);
  141. /* Restore the original SIGTSTP handler, we don't want ncurses' */
  142. /* handler messing the screen after the SIGCONT */
  143. sigaction (SIGTSTP, &startup_handler, &sigactions->stop);
  144. }
  145. /* --------------------------------------------------------------------------------------------- */
  146. static void
  147. my_system__restore_sigaction_handlers (my_system_sigactions_t * sigactions)
  148. {
  149. sigaction (SIGINT, &sigactions->intr, NULL);
  150. sigaction (SIGQUIT, &sigactions->quit, NULL);
  151. sigaction (SIGTSTP, &sigactions->stop, NULL);
  152. }
  153. /* --------------------------------------------------------------------------------------------- */
  154. static GPtrArray *
  155. my_system_make_arg_array (int flags, const char *shell, char **execute_name)
  156. {
  157. GPtrArray *args_array;
  158. args_array = g_ptr_array_new ();
  159. if ((flags & EXECUTE_AS_SHELL) != 0)
  160. {
  161. g_ptr_array_add (args_array, (gpointer) shell);
  162. g_ptr_array_add (args_array, (gpointer) "-c");
  163. *execute_name = g_strdup (shell);
  164. }
  165. else
  166. {
  167. char *shell_token;
  168. shell_token = shell != NULL ? strchr (shell, ' ') : NULL;
  169. if (shell_token == NULL)
  170. *execute_name = g_strdup (shell);
  171. else
  172. *execute_name = g_strndup (shell, (gsize) (shell_token - shell));
  173. g_ptr_array_add (args_array, (gpointer) shell);
  174. }
  175. return args_array;
  176. }
  177. /* --------------------------------------------------------------------------------------------- */
  178. static void
  179. mc_pread_stream (mc_pipe_stream_t * ps, const fd_set * fds)
  180. {
  181. size_t buf_len;
  182. ssize_t read_len;
  183. if (!FD_ISSET (ps->fd, fds))
  184. {
  185. ps->len = MC_PIPE_STREAM_UNREAD;
  186. return;
  187. }
  188. buf_len = (size_t) ps->len;
  189. if (buf_len >= MC_PIPE_BUFSIZE)
  190. buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
  191. do
  192. {
  193. read_len = read (ps->fd, ps->buf, buf_len);
  194. }
  195. while (read_len < 0 && errno == EINTR);
  196. if (read_len < 0)
  197. {
  198. /* reading error */
  199. ps->len = MC_PIPE_ERROR_READ;
  200. ps->error = errno;
  201. }
  202. else if (read_len == 0)
  203. /* EOF */
  204. ps->len = MC_PIPE_STREAM_EOF;
  205. else
  206. {
  207. /* success */
  208. ps->len = read_len;
  209. if (ps->null_term)
  210. ps->buf[(size_t) ps->len] = '\0';
  211. }
  212. ps->pos = 0;
  213. }
  214. /* --------------------------------------------------------------------------------------------- */
  215. /*** public functions ****************************************************************************/
  216. /* --------------------------------------------------------------------------------------------- */
  217. const char *
  218. get_owner (uid_t uid)
  219. {
  220. struct passwd *pwd;
  221. char *name;
  222. static uid_t uid_last;
  223. name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
  224. if (name != NULL)
  225. return name;
  226. pwd = getpwuid (uid);
  227. if (pwd != NULL)
  228. {
  229. i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
  230. return pwd->pw_name;
  231. }
  232. else
  233. {
  234. static char ibuf[10];
  235. g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
  236. return ibuf;
  237. }
  238. }
  239. /* --------------------------------------------------------------------------------------------- */
  240. const char *
  241. get_group (gid_t gid)
  242. {
  243. struct group *grp;
  244. char *name;
  245. static gid_t gid_last;
  246. name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
  247. if (name != NULL)
  248. return name;
  249. grp = getgrgid (gid);
  250. if (grp != NULL)
  251. {
  252. i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
  253. return grp->gr_name;
  254. }
  255. else
  256. {
  257. static char gbuf[10];
  258. g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
  259. return gbuf;
  260. }
  261. }
  262. /* --------------------------------------------------------------------------------------------- */
  263. /* Since ncurses uses a handler that automatically refreshes the */
  264. /* screen after a SIGCONT, and we don't want this behavior when */
  265. /* spawning a child, we save the original handler here */
  266. void
  267. save_stop_handler (void)
  268. {
  269. sigaction (SIGTSTP, NULL, &startup_handler);
  270. }
  271. /* --------------------------------------------------------------------------------------------- */
  272. /**
  273. * Wrapper for _exit() system call.
  274. * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
  275. * mock the call.
  276. *
  277. * @param status exit code
  278. */
  279. void
  280. /* __attribute__ ((noreturn)) */
  281. my_exit (int status)
  282. {
  283. _exit (status);
  284. }
  285. /* --------------------------------------------------------------------------------------------- */
  286. /**
  287. * Call external programs.
  288. *
  289. * @parameter flags addition conditions for running external programs.
  290. * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  291. * Shell (or command) will be found in paths described in PATH variable
  292. * (if shell parameter doesn't begin from path delimiter)
  293. * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
  294. * @return 0 if successfull, -1 otherwise
  295. */
  296. int
  297. my_system (int flags, const char *shell, const char *command)
  298. {
  299. return my_systeml (flags, shell, command, NULL);
  300. }
  301. /* --------------------------------------------------------------------------------------------- */
  302. /**
  303. * Call external programs with various parameters number.
  304. *
  305. * @parameter flags addition conditions for running external programs.
  306. * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  307. * Shell (or command) will be found in pathes described in PATH variable
  308. * (if shell parameter doesn't begin from path delimiter)
  309. * @parameter ... Command for shell with addition parameters for shell
  310. * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
  311. * Should be NULL terminated.
  312. * @return 0 if successfull, -1 otherwise
  313. */
  314. int
  315. my_systeml (int flags, const char *shell, ...)
  316. {
  317. GPtrArray *args_array;
  318. int status = 0;
  319. va_list vargs;
  320. char *one_arg;
  321. args_array = g_ptr_array_new ();
  322. va_start (vargs, shell);
  323. while ((one_arg = va_arg (vargs, char *)) != NULL)
  324. g_ptr_array_add (args_array, one_arg);
  325. va_end (vargs);
  326. g_ptr_array_add (args_array, NULL);
  327. status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
  328. g_ptr_array_free (args_array, TRUE);
  329. return status;
  330. }
  331. /* --------------------------------------------------------------------------------------------- */
  332. /**
  333. * Call external programs with array of strings as parameters.
  334. *
  335. * @parameter command command to run. Command will be found in paths described in PATH variable
  336. * (if command parameter doesn't begin from path delimiter)
  337. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  338. * @return 0 if successfull, -1 otherwise
  339. */
  340. int
  341. my_systemv (const char *command, char *const argv[])
  342. {
  343. my_fork_state_t fork_state;
  344. int status = 0;
  345. my_system_sigactions_t sigactions;
  346. my_system__save_sigaction_handlers (&sigactions);
  347. fork_state = my_fork ();
  348. switch (fork_state)
  349. {
  350. case FORK_ERROR:
  351. status = -1;
  352. break;
  353. case FORK_CHILD:
  354. {
  355. signal (SIGINT, SIG_DFL);
  356. signal (SIGQUIT, SIG_DFL);
  357. signal (SIGTSTP, SIG_DFL);
  358. signal (SIGCHLD, SIG_DFL);
  359. execvp (command, argv);
  360. my_exit (127); /* Exec error */
  361. }
  362. MC_FALLTHROUGH;
  363. /* no break here, or unreachable-code warning by no returning my_exit() */
  364. default:
  365. status = 0;
  366. break;
  367. }
  368. my_system__restore_sigaction_handlers (&sigactions);
  369. return status;
  370. }
  371. /* --------------------------------------------------------------------------------------------- */
  372. /**
  373. * Call external programs with flags and with array of strings as parameters.
  374. *
  375. * @parameter flags addition conditions for running external programs.
  376. * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  377. * Shell (or command) will be found in paths described in PATH variable
  378. * (if shell parameter doesn't begin from path delimiter)
  379. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  380. * @return 0 if successfull, -1 otherwise
  381. */
  382. int
  383. my_systemv_flags (int flags, const char *command, char *const argv[])
  384. {
  385. char *execute_name = NULL;
  386. GPtrArray *args_array;
  387. int status = 0;
  388. args_array = my_system_make_arg_array (flags, command, &execute_name);
  389. for (; argv != NULL && *argv != NULL; argv++)
  390. g_ptr_array_add (args_array, *argv);
  391. g_ptr_array_add (args_array, NULL);
  392. status = my_systemv (execute_name, (char *const *) args_array->pdata);
  393. g_free (execute_name);
  394. g_ptr_array_free (args_array, TRUE);
  395. return status;
  396. }
  397. /* --------------------------------------------------------------------------------------------- */
  398. /**
  399. * Create pipe and run child process.
  400. *
  401. * @parameter command command line of child process
  402. * @parameter read_out do or don't read the stdout of child process
  403. * @parameter read_err do or don't read the stderr of child process
  404. * @paremeter error contains pointer to object to handle error code and message
  405. *
  406. * @return newly created object of mc_pipe_t class in success, NULL otherwise
  407. */
  408. mc_pipe_t *
  409. mc_popen (const char *command, gboolean read_out, gboolean read_err, GError ** error)
  410. {
  411. mc_pipe_t *p;
  412. const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
  413. p = g_try_new (mc_pipe_t, 1);
  414. if (p == NULL)
  415. {
  416. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
  417. _("Cannot create pipe descriptor"));
  418. goto ret_err;
  419. }
  420. p->out.fd = -1;
  421. p->err.fd = -1;
  422. if (!g_spawn_async_with_pipes
  423. (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
  424. NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL, read_err ? &p->err.fd : NULL,
  425. error))
  426. {
  427. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
  428. _("Cannot create pipe streams"));
  429. goto ret_err;
  430. }
  431. p->out.buf[0] = '\0';
  432. p->out.len = MC_PIPE_BUFSIZE;
  433. p->out.null_term = FALSE;
  434. p->err.buf[0] = '\0';
  435. p->err.len = MC_PIPE_BUFSIZE;
  436. p->err.null_term = FALSE;
  437. return p;
  438. ret_err:
  439. g_free (p);
  440. return NULL;
  441. }
  442. /* --------------------------------------------------------------------------------------------- */
  443. /**
  444. * Read stdout and stderr of pipe asynchronously.
  445. *
  446. * @parameter p pipe descriptor
  447. *
  448. * The lengths of read data contain in p->out.len and p->err.len.
  449. *
  450. * Before read, p->xxx.len is an input. It defines the number of data to read.
  451. * Should not be greater than MC_PIPE_BUFSIZE.
  452. *
  453. * After read, p->xxx.len is an output and contains the following:
  454. * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
  455. * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
  456. * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
  457. * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
  458. *
  459. * @paremeter error contains pointer to object to handle error code and message
  460. */
  461. void
  462. mc_pread (mc_pipe_t * p, GError ** error)
  463. {
  464. gboolean read_out, read_err;
  465. fd_set fds;
  466. int maxfd = 0;
  467. int res;
  468. if (error != NULL)
  469. *error = NULL;
  470. read_out = p->out.fd >= 0;
  471. read_err = p->err.fd >= 0;
  472. if (!read_out && !read_err)
  473. {
  474. p->out.len = MC_PIPE_STREAM_UNREAD;
  475. p->err.len = MC_PIPE_STREAM_UNREAD;
  476. return;
  477. }
  478. FD_ZERO (&fds);
  479. if (read_out)
  480. {
  481. FD_SET (p->out.fd, &fds);
  482. maxfd = p->out.fd;
  483. }
  484. if (read_err)
  485. {
  486. FD_SET (p->err.fd, &fds);
  487. maxfd = MAX (maxfd, p->err.fd);
  488. }
  489. /* no timeout */
  490. res = select (maxfd + 1, &fds, NULL, NULL, NULL);
  491. if (res < 0 && errno != EINTR)
  492. {
  493. mc_propagate_error (error, MC_PIPE_ERROR_READ,
  494. _
  495. ("Unexpected error in select() reading data from a child process:\n%s"),
  496. unix_error_string (errno));
  497. return;
  498. }
  499. if (read_out)
  500. mc_pread_stream (&p->out, &fds);
  501. else
  502. p->out.len = MC_PIPE_STREAM_UNREAD;
  503. if (read_err)
  504. mc_pread_stream (&p->err, &fds);
  505. else
  506. p->err.len = MC_PIPE_STREAM_UNREAD;
  507. }
  508. /* --------------------------------------------------------------------------------------------- */
  509. /**
  510. * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
  511. * it is appended to the line.
  512. *
  513. * @stream mc_pipe_stream_t object
  514. *
  515. * @return newly created GString or NULL in case of EOL;
  516. */
  517. GString *
  518. mc_pstream_get_string (mc_pipe_stream_t * ps)
  519. {
  520. char *s;
  521. size_t size, i;
  522. gboolean escape = FALSE;
  523. g_return_val_if_fail (ps != NULL, NULL);
  524. if (ps->len < 0)
  525. return NULL;
  526. size = ps->len - ps->pos;
  527. if (size == 0)
  528. return NULL;
  529. s = ps->buf + ps->pos;
  530. if (s[0] == '\0')
  531. return NULL;
  532. /* find '\0' or unescaped '\n' */
  533. for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
  534. escape = s[i] == '\\' ? !escape : FALSE;
  535. if (i != size && s[i] == '\n')
  536. i++;
  537. ps->pos += i;
  538. return g_string_new_len (s, i);
  539. }
  540. /* --------------------------------------------------------------------------------------------- */
  541. /**
  542. * Close pipe and destroy pipe descriptor.
  543. *
  544. * @paremeter p pipe descriptor
  545. * @paremeter error contains pointer to object to handle error code and message
  546. */
  547. void
  548. mc_pclose (mc_pipe_t * p, GError ** error)
  549. {
  550. int res;
  551. if (p->out.fd >= 0)
  552. res = close (p->out.fd);
  553. if (p->err.fd >= 0)
  554. res = close (p->err.fd);
  555. do
  556. {
  557. int status;
  558. res = waitpid (p->child_pid, &status, 0);
  559. }
  560. while (res < 0 && errno == EINTR);
  561. if (res < 0)
  562. mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
  563. unix_error_string (errno));
  564. g_free (p);
  565. }
  566. /* --------------------------------------------------------------------------------------------- */
  567. /**
  568. * Perform tilde expansion if possible.
  569. *
  570. * @param directory pointer to the path
  571. *
  572. * @return newly allocated string, even if it's unchanged.
  573. */
  574. char *
  575. tilde_expand (const char *directory)
  576. {
  577. struct passwd *passwd;
  578. const char *p, *q;
  579. if (*directory != '~')
  580. return g_strdup (directory);
  581. p = directory + 1;
  582. /* d = "~" or d = "~/" */
  583. if (*p == '\0' || IS_PATH_SEP (*p))
  584. {
  585. passwd = getpwuid (geteuid ());
  586. q = IS_PATH_SEP (*p) ? p + 1 : "";
  587. }
  588. else
  589. {
  590. q = strchr (p, PATH_SEP);
  591. if (q == NULL)
  592. passwd = getpwnam (p);
  593. else
  594. {
  595. char *name;
  596. name = g_strndup (p, q - p);
  597. passwd = getpwnam (name);
  598. q++;
  599. g_free (name);
  600. }
  601. }
  602. /* If we can't figure the user name, leave tilde unexpanded */
  603. if (passwd == NULL)
  604. return g_strdup (directory);
  605. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  606. }
  607. /* --------------------------------------------------------------------------------------------- */
  608. /**
  609. * Canonicalize path, and return a new path. Do everything in place.
  610. * The new path differs from path in:
  611. * Multiple '/'s are collapsed to a single '/'.
  612. * Leading './'s and trailing '/.'s are removed.
  613. * Trailing '/'s are removed.
  614. * Non-leading '../'s and trailing '..'s are handled by removing
  615. * portions of the path.
  616. * Well formed UNC paths are modified only in the local part.
  617. */
  618. void
  619. custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
  620. {
  621. char *p, *s;
  622. char *lpath = path; /* path without leading UNC part */
  623. const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
  624. /* Detect and preserve UNC paths: //server/... */
  625. if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
  626. {
  627. for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
  628. ;
  629. if (IS_PATH_SEP (p[0]) && p > path + 2)
  630. lpath = p;
  631. }
  632. if (lpath[0] == '\0' || lpath[1] == '\0')
  633. return;
  634. if ((flags & CANON_PATH_JOINSLASHES) != 0)
  635. {
  636. /* Collapse multiple slashes */
  637. for (p = lpath; *p != '\0'; p++)
  638. if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
  639. {
  640. s = p + 1;
  641. while (IS_PATH_SEP (*(++s)))
  642. ;
  643. str_move (p + 1, s);
  644. }
  645. /* Collapse "/./" -> "/" */
  646. for (p = lpath; *p != '\0';)
  647. if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
  648. str_move (p, p + 2);
  649. else
  650. p++;
  651. }
  652. if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
  653. {
  654. size_t len;
  655. /* Remove trailing slashes */
  656. for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
  657. {
  658. if (p >= lpath + url_delim_len - 1
  659. && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  660. break;
  661. *p = '\0';
  662. }
  663. /* Remove leading "./" */
  664. if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
  665. {
  666. if (lpath[2] == '\0')
  667. {
  668. lpath[1] = '\0';
  669. return;
  670. }
  671. str_move (lpath, lpath + 2);
  672. }
  673. /* Remove trailing "/" or "/." */
  674. len = strlen (lpath);
  675. if (len < 2)
  676. return;
  677. if (IS_PATH_SEP (lpath[len - 1])
  678. && (len < url_delim_len
  679. || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
  680. url_delim_len) != 0))
  681. lpath[len - 1] = '\0';
  682. else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
  683. {
  684. if (len == 2)
  685. {
  686. lpath[1] = '\0';
  687. return;
  688. }
  689. lpath[len - 2] = '\0';
  690. }
  691. }
  692. /* Collapse "/.." with the previous part of path */
  693. if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
  694. {
  695. #ifdef HAVE_CHARSET
  696. const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
  697. #endif /* HAVE_CHARSET */
  698. for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
  699. {
  700. if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
  701. || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
  702. {
  703. p++;
  704. continue;
  705. }
  706. /* search for the previous token */
  707. s = p - 1;
  708. if (s >= lpath + url_delim_len - 2
  709. && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  710. {
  711. s -= (url_delim_len - 2);
  712. while (s >= lpath && !IS_PATH_SEP (*s--))
  713. ;
  714. }
  715. while (s >= lpath)
  716. {
  717. if (s - url_delim_len > lpath
  718. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  719. {
  720. char *vfs_prefix = s - url_delim_len;
  721. vfs_class *vclass;
  722. while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
  723. ;
  724. if (IS_PATH_SEP (*vfs_prefix))
  725. vfs_prefix++;
  726. *(s - url_delim_len) = '\0';
  727. vclass = vfs_prefix_to_class (vfs_prefix);
  728. *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
  729. if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
  730. {
  731. s = vfs_prefix;
  732. continue;
  733. }
  734. }
  735. if (IS_PATH_SEP (*s))
  736. break;
  737. s--;
  738. }
  739. s++;
  740. /* If the previous token is "..", we cannot collapse it */
  741. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  742. {
  743. p += 3;
  744. continue;
  745. }
  746. if (p[3] != '\0')
  747. {
  748. if (s == lpath && IS_PATH_SEP (*s))
  749. {
  750. /* "/../foo" -> "/foo" */
  751. str_move (s + 1, p + 4);
  752. }
  753. else
  754. {
  755. /* "token/../foo" -> "foo" */
  756. #ifdef HAVE_CHARSET
  757. if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  758. && (is_supported_encoding (s + enc_prefix_len)))
  759. /* special case: remove encoding */
  760. str_move (s, p + 1);
  761. else
  762. #endif /* HAVE_CHARSET */
  763. str_move (s, p + 4);
  764. }
  765. p = s > lpath ? s - 1 : s;
  766. continue;
  767. }
  768. /* trailing ".." */
  769. if (s == lpath)
  770. {
  771. /* "token/.." -> "." */
  772. if (!IS_PATH_SEP (lpath[0]))
  773. lpath[0] = '.';
  774. lpath[1] = '\0';
  775. }
  776. else
  777. {
  778. /* "foo/token/.." -> "foo" */
  779. if (s == lpath + 1)
  780. s[0] = '\0';
  781. #ifdef HAVE_CHARSET
  782. else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  783. && (is_supported_encoding (s + enc_prefix_len)))
  784. {
  785. /* special case: remove encoding */
  786. s[0] = '.';
  787. s[1] = '.';
  788. s[2] = '\0';
  789. /* search for the previous token */
  790. /* IS_PATH_SEP (s[-1]) */
  791. for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
  792. ;
  793. if (p >= lpath)
  794. continue;
  795. }
  796. #endif /* HAVE_CHARSET */
  797. else
  798. {
  799. if (s >= lpath + url_delim_len
  800. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  801. *s = '\0';
  802. else
  803. s[-1] = '\0';
  804. }
  805. }
  806. break;
  807. }
  808. }
  809. }
  810. /* --------------------------------------------------------------------------------------------- */
  811. void
  812. canonicalize_pathname (char *path)
  813. {
  814. custom_canonicalize_pathname (path, CANON_PATH_ALL);
  815. }
  816. /* --------------------------------------------------------------------------------------------- */
  817. #ifdef HAVE_GET_PROCESS_STATS
  818. int
  819. gettimeofday (struct timeval *tp, void *tzp)
  820. {
  821. (void) tzp;
  822. return get_process_stats (tp, PS_SELF, 0, 0);
  823. }
  824. #endif /* HAVE_GET_PROCESS_STATS */
  825. /* --------------------------------------------------------------------------------------------- */
  826. char *
  827. mc_realpath (const char *path, char *resolved_path)
  828. {
  829. #ifdef HAVE_CHARSET
  830. const char *p = path;
  831. gboolean absolute_path = FALSE;
  832. if (IS_PATH_SEP (*p))
  833. {
  834. absolute_path = TRUE;
  835. p++;
  836. }
  837. /* ignore encoding: skip "#enc:" */
  838. if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
  839. {
  840. p += strlen (VFS_ENCODING_PREFIX);
  841. p = strchr (p, PATH_SEP);
  842. if (p != NULL)
  843. {
  844. if (!absolute_path && p[1] != '\0')
  845. p++;
  846. path = p;
  847. }
  848. }
  849. #endif /* HAVE_CHARSET */
  850. #ifdef HAVE_REALPATH
  851. return realpath (path, resolved_path);
  852. #else
  853. {
  854. char copy_path[PATH_MAX];
  855. char got_path[PATH_MAX];
  856. char *new_path = got_path;
  857. char *max_path;
  858. #ifdef S_IFLNK
  859. char link_path[PATH_MAX];
  860. int readlinks = 0;
  861. int n;
  862. #endif /* S_IFLNK */
  863. /* Make a copy of the source path since we may need to modify it. */
  864. if (strlen (path) >= PATH_MAX - 2)
  865. {
  866. errno = ENAMETOOLONG;
  867. return NULL;
  868. }
  869. strcpy (copy_path, path);
  870. path = copy_path;
  871. max_path = copy_path + PATH_MAX - 2;
  872. /* If it's a relative pathname use getwd for starters. */
  873. if (!IS_PATH_SEP (*path))
  874. {
  875. new_path = g_get_current_dir ();
  876. if (new_path == NULL)
  877. strcpy (got_path, "");
  878. else
  879. {
  880. g_snprintf (got_path, sizeof (got_path), "%s", new_path);
  881. g_free (new_path);
  882. new_path = got_path;
  883. }
  884. new_path += strlen (got_path);
  885. if (!IS_PATH_SEP (new_path[-1]))
  886. *new_path++ = PATH_SEP;
  887. }
  888. else
  889. {
  890. *new_path++ = PATH_SEP;
  891. path++;
  892. }
  893. /* Expand each slash-separated pathname component. */
  894. while (*path != '\0')
  895. {
  896. /* Ignore stray "/". */
  897. if (IS_PATH_SEP (*path))
  898. {
  899. path++;
  900. continue;
  901. }
  902. if (*path == '.')
  903. {
  904. /* Ignore ".". */
  905. if (path[1] == '\0' || IS_PATH_SEP (path[1]))
  906. {
  907. path++;
  908. continue;
  909. }
  910. if (path[1] == '.')
  911. {
  912. if (path[2] == '\0' || IS_PATH_SEP (path[2]))
  913. {
  914. path += 2;
  915. /* Ignore ".." at root. */
  916. if (new_path == got_path + 1)
  917. continue;
  918. /* Handle ".." by backing up. */
  919. while (!IS_PATH_SEP ((--new_path)[-1]))
  920. ;
  921. continue;
  922. }
  923. }
  924. }
  925. /* Safely copy the next pathname component. */
  926. while (*path != '\0' && !IS_PATH_SEP (*path))
  927. {
  928. if (path > max_path)
  929. {
  930. errno = ENAMETOOLONG;
  931. return NULL;
  932. }
  933. *new_path++ = *path++;
  934. }
  935. #ifdef S_IFLNK
  936. /* Protect against infinite loops. */
  937. if (readlinks++ > MAXSYMLINKS)
  938. {
  939. errno = ELOOP;
  940. return NULL;
  941. }
  942. /* See if latest pathname component is a symlink. */
  943. *new_path = '\0';
  944. n = readlink (got_path, link_path, PATH_MAX - 1);
  945. if (n < 0)
  946. {
  947. /* EINVAL means the file exists but isn't a symlink. */
  948. if (errno != EINVAL)
  949. {
  950. /* Make sure it's null terminated. */
  951. *new_path = '\0';
  952. strcpy (resolved_path, got_path);
  953. return NULL;
  954. }
  955. }
  956. else
  957. {
  958. /* Note: readlink doesn't add the null byte. */
  959. link_path[n] = '\0';
  960. if (IS_PATH_SEP (*link_path))
  961. /* Start over for an absolute symlink. */
  962. new_path = got_path;
  963. else
  964. /* Otherwise back up over this component. */
  965. while (!IS_PATH_SEP (*(--new_path)))
  966. ;
  967. /* Safe sex check. */
  968. if (strlen (path) + n >= PATH_MAX - 2)
  969. {
  970. errno = ENAMETOOLONG;
  971. return NULL;
  972. }
  973. /* Insert symlink contents into path. */
  974. strcat (link_path, path);
  975. strcpy (copy_path, link_path);
  976. path = copy_path;
  977. }
  978. #endif /* S_IFLNK */
  979. *new_path++ = PATH_SEP;
  980. }
  981. /* Delete trailing slash but don't whomp a lone slash. */
  982. if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
  983. new_path--;
  984. /* Make sure it's null terminated. */
  985. *new_path = '\0';
  986. strcpy (resolved_path, got_path);
  987. return resolved_path;
  988. }
  989. #endif /* HAVE_REALPATH */
  990. }
  991. /* --------------------------------------------------------------------------------------------- */
  992. /**
  993. * Return the index of the permissions triplet
  994. *
  995. */
  996. int
  997. get_user_permissions (struct stat *st)
  998. {
  999. static gboolean initialized = FALSE;
  1000. static gid_t *groups;
  1001. static int ngroups;
  1002. static uid_t uid;
  1003. int i;
  1004. if (!initialized)
  1005. {
  1006. uid = geteuid ();
  1007. ngroups = getgroups (0, NULL);
  1008. if (ngroups == -1)
  1009. ngroups = 0; /* ignore errors */
  1010. /* allocate space for one element in addition to what
  1011. * will be filled by getgroups(). */
  1012. groups = g_new (gid_t, ngroups + 1);
  1013. if (ngroups != 0)
  1014. {
  1015. ngroups = getgroups (ngroups, groups);
  1016. if (ngroups == -1)
  1017. ngroups = 0; /* ignore errors */
  1018. }
  1019. /* getgroups() may or may not return the effective group ID,
  1020. * so we always include it at the end of the list. */
  1021. groups[ngroups++] = getegid ();
  1022. initialized = TRUE;
  1023. }
  1024. if (st->st_uid == uid || uid == 0)
  1025. return 0;
  1026. for (i = 0; i < ngroups; i++)
  1027. if (st->st_gid == groups[i])
  1028. return 1;
  1029. return 2;
  1030. }
  1031. /* --------------------------------------------------------------------------------------------- */
  1032. /**
  1033. * Build filename from arguments.
  1034. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1035. */
  1036. char *
  1037. mc_build_filenamev (const char *first_element, va_list args)
  1038. {
  1039. gboolean absolute;
  1040. const char *element = first_element;
  1041. GString *path;
  1042. char *ret;
  1043. if (element == NULL)
  1044. return NULL;
  1045. path = g_string_new ("");
  1046. absolute = IS_PATH_SEP (*first_element);
  1047. do
  1048. {
  1049. if (*element == '\0')
  1050. element = va_arg (args, char *);
  1051. else
  1052. {
  1053. char *tmp_element;
  1054. size_t len;
  1055. const char *start;
  1056. tmp_element = g_strdup (element);
  1057. element = va_arg (args, char *);
  1058. canonicalize_pathname (tmp_element);
  1059. len = strlen (tmp_element);
  1060. start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
  1061. g_string_append (path, start);
  1062. if (!IS_PATH_SEP (tmp_element[len - 1]) && element != NULL)
  1063. g_string_append_c (path, PATH_SEP);
  1064. g_free (tmp_element);
  1065. }
  1066. }
  1067. while (element != NULL);
  1068. if (absolute)
  1069. g_string_prepend_c (path, PATH_SEP);
  1070. ret = g_string_free (path, FALSE);
  1071. canonicalize_pathname (ret);
  1072. return ret;
  1073. }
  1074. /* --------------------------------------------------------------------------------------------- */
  1075. /**
  1076. * Build filename from arguments.
  1077. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1078. */
  1079. char *
  1080. mc_build_filename (const char *first_element, ...)
  1081. {
  1082. va_list args;
  1083. char *ret;
  1084. if (first_element == NULL)
  1085. return NULL;
  1086. va_start (args, first_element);
  1087. ret = mc_build_filenamev (first_element, args);
  1088. va_end (args);
  1089. return ret;
  1090. }
  1091. /* --------------------------------------------------------------------------------------------- */