utilunix.c 37 KB

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