utilunix.c 38 KB

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