util.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. /*
  2. Various utilities
  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. Slava Zanko <slavazanko@gmail.com>, 2013
  12. This file is part of the Midnight Commander.
  13. The Midnight Commander is free software: you can redistribute it
  14. and/or modify it under the terms of the GNU General Public License as
  15. published by the Free Software Foundation, either version 3 of the License,
  16. or (at your option) any later version.
  17. The Midnight Commander is distributed in the hope that it will be useful,
  18. but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. GNU General Public License for more details.
  21. You should have received a copy of the GNU General Public License
  22. along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. /** \file lib/util.c
  25. * \brief Source: various utilities
  26. */
  27. #include <config.h>
  28. #include <ctype.h>
  29. #include <stddef.h> /* ptrdiff_t */
  30. #include <limits.h>
  31. #include <stdarg.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <sys/types.h>
  36. #include <sys/stat.h>
  37. #include <unistd.h>
  38. #include "lib/global.h"
  39. #include "lib/mcconfig.h"
  40. #include "lib/fileloc.h"
  41. #include "lib/vfs/vfs.h"
  42. #include "lib/strutil.h"
  43. #include "lib/util.h"
  44. /*** global variables ****************************************************************************/
  45. /*** file scope macro definitions ****************************************************************/
  46. #define ismode(n,m) ((n & m) == m)
  47. /* Number of attempts to create a temporary file */
  48. #ifndef TMP_MAX
  49. #define TMP_MAX 16384
  50. #endif /* !TMP_MAX */
  51. #define TMP_SUFFIX ".tmp"
  52. #define ASCII_A (0x40 + 1)
  53. #define ASCII_Z (0x40 + 26)
  54. #define ASCII_a (0x60 + 1)
  55. #define ASCII_z (0x60 + 26)
  56. /*** file scope type declarations ****************************************************************/
  57. /*** forward declarations (file scope functions) *************************************************/
  58. /*** file scope variables ************************************************************************/
  59. /* --------------------------------------------------------------------------------------------- */
  60. /*** file scope functions ************************************************************************/
  61. /* --------------------------------------------------------------------------------------------- */
  62. #ifndef HAVE_CHARSET
  63. static inline int
  64. is_7bit_printable (unsigned char c)
  65. {
  66. return (c > 31 && c < 127);
  67. }
  68. #endif
  69. /* --------------------------------------------------------------------------------------------- */
  70. static inline int
  71. is_iso_printable (unsigned char c)
  72. {
  73. return ((c > 31 && c < 127) || c >= 160);
  74. }
  75. /* --------------------------------------------------------------------------------------------- */
  76. static inline int
  77. is_8bit_printable (unsigned char c)
  78. {
  79. /* "Full 8 bits output" doesn't work on xterm */
  80. if (mc_global.tty.xterm_flag)
  81. return is_iso_printable (c);
  82. return (c > 31 && c != 127 && c != 155);
  83. }
  84. /* --------------------------------------------------------------------------------------------- */
  85. static char *
  86. resolve_symlinks (const vfs_path_t *vpath)
  87. {
  88. char *p, *p2;
  89. char *buf, *buf2, *q, *r, c;
  90. struct stat mybuf;
  91. if (vpath->relative)
  92. return NULL;
  93. p = p2 = g_strdup (vfs_path_as_str (vpath));
  94. r = buf = g_malloc (MC_MAXPATHLEN);
  95. buf2 = g_malloc (MC_MAXPATHLEN);
  96. *r++ = PATH_SEP;
  97. *r = '\0';
  98. do
  99. {
  100. q = strchr (p + 1, PATH_SEP);
  101. if (q == NULL)
  102. {
  103. q = strchr (p + 1, '\0');
  104. if (q == p + 1)
  105. break;
  106. }
  107. c = *q;
  108. *q = '\0';
  109. if (mc_lstat (vpath, &mybuf) < 0)
  110. {
  111. MC_PTR_FREE (buf);
  112. goto ret;
  113. }
  114. if (!S_ISLNK (mybuf.st_mode))
  115. strcpy (r, p + 1);
  116. else
  117. {
  118. int len;
  119. len = mc_readlink (vpath, buf2, MC_MAXPATHLEN - 1);
  120. if (len < 0)
  121. {
  122. MC_PTR_FREE (buf);
  123. goto ret;
  124. }
  125. buf2[len] = '\0';
  126. if (IS_PATH_SEP (*buf2))
  127. strcpy (buf, buf2);
  128. else
  129. strcpy (r, buf2);
  130. }
  131. canonicalize_pathname (buf);
  132. r = strchr (buf, '\0');
  133. if (*r == '\0' || !IS_PATH_SEP (r[-1]))
  134. /* FIXME: this condition is always true because r points to the EOL */
  135. {
  136. *r++ = PATH_SEP;
  137. *r = '\0';
  138. }
  139. *q = c;
  140. p = q;
  141. }
  142. while (c != '\0');
  143. if (*buf == '\0')
  144. strcpy (buf, PATH_SEP_STR);
  145. else if (IS_PATH_SEP (r[-1]) && r != buf + 1)
  146. r[-1] = '\0';
  147. ret:
  148. g_free (buf2);
  149. g_free (p2);
  150. return buf;
  151. }
  152. /* --------------------------------------------------------------------------------------------- */
  153. static gboolean
  154. mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
  155. {
  156. FILE *backup_fd;
  157. char *contents;
  158. gsize length;
  159. gboolean ret1 = TRUE;
  160. if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
  161. return FALSE;
  162. backup_fd = fopen (to_file_name, "w");
  163. if (backup_fd == NULL)
  164. {
  165. g_free (contents);
  166. return FALSE;
  167. }
  168. if (fwrite ((const void *) contents, 1, length, backup_fd) != length)
  169. ret1 = FALSE;
  170. {
  171. int ret2;
  172. /* cppcheck-suppress redundantAssignment */
  173. ret2 = fflush (backup_fd);
  174. /* cppcheck-suppress redundantAssignment */
  175. ret2 = fclose (backup_fd);
  176. (void) ret2;
  177. }
  178. g_free (contents);
  179. return ret1;
  180. }
  181. /* --------------------------------------------------------------------------------------------- */
  182. /*** public functions ****************************************************************************/
  183. /* --------------------------------------------------------------------------------------------- */
  184. int
  185. is_printable (int c)
  186. {
  187. c &= 0xff;
  188. #ifdef HAVE_CHARSET
  189. /* "Display bits" is ignored, since the user controls the output
  190. by setting the output codepage */
  191. return is_8bit_printable (c);
  192. #else
  193. if (!mc_global.eight_bit_clean)
  194. return is_7bit_printable (c);
  195. if (mc_global.full_eight_bits)
  196. return is_8bit_printable (c);
  197. return is_iso_printable (c);
  198. #endif /* !HAVE_CHARSET */
  199. }
  200. /* --------------------------------------------------------------------------------------------- */
  201. /**
  202. * Quote the filename for the purpose of inserting it into the command
  203. * line. If quote_percent is TRUE, replace "%" with "%%" - the percent is
  204. * processed by the mc command line.
  205. */
  206. char *
  207. name_quote (const char *s, gboolean quote_percent)
  208. {
  209. GString *ret;
  210. if (s == NULL || *s == '\0')
  211. return NULL;
  212. ret = g_string_sized_new (64);
  213. if (*s == '-')
  214. g_string_append (ret, "." PATH_SEP_STR);
  215. for (; *s != '\0'; s++)
  216. {
  217. switch (*s)
  218. {
  219. case '%':
  220. if (quote_percent)
  221. g_string_append_c (ret, '%');
  222. break;
  223. case '\'':
  224. case '\\':
  225. case '\r':
  226. case '\n':
  227. case '\t':
  228. case '"':
  229. case ';':
  230. case ' ':
  231. case '?':
  232. case '|':
  233. case '[':
  234. case ']':
  235. case '{':
  236. case '}':
  237. case '<':
  238. case '>':
  239. case '`':
  240. case '!':
  241. case '$':
  242. case '&':
  243. case '*':
  244. case '(':
  245. case ')':
  246. g_string_append_c (ret, '\\');
  247. break;
  248. case '~':
  249. case '#':
  250. if (ret->len == 0)
  251. g_string_append_c (ret, '\\');
  252. break;
  253. default:
  254. break;
  255. }
  256. g_string_append_c (ret, *s);
  257. }
  258. return g_string_free (ret, ret->len == 0);
  259. }
  260. /* --------------------------------------------------------------------------------------------- */
  261. char *
  262. fake_name_quote (const char *s, gboolean quote_percent)
  263. {
  264. (void) quote_percent;
  265. return (s == NULL || *s == '\0' ? NULL : g_strdup (s));
  266. }
  267. /* --------------------------------------------------------------------------------------------- */
  268. /**
  269. * path_trunc() is the same as str_trunc() but
  270. * it deletes possible password from path for security
  271. * reasons.
  272. */
  273. const char *
  274. path_trunc (const char *path, size_t trunc_len)
  275. {
  276. vfs_path_t *vpath;
  277. const char *ret;
  278. vpath = vfs_path_from_str_flags (path, VPF_STRIP_PASSWORD);
  279. ret = str_trunc (vfs_path_as_str (vpath), trunc_len);
  280. vfs_path_free (vpath, TRUE);
  281. return ret;
  282. }
  283. /* --------------------------------------------------------------------------------------------- */
  284. const char *
  285. size_trunc (uintmax_t size, gboolean use_si)
  286. {
  287. static char x[BUF_TINY];
  288. uintmax_t divisor = 1;
  289. const char *xtra = _("B");
  290. if (size > 999999999UL)
  291. {
  292. divisor = use_si ? 1000 : 1024;
  293. xtra = use_si ? _("kB") : _("KiB");
  294. if (size / divisor > 999999999UL)
  295. {
  296. divisor = use_si ? (1000 * 1000) : (1024 * 1024);
  297. xtra = use_si ? _("MB") : _("MiB");
  298. if (size / divisor > 999999999UL)
  299. {
  300. divisor = use_si ? (1000 * 1000 * 1000) : (1024 * 1024 * 1024);
  301. xtra = use_si ? _("GB") : _("GiB");
  302. }
  303. }
  304. }
  305. g_snprintf (x, sizeof (x), "%.0f %s", 1.0 * size / divisor, xtra);
  306. return x;
  307. }
  308. /* --------------------------------------------------------------------------------------------- */
  309. const char *
  310. size_trunc_sep (uintmax_t size, gboolean use_si)
  311. {
  312. static char x[60];
  313. int count;
  314. const char *p, *y;
  315. char *d;
  316. p = y = size_trunc (size, use_si);
  317. p += strlen (p) - 1;
  318. d = x + sizeof (x) - 1;
  319. *d-- = '\0';
  320. /* @size format is "size unit", i.e. "[digits][space][letters]".
  321. Copy all characters after digits. */
  322. while (p >= y && !g_ascii_isdigit (*p))
  323. *d-- = *p--;
  324. for (count = 0; p >= y; count++)
  325. {
  326. if (count == 3)
  327. {
  328. *d-- = ',';
  329. count = 0;
  330. }
  331. *d-- = *p--;
  332. }
  333. d++;
  334. if (*d == ',')
  335. d++;
  336. return d;
  337. }
  338. /* --------------------------------------------------------------------------------------------- */
  339. /**
  340. * Print file SIZE to BUFFER, but don't exceed LEN characters,
  341. * not including trailing 0. BUFFER should be at least LEN+1 long.
  342. * This function is called for every file on panels, so avoid
  343. * floating point by any means.
  344. *
  345. * Units: size units (filesystem sizes are 1K blocks)
  346. * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
  347. */
  348. void
  349. size_trunc_len (char *buffer, unsigned int len, uintmax_t size, int units, gboolean use_si)
  350. {
  351. /* Avoid taking power for every file. */
  352. /* *INDENT-OFF* */
  353. static const uintmax_t power10[] = {
  354. /* we hope that size of uintmax_t is 4 bytes at least */
  355. 1ULL,
  356. 10ULL,
  357. 100ULL,
  358. 1000ULL,
  359. 10000ULL,
  360. 100000ULL,
  361. 1000000ULL,
  362. 10000000ULL,
  363. 100000000ULL,
  364. 1000000000ULL
  365. /* maximum value of uintmax_t (in case of 4 bytes) is
  366. 4294967295
  367. */
  368. #if SIZEOF_UINTMAX_T == 8
  369. ,
  370. 10000000000ULL,
  371. 100000000000ULL,
  372. 1000000000000ULL,
  373. 10000000000000ULL,
  374. 100000000000000ULL,
  375. 1000000000000000ULL,
  376. 10000000000000000ULL,
  377. 100000000000000000ULL,
  378. 1000000000000000000ULL,
  379. 10000000000000000000ULL
  380. /* maximum value of uintmax_t (in case of 8 bytes) is
  381. 18447644073710439615
  382. */
  383. #endif
  384. };
  385. static const char *const suffix[] =
  386. { "", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q", NULL };
  387. static const char *const suffix_lc[] =
  388. { "", "k", "m", "g", "t", "p", "e", "z", "y", "r", "q", NULL };
  389. /* *INDENT-ON* */
  390. const char *const *sfx = use_si ? suffix_lc : suffix;
  391. int j = 0;
  392. if (len == 0)
  393. len = 9;
  394. #if SIZEOF_UINTMAX_T == 8
  395. /* 20 decimal digits are required to represent 8 bytes */
  396. else if (len > 19)
  397. len = 19;
  398. #else
  399. /* 10 decimal digits are required to represent 4 bytes */
  400. else if (len > 9)
  401. len = 9;
  402. #endif
  403. /*
  404. * recalculate from 1024 base to 1000 base if units>0
  405. * We can't just multiply by 1024 - that might cause overflow
  406. * if uintmax_t type is too small
  407. */
  408. if (use_si)
  409. for (j = 0; j < units; j++)
  410. {
  411. uintmax_t size_remain;
  412. size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
  413. size /= 125; /* 128/125 = 1024/1000 */
  414. size *= 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
  415. size += size_remain; /* Re-add remainder lost by division/multiplication */
  416. }
  417. for (j = units; sfx[j] != NULL; j++)
  418. {
  419. if (size == 0)
  420. {
  421. if (j == units)
  422. {
  423. /* Empty files will print "0" even with minimal width. */
  424. g_snprintf (buffer, len + 1, "%s", "0");
  425. }
  426. else
  427. {
  428. /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
  429. g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s", (j > 1) ? sfx[j - 1] : "B");
  430. }
  431. break;
  432. }
  433. if (size < power10[len - (j > 0 ? 1 : 0)])
  434. {
  435. g_snprintf (buffer, len + 1, "%" PRIuMAX "%s", size, sfx[j]);
  436. break;
  437. }
  438. /* Powers of 1000 or 1024, with rounding. */
  439. if (use_si)
  440. size = (size + 500) / 1000;
  441. else
  442. size = (size + 512) >> 10;
  443. }
  444. }
  445. /* --------------------------------------------------------------------------------------------- */
  446. const char *
  447. string_perm (mode_t mode_bits)
  448. {
  449. static char mode[11];
  450. strcpy (mode, "----------");
  451. if (S_ISDIR (mode_bits))
  452. mode[0] = 'd';
  453. if (S_ISCHR (mode_bits))
  454. mode[0] = 'c';
  455. if (S_ISBLK (mode_bits))
  456. mode[0] = 'b';
  457. if (S_ISLNK (mode_bits))
  458. mode[0] = 'l';
  459. if (S_ISFIFO (mode_bits))
  460. mode[0] = 'p';
  461. if (S_ISNAM (mode_bits))
  462. mode[0] = 'n';
  463. if (S_ISSOCK (mode_bits))
  464. mode[0] = 's';
  465. if (S_ISDOOR (mode_bits))
  466. mode[0] = 'D';
  467. if (ismode (mode_bits, S_IXOTH))
  468. mode[9] = 'x';
  469. if (ismode (mode_bits, S_IWOTH))
  470. mode[8] = 'w';
  471. if (ismode (mode_bits, S_IROTH))
  472. mode[7] = 'r';
  473. if (ismode (mode_bits, S_IXGRP))
  474. mode[6] = 'x';
  475. if (ismode (mode_bits, S_IWGRP))
  476. mode[5] = 'w';
  477. if (ismode (mode_bits, S_IRGRP))
  478. mode[4] = 'r';
  479. if (ismode (mode_bits, S_IXUSR))
  480. mode[3] = 'x';
  481. if (ismode (mode_bits, S_IWUSR))
  482. mode[2] = 'w';
  483. if (ismode (mode_bits, S_IRUSR))
  484. mode[1] = 'r';
  485. #ifdef S_ISUID
  486. if (ismode (mode_bits, S_ISUID))
  487. mode[3] = (mode[3] == 'x') ? 's' : 'S';
  488. #endif /* S_ISUID */
  489. #ifdef S_ISGID
  490. if (ismode (mode_bits, S_ISGID))
  491. mode[6] = (mode[6] == 'x') ? 's' : 'S';
  492. #endif /* S_ISGID */
  493. #ifdef S_ISVTX
  494. if (ismode (mode_bits, S_ISVTX))
  495. mode[9] = (mode[9] == 'x') ? 't' : 'T';
  496. #endif /* S_ISVTX */
  497. return mode;
  498. }
  499. /* --------------------------------------------------------------------------------------------- */
  500. const char *
  501. extension (const char *filename)
  502. {
  503. const char *d;
  504. d = strrchr (filename, '.');
  505. return d != NULL ? d + 1 : "";
  506. }
  507. /* --------------------------------------------------------------------------------------------- */
  508. char *
  509. load_mc_home_file (const char *from, const char *filename, char **allocated_filename,
  510. size_t *length)
  511. {
  512. char *hintfile_base, *hintfile;
  513. char *lang;
  514. char *data;
  515. hintfile_base = g_build_filename (from, filename, (char *) NULL);
  516. lang = guess_message_value ();
  517. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  518. if (!g_file_get_contents (hintfile, &data, length, NULL))
  519. {
  520. /* Fall back to the two-letter language code */
  521. if (lang[0] != '\0' && lang[1] != '\0')
  522. lang[2] = '\0';
  523. g_free (hintfile);
  524. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  525. if (!g_file_get_contents (hintfile, &data, length, NULL))
  526. {
  527. g_free (hintfile);
  528. hintfile = hintfile_base;
  529. g_file_get_contents (hintfile_base, &data, length, NULL);
  530. }
  531. }
  532. g_free (lang);
  533. if (hintfile != hintfile_base)
  534. g_free (hintfile_base);
  535. if (allocated_filename != NULL)
  536. *allocated_filename = hintfile;
  537. else
  538. g_free (hintfile);
  539. return data;
  540. }
  541. /* --------------------------------------------------------------------------------------------- */
  542. const char *
  543. extract_line (const char *s, const char *top, size_t *len)
  544. {
  545. static char tmp_line[BUF_MEDIUM];
  546. char *t = tmp_line;
  547. while (*s != '\0' && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
  548. *t++ = *s++;
  549. *t = '\0';
  550. if (len != NULL)
  551. *len = (size_t) (t - tmp_line);
  552. return tmp_line;
  553. }
  554. /* --------------------------------------------------------------------------------------------- */
  555. /**
  556. * The basename routine
  557. */
  558. const char *
  559. x_basename (const char *s)
  560. {
  561. const char *url_delim, *path_sep;
  562. url_delim = g_strrstr (s, VFS_PATH_URL_DELIMITER);
  563. path_sep = strrchr (s, PATH_SEP);
  564. if (path_sep == NULL)
  565. return s;
  566. if (url_delim == NULL
  567. || url_delim < path_sep - strlen (VFS_PATH_URL_DELIMITER)
  568. || url_delim - s + strlen (VFS_PATH_URL_DELIMITER) < strlen (s))
  569. {
  570. /* avoid trailing PATH_SEP, if present */
  571. if (!IS_PATH_SEP (s[strlen (s) - 1]))
  572. return path_sep + 1;
  573. while (--path_sep > s && !IS_PATH_SEP (*path_sep))
  574. ;
  575. return (path_sep != s) ? path_sep + 1 : s;
  576. }
  577. while (--url_delim > s && !IS_PATH_SEP (*url_delim))
  578. ;
  579. while (--url_delim > s && !IS_PATH_SEP (*url_delim))
  580. ;
  581. return url_delim == s ? s : url_delim + 1;
  582. }
  583. /* --------------------------------------------------------------------------------------------- */
  584. const char *
  585. unix_error_string (int error_num)
  586. {
  587. static char buffer[BUF_LARGE];
  588. gchar *strerror_currentlocale;
  589. strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
  590. g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
  591. g_free (strerror_currentlocale);
  592. return buffer;
  593. }
  594. /* --------------------------------------------------------------------------------------------- */
  595. const char *
  596. skip_separators (const char *s)
  597. {
  598. const char *su = s;
  599. for (; *su != '\0'; str_cnext_char (&su))
  600. if (!whitespace (*su) && *su != ',')
  601. break;
  602. return su;
  603. }
  604. /* --------------------------------------------------------------------------------------------- */
  605. const char *
  606. skip_numbers (const char *s)
  607. {
  608. const char *su = s;
  609. for (; *su != '\0'; str_cnext_char (&su))
  610. if (!str_isdigit (su))
  611. break;
  612. return su;
  613. }
  614. /* --------------------------------------------------------------------------------------------- */
  615. /**
  616. * Remove all control sequences from the argument string. We define
  617. * "control sequence", in a sort of pidgin BNF, as follows:
  618. *
  619. * control-seq = Esc non-'['
  620. * | Esc '[' (parameter-byte)* (intermediate-byte)* final-byte
  621. * parameter-byte = [\x30-\x3F] # one of "0-9;:<=>?"
  622. * intermediate-byte = [\x20–\x2F] # one of " !\"#$%&'()*+,-./"
  623. * final-byte = [\x40-\x7e] # one of "@A–Z[\]^_`a–z{|}~"
  624. *
  625. * The 256-color and true-color escape sequences should allow either ';' or ':' inside as separator,
  626. * actually, ':' is the more correct according to ECMA-48.
  627. * Some terminal emulators (e.g. xterm, gnome-terminal) support this.
  628. *
  629. * Non-printable characters are also removed.
  630. */
  631. char *
  632. strip_ctrl_codes (char *s)
  633. {
  634. char *w; /* Current position where the stripped data is written */
  635. char *r; /* Current position where the original data is read */
  636. if (s == NULL)
  637. return NULL;
  638. for (w = s, r = s; *r != '\0';)
  639. {
  640. if (*r == ESC_CHAR)
  641. {
  642. /* Skip the control sequence's arguments */ ;
  643. /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
  644. if (*(++r) == '[' || *r == '(')
  645. {
  646. /* strchr() matches trailing binary 0 */
  647. while (*(++r) != '\0' && strchr ("0123456789;:<=>?", *r) != NULL)
  648. ;
  649. while (*r != '\0' && (*r < 0x40 || *r > 0x7E))
  650. ++r;
  651. }
  652. else if (*r == ']')
  653. {
  654. /*
  655. * Skip xterm's OSC (Operating System Command)
  656. * http://www.xfree86.org/current/ctlseqs.html
  657. * OSC P s ; P t ST
  658. * OSC P s ; P t BEL
  659. */
  660. char *new_r;
  661. for (new_r = r; *new_r != '\0'; new_r++)
  662. {
  663. switch (*new_r)
  664. {
  665. /* BEL */
  666. case '\a':
  667. r = new_r;
  668. goto osc_out;
  669. case ESC_CHAR:
  670. /* ST */
  671. if (new_r[1] == '\\')
  672. {
  673. r = new_r + 1;
  674. goto osc_out;
  675. }
  676. break;
  677. default:
  678. break;
  679. }
  680. }
  681. osc_out:
  682. ;
  683. }
  684. /*
  685. * Now we are at the last character of the sequence.
  686. * Skip it unless it's binary 0.
  687. */
  688. if (*r != '\0')
  689. r++;
  690. }
  691. else
  692. {
  693. char *n;
  694. n = str_get_next_char (r);
  695. if (str_isprint (r))
  696. {
  697. memmove (w, r, n - r);
  698. w += n - r;
  699. }
  700. r = n;
  701. }
  702. }
  703. *w = '\0';
  704. return s;
  705. }
  706. /* --------------------------------------------------------------------------------------------- */
  707. enum compression_type
  708. get_compression_type (int fd, const char *name)
  709. {
  710. unsigned char magic[16];
  711. size_t str_len;
  712. /* Read the magic signature */
  713. if (mc_read (fd, (char *) magic, 4) != 4)
  714. return COMPRESSION_NONE;
  715. /* GZIP_MAGIC and OLD_GZIP_MAGIC */
  716. if (magic[0] == 0x1F && (magic[1] == 0x8B || magic[1] == 0x9E))
  717. return COMPRESSION_GZIP;
  718. /* PKZIP_MAGIC */
  719. if (magic[0] == 'P' && magic[1] == 'K' && magic[2] == 0x03 && magic[3] == 0x04)
  720. {
  721. /* Read compression type */
  722. mc_lseek (fd, 8, SEEK_SET);
  723. if (mc_read (fd, (char *) magic, 2) != 2)
  724. return COMPRESSION_NONE;
  725. if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
  726. return COMPRESSION_NONE;
  727. return COMPRESSION_ZIP;
  728. }
  729. /* PACK_MAGIC and LZH_MAGIC and compress magic */
  730. if (magic[0] == 0x1F && (magic[1] == 0x1E || magic[1] == 0xA0 || magic[1] == 0x9D))
  731. /* Compatible with gzip */
  732. return COMPRESSION_GZIP;
  733. /* BZIP and BZIP2 files */
  734. if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
  735. switch (magic[2])
  736. {
  737. case '0':
  738. return COMPRESSION_BZIP;
  739. case 'h':
  740. return COMPRESSION_BZIP2;
  741. default:
  742. break;
  743. }
  744. /* LZ4 format - v1.5.0 - 0x184D2204 (little endian) */
  745. if (magic[0] == 0x04 && magic[1] == 0x22 && magic[2] == 0x4d && magic[3] == 0x18)
  746. return COMPRESSION_LZ4;
  747. if (mc_read (fd, (char *) magic + 4, 2) != 2)
  748. return COMPRESSION_NONE;
  749. /* LZIP files */
  750. if (magic[0] == 'L'
  751. && magic[1] == 'Z'
  752. && magic[2] == 'I' && magic[3] == 'P' && (magic[4] == 0x00 || magic[4] == 0x01))
  753. return COMPRESSION_LZIP;
  754. /* Support for LZMA (only utils format with magic in header).
  755. * This is the default format of LZMA utils 4.32.1 and later. */
  756. if (magic[0] == 0xFF
  757. && magic[1] == 'L'
  758. && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
  759. return COMPRESSION_LZMA;
  760. /* LZO format - \x89\x4c\x5a\x4f\x00\x0d\x0a\x1a\x0a lzop compressed data */
  761. if (magic[0] == 0x89 && magic[1] == 0x4c &&
  762. magic[2] == 0x5a && magic[3] == 0x4f && magic[4] == 0x00 && magic[5] == 0x0d)
  763. return COMPRESSION_LZO;
  764. /* XZ compression magic */
  765. if (magic[0] == 0xFD
  766. && magic[1] == 0x37
  767. && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
  768. return COMPRESSION_XZ;
  769. if (magic[0] == 0x28 && magic[1] == 0xB5 && magic[2] == 0x2F && magic[3] == 0xFD)
  770. return COMPRESSION_ZSTD;
  771. str_len = strlen (name);
  772. /* HACK: we must believe to extension of LZMA file :) ... */
  773. if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
  774. (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
  775. return COMPRESSION_LZMA;
  776. return COMPRESSION_NONE;
  777. }
  778. /* --------------------------------------------------------------------------------------------- */
  779. const char *
  780. decompress_extension (int type)
  781. {
  782. switch (type)
  783. {
  784. case COMPRESSION_ZIP:
  785. return "/uz" VFS_PATH_URL_DELIMITER;
  786. case COMPRESSION_GZIP:
  787. return "/ugz" VFS_PATH_URL_DELIMITER;
  788. case COMPRESSION_BZIP:
  789. return "/ubz" VFS_PATH_URL_DELIMITER;
  790. case COMPRESSION_BZIP2:
  791. return "/ubz2" VFS_PATH_URL_DELIMITER;
  792. case COMPRESSION_LZIP:
  793. return "/ulz" VFS_PATH_URL_DELIMITER;
  794. case COMPRESSION_LZ4:
  795. return "/ulz4" VFS_PATH_URL_DELIMITER;
  796. case COMPRESSION_LZMA:
  797. return "/ulzma" VFS_PATH_URL_DELIMITER;
  798. case COMPRESSION_LZO:
  799. return "/ulzo" VFS_PATH_URL_DELIMITER;
  800. case COMPRESSION_XZ:
  801. return "/uxz" VFS_PATH_URL_DELIMITER;
  802. case COMPRESSION_ZSTD:
  803. return "/uzst" VFS_PATH_URL_DELIMITER;
  804. default:
  805. break;
  806. }
  807. /* Should never reach this place */
  808. fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
  809. return 0;
  810. }
  811. /* --------------------------------------------------------------------------------------------- */
  812. void
  813. wipe_password (char *passwd)
  814. {
  815. if (passwd != NULL)
  816. {
  817. char *p;
  818. for (p = passwd; *p != '\0'; p++)
  819. *p = '\0';
  820. g_free (passwd);
  821. }
  822. }
  823. /* --------------------------------------------------------------------------------------------- */
  824. /**
  825. * Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key
  826. *
  827. * @param p pointer to string
  828. *
  829. * @return newly allocated string
  830. */
  831. char *
  832. convert_controls (const char *p)
  833. {
  834. char *valcopy;
  835. char *q;
  836. valcopy = g_strdup (p);
  837. /* Parse the escape special character */
  838. for (q = valcopy; *p != '\0';)
  839. switch (*p)
  840. {
  841. case '\\':
  842. p++;
  843. if (*p == 'e' || *p == 'E')
  844. {
  845. p++;
  846. *q++ = ESC_CHAR;
  847. }
  848. break;
  849. case '^':
  850. p++;
  851. if (*p == '^')
  852. *q++ = *p++;
  853. else
  854. {
  855. char c;
  856. c = *p | 0x20;
  857. if (c >= 'a' && c <= 'z')
  858. {
  859. *q++ = c - 'a' + 1;
  860. p++;
  861. }
  862. else if (*p != '\0')
  863. p++;
  864. }
  865. break;
  866. default:
  867. *q++ = *p++;
  868. }
  869. *q = '\0';
  870. return valcopy;
  871. }
  872. /* --------------------------------------------------------------------------------------------- */
  873. /**
  874. * Finds out a relative path from first to second, i.e. goes as many ..
  875. * as needed up in first and then goes down using second
  876. */
  877. char *
  878. diff_two_paths (const vfs_path_t *vpath1, const vfs_path_t *vpath2)
  879. {
  880. int j, prevlen = -1, currlen;
  881. char *my_first = NULL, *my_second = NULL;
  882. char *buf = NULL;
  883. my_first = resolve_symlinks (vpath1);
  884. if (my_first == NULL)
  885. goto ret;
  886. my_second = resolve_symlinks (vpath2);
  887. if (my_second == NULL)
  888. goto ret;
  889. for (j = 0; j < 2; j++)
  890. {
  891. char *p, *q;
  892. int i;
  893. p = my_first;
  894. q = my_second;
  895. while (TRUE)
  896. {
  897. char *r, *s;
  898. ptrdiff_t len;
  899. r = strchr (p, PATH_SEP);
  900. if (r == NULL)
  901. break;
  902. s = strchr (q, PATH_SEP);
  903. if (s == NULL)
  904. break;
  905. len = r - p;
  906. if (len != (s - q) || strncmp (p, q, (size_t) len) != 0)
  907. break;
  908. p = r + 1;
  909. q = s + 1;
  910. }
  911. p--;
  912. for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++)
  913. ;
  914. currlen = (i + 1) * 3 + strlen (q) + 1;
  915. if (j != 0)
  916. {
  917. if (currlen < prevlen)
  918. g_free (buf);
  919. else
  920. goto ret;
  921. }
  922. p = buf = g_malloc (currlen);
  923. prevlen = currlen;
  924. for (; i >= 0; i--, p += 3)
  925. strcpy (p, "../");
  926. strcpy (p, q);
  927. }
  928. ret:
  929. g_free (my_first);
  930. g_free (my_second);
  931. return buf;
  932. }
  933. /* --------------------------------------------------------------------------------------------- */
  934. /**
  935. * Append text to GList, remove all entries with the same text
  936. */
  937. GList *
  938. list_append_unique (GList *list, char *text)
  939. {
  940. GList *lc_link;
  941. /*
  942. * Go to the last position and traverse the list backwards
  943. * starting from the second last entry to make sure that we
  944. * are not removing the current link.
  945. */
  946. list = g_list_append (list, text);
  947. list = g_list_last (list);
  948. lc_link = g_list_previous (list);
  949. while (lc_link != NULL)
  950. {
  951. GList *newlink;
  952. newlink = g_list_previous (lc_link);
  953. if (strcmp ((char *) lc_link->data, text) == 0)
  954. {
  955. GList *tmp;
  956. g_free (lc_link->data);
  957. tmp = g_list_remove_link (list, lc_link);
  958. (void) tmp;
  959. g_list_free_1 (lc_link);
  960. }
  961. lc_link = newlink;
  962. }
  963. return list;
  964. }
  965. /* --------------------------------------------------------------------------------------------- */
  966. /**
  967. * Read and restore position for the given filename.
  968. * If there is no stored data, return line 1 and col 0.
  969. */
  970. void
  971. load_file_position (const vfs_path_t *filename_vpath, long *line, long *column, off_t *offset,
  972. GArray **bookmarks)
  973. {
  974. char *fn;
  975. FILE *f;
  976. char buf[MC_MAXPATHLEN + 100];
  977. const size_t len = vfs_path_len (filename_vpath);
  978. /* defaults */
  979. *line = 1;
  980. *column = 0;
  981. *offset = 0;
  982. /* open file with positions */
  983. fn = mc_config_get_full_path (MC_FILEPOS_FILE);
  984. f = fopen (fn, "r");
  985. g_free (fn);
  986. if (f == NULL)
  987. return;
  988. /* prepare array for serialized bookmarks */
  989. if (bookmarks != NULL)
  990. *bookmarks = g_array_sized_new (FALSE, FALSE, sizeof (size_t), MAX_SAVED_BOOKMARKS);
  991. while (fgets (buf, sizeof (buf), f) != NULL)
  992. {
  993. const char *p;
  994. gchar **pos_tokens;
  995. /* check if the filename matches the beginning of string */
  996. if (strncmp (buf, vfs_path_as_str (filename_vpath), len) != 0)
  997. continue;
  998. /* followed by single space */
  999. if (buf[len] != ' ')
  1000. continue;
  1001. /* and string without spaces */
  1002. p = &buf[len + 1];
  1003. if (strchr (p, ' ') != NULL)
  1004. continue;
  1005. pos_tokens = g_strsplit (p, ";", 3 + MAX_SAVED_BOOKMARKS);
  1006. if (pos_tokens[0] == NULL)
  1007. {
  1008. *line = 1;
  1009. *column = 0;
  1010. *offset = 0;
  1011. }
  1012. else
  1013. {
  1014. *line = strtol (pos_tokens[0], NULL, 10);
  1015. if (pos_tokens[1] == NULL)
  1016. {
  1017. *column = 0;
  1018. *offset = 0;
  1019. }
  1020. else
  1021. {
  1022. *column = strtol (pos_tokens[1], NULL, 10);
  1023. if (pos_tokens[2] == NULL)
  1024. *offset = 0;
  1025. else if (bookmarks != NULL)
  1026. {
  1027. size_t i;
  1028. *offset = (off_t) g_ascii_strtoll (pos_tokens[2], NULL, 10);
  1029. for (i = 0; i < MAX_SAVED_BOOKMARKS && pos_tokens[3 + i] != NULL; i++)
  1030. {
  1031. size_t val;
  1032. val = strtoul (pos_tokens[3 + i], NULL, 10);
  1033. g_array_append_val (*bookmarks, val);
  1034. }
  1035. }
  1036. }
  1037. }
  1038. g_strfreev (pos_tokens);
  1039. }
  1040. fclose (f);
  1041. }
  1042. /* --------------------------------------------------------------------------------------------- */
  1043. /**
  1044. * Save position for the given file
  1045. */
  1046. void
  1047. save_file_position (const vfs_path_t *filename_vpath, long line, long column, off_t offset,
  1048. GArray *bookmarks)
  1049. {
  1050. static size_t filepos_max_saved_entries = 0;
  1051. char *fn, *tmp_fn;
  1052. FILE *f, *tmp_f;
  1053. char buf[MC_MAXPATHLEN + 100];
  1054. size_t i;
  1055. const size_t len = vfs_path_len (filename_vpath);
  1056. gboolean src_error = FALSE;
  1057. if (filepos_max_saved_entries == 0)
  1058. filepos_max_saved_entries = mc_config_get_int (mc_global.main_config, CONFIG_APP_SECTION,
  1059. "filepos_max_saved_entries", 1024);
  1060. fn = mc_config_get_full_path (MC_FILEPOS_FILE);
  1061. if (fn == NULL)
  1062. goto early_error;
  1063. mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
  1064. /* open file */
  1065. f = fopen (fn, "w");
  1066. if (f == NULL)
  1067. goto open_target_error;
  1068. tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
  1069. tmp_f = fopen (tmp_fn, "r");
  1070. if (tmp_f == NULL)
  1071. {
  1072. src_error = TRUE;
  1073. goto open_source_error;
  1074. }
  1075. /* put the new record */
  1076. if (line != 1 || column != 0 || bookmarks != NULL)
  1077. {
  1078. if (fprintf
  1079. (f, "%s %ld;%ld;%" PRIuMAX, vfs_path_as_str (filename_vpath), line, column,
  1080. (uintmax_t) offset) < 0)
  1081. goto write_position_error;
  1082. if (bookmarks != NULL)
  1083. for (i = 0; i < bookmarks->len && i < MAX_SAVED_BOOKMARKS; i++)
  1084. if (fprintf (f, ";%zu", g_array_index (bookmarks, size_t, i)) < 0)
  1085. goto write_position_error;
  1086. if (fprintf (f, "\n") < 0)
  1087. goto write_position_error;
  1088. }
  1089. i = 1;
  1090. while (fgets (buf, sizeof (buf), tmp_f) != NULL)
  1091. {
  1092. if (buf[len] == ' ' && strncmp (buf, vfs_path_as_str (filename_vpath), len) == 0
  1093. && strchr (&buf[len + 1], ' ') == NULL)
  1094. continue;
  1095. fprintf (f, "%s", buf);
  1096. if (++i > filepos_max_saved_entries)
  1097. break;
  1098. }
  1099. write_position_error:
  1100. fclose (tmp_f);
  1101. open_source_error:
  1102. g_free (tmp_fn);
  1103. fclose (f);
  1104. if (src_error)
  1105. mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
  1106. else
  1107. mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
  1108. open_target_error:
  1109. g_free (fn);
  1110. early_error:
  1111. if (bookmarks != NULL)
  1112. g_array_free (bookmarks, TRUE);
  1113. }
  1114. /* --------------------------------------------------------------------------------------------- */
  1115. extern int
  1116. ascii_alpha_to_cntrl (int ch)
  1117. {
  1118. if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
  1119. ch &= 0x1f;
  1120. return ch;
  1121. }
  1122. /* --------------------------------------------------------------------------------------------- */
  1123. const char *
  1124. Q_ (const char *s)
  1125. {
  1126. const char *result, *sep;
  1127. result = _(s);
  1128. sep = strchr (result, '|');
  1129. return sep != NULL ? sep + 1 : result;
  1130. }
  1131. /* --------------------------------------------------------------------------------------------- */
  1132. gboolean
  1133. mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
  1134. {
  1135. struct stat stat_buf;
  1136. char *backup_path;
  1137. gboolean ret;
  1138. if (!exist_file (file_name))
  1139. return FALSE;
  1140. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1141. if (backup_path == NULL)
  1142. return FALSE;
  1143. ret = mc_util_write_backup_content (file_name, backup_path);
  1144. if (ret)
  1145. {
  1146. /* Backup file will have same ownership with main file. */
  1147. if (stat (file_name, &stat_buf) == 0)
  1148. chmod (backup_path, stat_buf.st_mode);
  1149. else
  1150. chmod (backup_path, S_IRUSR | S_IWUSR);
  1151. }
  1152. g_free (backup_path);
  1153. return ret;
  1154. }
  1155. /* --------------------------------------------------------------------------------------------- */
  1156. gboolean
  1157. mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
  1158. {
  1159. gboolean ret;
  1160. char *backup_path;
  1161. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1162. if (backup_path == NULL)
  1163. return FALSE;
  1164. ret = mc_util_write_backup_content (backup_path, file_name);
  1165. g_free (backup_path);
  1166. return ret;
  1167. }
  1168. /* --------------------------------------------------------------------------------------------- */
  1169. gboolean
  1170. mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
  1171. {
  1172. char *backup_path;
  1173. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1174. if (backup_path == NULL)
  1175. return FALSE;
  1176. if (exist_file (backup_path))
  1177. {
  1178. vfs_path_t *vpath;
  1179. vpath = vfs_path_from_str (backup_path);
  1180. mc_unlink (vpath);
  1181. vfs_path_free (vpath, TRUE);
  1182. }
  1183. g_free (backup_path);
  1184. return TRUE;
  1185. }
  1186. /* --------------------------------------------------------------------------------------------- */
  1187. /**
  1188. * partly taken from dcigettext.c, returns "" for default locale
  1189. * value should be freed by calling function g_free()
  1190. */
  1191. char *
  1192. guess_message_value (void)
  1193. {
  1194. static const char *const var[] = {
  1195. /* Setting of LC_ALL overwrites all other. */
  1196. /* Do not use LANGUAGE for check user locale and drowing hints */
  1197. "LC_ALL",
  1198. /* Next comes the name of the desired category. */
  1199. "LC_MESSAGES",
  1200. /* Last possibility is the LANG environment variable. */
  1201. "LANG",
  1202. /* NULL exit loops */
  1203. NULL
  1204. };
  1205. size_t i;
  1206. const char *locale = NULL;
  1207. for (i = 0; var[i] != NULL; i++)
  1208. {
  1209. locale = getenv (var[i]);
  1210. if (locale != NULL && locale[0] != '\0')
  1211. break;
  1212. }
  1213. if (locale == NULL)
  1214. locale = "";
  1215. return g_strdup (locale);
  1216. }
  1217. /* --------------------------------------------------------------------------------------------- */
  1218. /**
  1219. * The "profile root" is the tree under which all of MC's user data &
  1220. * settings are stored.
  1221. *
  1222. * It defaults to the user's home dir. The user may override this default
  1223. * with the environment variable $MC_PROFILE_ROOT.
  1224. */
  1225. const char *
  1226. mc_get_profile_root (void)
  1227. {
  1228. static const char *profile_root = NULL;
  1229. if (profile_root == NULL)
  1230. {
  1231. profile_root = g_getenv ("MC_PROFILE_ROOT");
  1232. if (profile_root == NULL || *profile_root == '\0')
  1233. profile_root = mc_config_get_home_dir ();
  1234. }
  1235. return profile_root;
  1236. }
  1237. /* --------------------------------------------------------------------------------------------- */
  1238. /**
  1239. * Propagate error in simple way.
  1240. *
  1241. * @param dest error return location
  1242. * @param code error code
  1243. * @param format printf()-style format for error message
  1244. * @param ... parameters for message format
  1245. */
  1246. void
  1247. mc_propagate_error (GError **dest, int code, const char *format, ...)
  1248. {
  1249. if (dest != NULL && *dest == NULL)
  1250. {
  1251. GError *tmp_error;
  1252. va_list args;
  1253. va_start (args, format);
  1254. tmp_error = g_error_new_valist (MC_ERROR, code, format, args);
  1255. va_end (args);
  1256. g_propagate_error (dest, tmp_error);
  1257. }
  1258. }
  1259. /* --------------------------------------------------------------------------------------------- */
  1260. /**
  1261. * Replace existing error in simple way.
  1262. *
  1263. * @param dest error return location
  1264. * @param code error code
  1265. * @param format printf()-style format for error message
  1266. * @param ... parameters for message format
  1267. */
  1268. void
  1269. mc_replace_error (GError **dest, int code, const char *format, ...)
  1270. {
  1271. if (dest != NULL)
  1272. {
  1273. GError *tmp_error;
  1274. va_list args;
  1275. va_start (args, format);
  1276. tmp_error = g_error_new_valist (MC_ERROR, code, format, args);
  1277. va_end (args);
  1278. g_error_free (*dest);
  1279. *dest = NULL;
  1280. g_propagate_error (dest, tmp_error);
  1281. }
  1282. }
  1283. /* --------------------------------------------------------------------------------------------- */
  1284. /**
  1285. * Returns if the given duration has elapsed since the given timestamp,
  1286. * and if it has then updates the timestamp.
  1287. *
  1288. * @param timestamp the last timestamp in microseconds, updated if the given time elapsed
  1289. * @param delay amount of time in microseconds
  1290. * @return TRUE if clock skew detected, FALSE otherwise
  1291. */
  1292. gboolean
  1293. mc_time_elapsed (gint64 *timestamp, gint64 delay)
  1294. {
  1295. gint64 now;
  1296. now = g_get_monotonic_time ();
  1297. if (now >= *timestamp && now < *timestamp + delay)
  1298. return FALSE;
  1299. *timestamp = now;
  1300. return TRUE;
  1301. }
  1302. /* --------------------------------------------------------------------------------------------- */