utilunix.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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. #ifdef HAVE_CHARSET
  857. last:
  858. #endif /* HAVE_CHARSET */
  859. if (s >= lpath + url_delim_len
  860. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  861. *s = '\0';
  862. else
  863. s[-1] = '\0';
  864. }
  865. }
  866. break;
  867. }
  868. }
  869. }
  870. /* --------------------------------------------------------------------------------------------- */
  871. char *
  872. mc_realpath (const char *path, char *resolved_path)
  873. {
  874. #ifdef HAVE_CHARSET
  875. const char *p = path;
  876. gboolean absolute_path = FALSE;
  877. if (IS_PATH_SEP (*p))
  878. {
  879. absolute_path = TRUE;
  880. p++;
  881. }
  882. /* ignore encoding: skip "#enc:" */
  883. if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
  884. {
  885. p += strlen (VFS_ENCODING_PREFIX);
  886. p = strchr (p, PATH_SEP);
  887. if (p != NULL)
  888. {
  889. if (!absolute_path && p[1] != '\0')
  890. p++;
  891. path = p;
  892. }
  893. }
  894. #endif /* HAVE_CHARSET */
  895. #ifdef HAVE_REALPATH
  896. return realpath (path, resolved_path);
  897. #else
  898. {
  899. char copy_path[PATH_MAX];
  900. char got_path[PATH_MAX];
  901. char *new_path = got_path;
  902. char *max_path;
  903. #ifdef S_IFLNK
  904. char link_path[PATH_MAX];
  905. int readlinks = 0;
  906. int n;
  907. #endif /* S_IFLNK */
  908. /* Make a copy of the source path since we may need to modify it. */
  909. if (strlen (path) >= PATH_MAX - 2)
  910. {
  911. errno = ENAMETOOLONG;
  912. return NULL;
  913. }
  914. strcpy (copy_path, path);
  915. path = copy_path;
  916. max_path = copy_path + PATH_MAX - 2;
  917. /* If it's a relative pathname use getwd for starters. */
  918. if (!IS_PATH_SEP (*path))
  919. {
  920. new_path = my_get_current_dir ();
  921. if (new_path == NULL)
  922. strcpy (got_path, "");
  923. else
  924. {
  925. g_snprintf (got_path, sizeof (got_path), "%s", new_path);
  926. g_free (new_path);
  927. new_path = got_path;
  928. }
  929. new_path += strlen (got_path);
  930. if (!IS_PATH_SEP (new_path[-1]))
  931. *new_path++ = PATH_SEP;
  932. }
  933. else
  934. {
  935. *new_path++ = PATH_SEP;
  936. path++;
  937. }
  938. /* Expand each slash-separated pathname component. */
  939. while (*path != '\0')
  940. {
  941. /* Ignore stray "/". */
  942. if (IS_PATH_SEP (*path))
  943. {
  944. path++;
  945. continue;
  946. }
  947. if (*path == '.')
  948. {
  949. /* Ignore ".". */
  950. if (path[1] == '\0' || IS_PATH_SEP (path[1]))
  951. {
  952. path++;
  953. continue;
  954. }
  955. if (path[1] == '.')
  956. {
  957. if (path[2] == '\0' || IS_PATH_SEP (path[2]))
  958. {
  959. path += 2;
  960. /* Ignore ".." at root. */
  961. if (new_path == got_path + 1)
  962. continue;
  963. /* Handle ".." by backing up. */
  964. while (!IS_PATH_SEP ((--new_path)[-1]))
  965. ;
  966. continue;
  967. }
  968. }
  969. }
  970. /* Safely copy the next pathname component. */
  971. while (*path != '\0' && !IS_PATH_SEP (*path))
  972. {
  973. if (path > max_path)
  974. {
  975. errno = ENAMETOOLONG;
  976. return NULL;
  977. }
  978. *new_path++ = *path++;
  979. }
  980. #ifdef S_IFLNK
  981. /* Protect against infinite loops. */
  982. if (readlinks++ > MAXSYMLINKS)
  983. {
  984. errno = ELOOP;
  985. return NULL;
  986. }
  987. /* See if latest pathname component is a symlink. */
  988. *new_path = '\0';
  989. n = readlink (got_path, link_path, PATH_MAX - 1);
  990. if (n < 0)
  991. {
  992. /* EINVAL means the file exists but isn't a symlink. */
  993. if (errno != EINVAL)
  994. {
  995. /* Make sure it's null terminated. */
  996. *new_path = '\0';
  997. strcpy (resolved_path, got_path);
  998. return NULL;
  999. }
  1000. }
  1001. else
  1002. {
  1003. /* Note: readlink doesn't add the null byte. */
  1004. link_path[n] = '\0';
  1005. if (IS_PATH_SEP (*link_path))
  1006. /* Start over for an absolute symlink. */
  1007. new_path = got_path;
  1008. else
  1009. /* Otherwise back up over this component. */
  1010. while (!IS_PATH_SEP (*(--new_path)))
  1011. ;
  1012. /* Safe sex check. */
  1013. if (strlen (path) + n >= PATH_MAX - 2)
  1014. {
  1015. errno = ENAMETOOLONG;
  1016. return NULL;
  1017. }
  1018. /* Insert symlink contents into path. */
  1019. strcat (link_path, path);
  1020. strcpy (copy_path, link_path);
  1021. path = copy_path;
  1022. }
  1023. #endif /* S_IFLNK */
  1024. *new_path++ = PATH_SEP;
  1025. }
  1026. /* Delete trailing slash but don't whomp a lone slash. */
  1027. if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
  1028. new_path--;
  1029. /* Make sure it's null terminated. */
  1030. *new_path = '\0';
  1031. strcpy (resolved_path, got_path);
  1032. return resolved_path;
  1033. }
  1034. #endif /* HAVE_REALPATH */
  1035. }
  1036. /* --------------------------------------------------------------------------------------------- */
  1037. /**
  1038. * Return the index of the permissions triplet
  1039. *
  1040. */
  1041. int
  1042. get_user_permissions (struct stat *st)
  1043. {
  1044. static gboolean initialized = FALSE;
  1045. static gid_t *groups;
  1046. static int ngroups;
  1047. static uid_t uid;
  1048. int i;
  1049. if (!initialized)
  1050. {
  1051. uid = geteuid ();
  1052. ngroups = getgroups (0, NULL);
  1053. if (ngroups == -1)
  1054. ngroups = 0; /* ignore errors */
  1055. /* allocate space for one element in addition to what
  1056. * will be filled by getgroups(). */
  1057. groups = g_new (gid_t, ngroups + 1);
  1058. if (ngroups != 0)
  1059. {
  1060. ngroups = getgroups (ngroups, groups);
  1061. if (ngroups == -1)
  1062. ngroups = 0; /* ignore errors */
  1063. }
  1064. /* getgroups() may or may not return the effective group ID,
  1065. * so we always include it at the end of the list. */
  1066. groups[ngroups++] = getegid ();
  1067. initialized = TRUE;
  1068. }
  1069. if (st->st_uid == uid || uid == 0)
  1070. return 0;
  1071. for (i = 0; i < ngroups; i++)
  1072. if (st->st_gid == groups[i])
  1073. return 1;
  1074. return 2;
  1075. }
  1076. /* --------------------------------------------------------------------------------------------- */
  1077. /**
  1078. * Build filename from arguments.
  1079. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1080. */
  1081. char *
  1082. mc_build_filenamev (const char *first_element, va_list args)
  1083. {
  1084. gboolean absolute;
  1085. const char *element = first_element;
  1086. GString *path;
  1087. char *ret;
  1088. if (first_element == NULL)
  1089. return NULL;
  1090. absolute = IS_PATH_SEP (*first_element);
  1091. path = g_string_new (absolute ? PATH_SEP_STR : "");
  1092. do
  1093. {
  1094. if (*element == '\0')
  1095. element = va_arg (args, char *);
  1096. else
  1097. {
  1098. char *tmp_element;
  1099. const char *start;
  1100. tmp_element = g_strdup (element);
  1101. element = va_arg (args, char *);
  1102. canonicalize_pathname (tmp_element);
  1103. start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
  1104. g_string_append (path, start);
  1105. if (!IS_PATH_SEP (path->str[path->len - 1]) && element != NULL)
  1106. g_string_append_c (path, PATH_SEP);
  1107. g_free (tmp_element);
  1108. }
  1109. }
  1110. while (element != NULL);
  1111. ret = g_string_free (path, FALSE);
  1112. canonicalize_pathname (ret);
  1113. return ret;
  1114. }
  1115. /* --------------------------------------------------------------------------------------------- */
  1116. /**
  1117. * Build filename from arguments.
  1118. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1119. */
  1120. char *
  1121. mc_build_filename (const char *first_element, ...)
  1122. {
  1123. va_list args;
  1124. char *ret;
  1125. if (first_element == NULL)
  1126. return NULL;
  1127. va_start (args, first_element);
  1128. ret = mc_build_filenamev (first_element, args);
  1129. va_end (args);
  1130. return ret;
  1131. }
  1132. /* --------------------------------------------------------------------------------------------- */