utilunix.c 31 KB

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