util.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. /* Various utilities
  2. Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
  3. 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
  4. Written 1994, 1995, 1996 by:
  5. Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
  6. Jakub Jelinek, Mauricio Plaza.
  7. The file_date routine is mostly from GNU's fileutils package,
  8. written by Richard Stallman and David MacKenzie.
  9. This program is free software; you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation; either version 2 of the License, or
  12. (at your option) any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  20. /** \file
  21. * \brief Source: various utilities
  22. */
  23. #include <config.h>
  24. #include <ctype.h>
  25. #include <limits.h>
  26. #include <stdarg.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <fcntl.h>
  31. #include <sys/time.h>
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <unistd.h>
  35. #include "lib/global.h"
  36. #include "lib/tty/win.h" /* xterm_flag */
  37. #include "lib/search.h"
  38. #include "lib/mcconfig.h"
  39. #include "lib/timefmt.h"
  40. #include "lib/fileloc.h"
  41. #include "lib/vfs/mc-vfs/vfs.h"
  42. #include "lib/strutil.h"
  43. #include "src/filegui.h"
  44. #include "src/file.h" /* copy_file_file() */
  45. #ifndef HAVE_CHARSET
  46. #include "src/main.h" /* eight_bit_clean */
  47. #endif
  48. int easy_patterns = 1;
  49. char *user_recent_timeformat = NULL; /* time format string for recent dates */
  50. char *user_old_timeformat = NULL; /* time format string for older dates */
  51. /*
  52. * Cache variable for the i18n_checktimelength function,
  53. * initially set to a clearly invalid value to show that
  54. * it hasn't been initialized yet.
  55. */
  56. static size_t i18n_timelength_cache = MAX_I18NTIMELENGTH + 1;
  57. extern void
  58. str_replace (char *s, char from, char to)
  59. {
  60. for (; *s != '\0'; s++)
  61. {
  62. if (*s == from)
  63. *s = to;
  64. }
  65. }
  66. static inline int
  67. is_7bit_printable (unsigned char c)
  68. {
  69. return (c > 31 && c < 127);
  70. }
  71. static inline int
  72. is_iso_printable (unsigned char c)
  73. {
  74. return ((c > 31 && c < 127) || c >= 160);
  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 (xterm_flag)
  81. return is_iso_printable (c);
  82. return (c > 31 && c != 127 && c != 155);
  83. }
  84. int
  85. is_printable (int c)
  86. {
  87. c &= 0xff;
  88. #ifdef HAVE_CHARSET
  89. /* "Display bits" is ignored, since the user controls the output
  90. by setting the output codepage */
  91. return is_8bit_printable (c);
  92. #else
  93. if (!eight_bit_clean)
  94. return is_7bit_printable (c);
  95. if (full_eight_bits)
  96. {
  97. return is_8bit_printable (c);
  98. }
  99. else
  100. return is_iso_printable (c);
  101. #endif /* !HAVE_CHARSET */
  102. }
  103. /* Calculates the message dimensions (lines and columns) */
  104. void
  105. msglen (const char *text, int *lines, int *columns)
  106. {
  107. int nlines = 1; /* even the empty string takes one line */
  108. int ncolumns = 0;
  109. int colindex = 0;
  110. for (; *text != '\0'; text++)
  111. {
  112. if (*text == '\n')
  113. {
  114. nlines++;
  115. colindex = 0;
  116. }
  117. else
  118. {
  119. colindex++;
  120. if (colindex > ncolumns)
  121. ncolumns = colindex;
  122. }
  123. }
  124. *lines = nlines;
  125. *columns = ncolumns;
  126. }
  127. /*
  128. * Copy from s to d, and trim the beginning if necessary, and prepend
  129. * "..." in this case. The destination string can have at most len
  130. * bytes, not counting trailing 0.
  131. */
  132. char *
  133. trim (const char *s, char *d, int len)
  134. {
  135. int source_len;
  136. /* Sanity check */
  137. len = max (len, 0);
  138. source_len = strlen (s);
  139. if (source_len > len)
  140. {
  141. /* Cannot fit the whole line */
  142. if (len <= 3)
  143. {
  144. /* We only have room for the dots */
  145. memset (d, '.', len);
  146. d[len] = 0;
  147. return d;
  148. }
  149. else
  150. {
  151. /* Begin with ... and add the rest of the source string */
  152. memset (d, '.', 3);
  153. strcpy (d + 3, s + 3 + source_len - len);
  154. }
  155. }
  156. else
  157. /* We can copy the whole line */
  158. strcpy (d, s);
  159. return d;
  160. }
  161. /*
  162. * Quote the filename for the purpose of inserting it into the command
  163. * line. If quote_percent is 1, replace "%" with "%%" - the percent is
  164. * processed by the mc command line.
  165. */
  166. char *
  167. name_quote (const char *s, int quote_percent)
  168. {
  169. char *ret, *d;
  170. d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
  171. if (*s == '-')
  172. {
  173. *d++ = '.';
  174. *d++ = '/';
  175. }
  176. for (; *s; s++, d++)
  177. {
  178. switch (*s)
  179. {
  180. case '%':
  181. if (quote_percent)
  182. *d++ = '%';
  183. break;
  184. case '\'':
  185. case '\\':
  186. case '\r':
  187. case '\n':
  188. case '\t':
  189. case '"':
  190. case ';':
  191. case ' ':
  192. case '?':
  193. case '|':
  194. case '[':
  195. case ']':
  196. case '{':
  197. case '}':
  198. case '<':
  199. case '>':
  200. case '`':
  201. case '!':
  202. case '$':
  203. case '&':
  204. case '*':
  205. case '(':
  206. case ')':
  207. *d++ = '\\';
  208. break;
  209. case '~':
  210. case '#':
  211. if (d == ret)
  212. *d++ = '\\';
  213. break;
  214. }
  215. *d = *s;
  216. }
  217. *d = '\0';
  218. return ret;
  219. }
  220. char *
  221. fake_name_quote (const char *s, int quote_percent)
  222. {
  223. (void) quote_percent;
  224. return g_strdup (s);
  225. }
  226. /*
  227. * Remove the middle part of the string to fit given length.
  228. * Use "~" to show where the string was truncated.
  229. * Return static buffer, no need to free() it.
  230. */
  231. const char *
  232. name_trunc (const char *txt, size_t trunc_len)
  233. {
  234. return str_trunc (txt, trunc_len);
  235. }
  236. /*
  237. * path_trunc() is the same as name_trunc() above but
  238. * it deletes possible password from path for security
  239. * reasons.
  240. */
  241. const char *
  242. path_trunc (const char *path, size_t trunc_len)
  243. {
  244. char *secure_path = strip_password (g_strdup (path), 1);
  245. const char *ret = str_trunc (secure_path, trunc_len);
  246. g_free (secure_path);
  247. return ret;
  248. }
  249. const char *
  250. size_trunc (double size, gboolean use_si)
  251. {
  252. static char x[BUF_TINY];
  253. long int divisor = 1;
  254. const char *xtra = "";
  255. if (size > 999999999L)
  256. {
  257. divisor = use_si ? 1000 : 1024;
  258. xtra = use_si ? "k" : "K";
  259. if (size / divisor > 999999999L)
  260. {
  261. divisor = use_si ? (1000 * 1000) : (1024 * 1024);
  262. xtra = use_si ? "m" : "M";
  263. }
  264. }
  265. g_snprintf (x, sizeof (x), "%.0f%s", (size / divisor), xtra);
  266. return x;
  267. }
  268. const char *
  269. size_trunc_sep (double size, gboolean use_si)
  270. {
  271. static char x[60];
  272. int count;
  273. const char *p, *y;
  274. char *d;
  275. p = y = size_trunc (size, use_si);
  276. p += strlen (p) - 1;
  277. d = x + sizeof (x) - 1;
  278. *d-- = 0;
  279. while (p >= y && isalpha ((unsigned char) *p))
  280. *d-- = *p--;
  281. for (count = 0; p >= y; count++)
  282. {
  283. if (count == 3)
  284. {
  285. *d-- = ',';
  286. count = 0;
  287. }
  288. *d-- = *p--;
  289. }
  290. d++;
  291. if (*d == ',')
  292. d++;
  293. return d;
  294. }
  295. /*
  296. * Print file SIZE to BUFFER, but don't exceed LEN characters,
  297. * not including trailing 0. BUFFER should be at least LEN+1 long.
  298. * This function is called for every file on panels, so avoid
  299. * floating point by any means.
  300. *
  301. * Units: size units (filesystem sizes are 1K blocks)
  302. * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
  303. */
  304. void
  305. size_trunc_len (char *buffer, unsigned int len, off_t size, int units, gboolean use_si)
  306. {
  307. /* Avoid taking power for every file. */
  308. static const off_t power10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
  309. 1000000000
  310. };
  311. static const char *const suffix[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL };
  312. static const char *const suffix_lc[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL };
  313. int j = 0;
  314. int size_remain;
  315. if (len == 0)
  316. len = 9;
  317. /*
  318. * recalculate from 1024 base to 1000 base if units>0
  319. * We can't just multiply by 1024 - that might cause overflow
  320. * if off_t type is too small
  321. */
  322. if (units && use_si)
  323. {
  324. for (j = 0; j < units; j++)
  325. {
  326. size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
  327. size = size / 125; /* 128/125 = 1024/1000 */
  328. size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
  329. size += size_remain; /* Re-add remainder lost by division/multiplication */
  330. }
  331. }
  332. for (j = units; suffix[j] != NULL; j++)
  333. {
  334. if (size == 0)
  335. {
  336. if (j == units)
  337. {
  338. /* Empty files will print "0" even with minimal width. */
  339. g_snprintf (buffer, len + 1, "0");
  340. break;
  341. }
  342. /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
  343. g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
  344. (j > 1) ? (use_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
  345. break;
  346. }
  347. if (size < power10[len - (j > 0)])
  348. {
  349. g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size,
  350. use_si ? suffix_lc[j] : suffix[j]);
  351. break;
  352. }
  353. /* Powers of 1000 or 1024, with rounding. */
  354. if (use_si)
  355. size = (size + 500) / 1000;
  356. else
  357. size = (size + 512) >> 10;
  358. }
  359. }
  360. int
  361. is_exe (mode_t mode)
  362. {
  363. if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
  364. return 1;
  365. return 0;
  366. }
  367. #define ismode(n,m) ((n & m) == m)
  368. const char *
  369. string_perm (mode_t mode_bits)
  370. {
  371. static char mode[11];
  372. strcpy (mode, "----------");
  373. if (S_ISDIR (mode_bits))
  374. mode[0] = 'd';
  375. if (S_ISCHR (mode_bits))
  376. mode[0] = 'c';
  377. if (S_ISBLK (mode_bits))
  378. mode[0] = 'b';
  379. if (S_ISLNK (mode_bits))
  380. mode[0] = 'l';
  381. if (S_ISFIFO (mode_bits))
  382. mode[0] = 'p';
  383. if (S_ISNAM (mode_bits))
  384. mode[0] = 'n';
  385. if (S_ISSOCK (mode_bits))
  386. mode[0] = 's';
  387. if (S_ISDOOR (mode_bits))
  388. mode[0] = 'D';
  389. if (ismode (mode_bits, S_IXOTH))
  390. mode[9] = 'x';
  391. if (ismode (mode_bits, S_IWOTH))
  392. mode[8] = 'w';
  393. if (ismode (mode_bits, S_IROTH))
  394. mode[7] = 'r';
  395. if (ismode (mode_bits, S_IXGRP))
  396. mode[6] = 'x';
  397. if (ismode (mode_bits, S_IWGRP))
  398. mode[5] = 'w';
  399. if (ismode (mode_bits, S_IRGRP))
  400. mode[4] = 'r';
  401. if (ismode (mode_bits, S_IXUSR))
  402. mode[3] = 'x';
  403. if (ismode (mode_bits, S_IWUSR))
  404. mode[2] = 'w';
  405. if (ismode (mode_bits, S_IRUSR))
  406. mode[1] = 'r';
  407. #ifdef S_ISUID
  408. if (ismode (mode_bits, S_ISUID))
  409. mode[3] = (mode[3] == 'x') ? 's' : 'S';
  410. #endif /* S_ISUID */
  411. #ifdef S_ISGID
  412. if (ismode (mode_bits, S_ISGID))
  413. mode[6] = (mode[6] == 'x') ? 's' : 'S';
  414. #endif /* S_ISGID */
  415. #ifdef S_ISVTX
  416. if (ismode (mode_bits, S_ISVTX))
  417. mode[9] = (mode[9] == 'x') ? 't' : 'T';
  418. #endif /* S_ISVTX */
  419. return mode;
  420. }
  421. /* p: string which might contain an url with a password (this parameter is
  422. modified in place).
  423. has_prefix = 0: The first parameter is an url without a prefix
  424. (user[:pass]@]machine[:port][remote-dir). Delete
  425. the password.
  426. has_prefix = 1: Search p for known url prefixes. If found delete
  427. the password from the url.
  428. Caveat: only the first url is found
  429. */
  430. char *
  431. strip_password (char *p, int has_prefix)
  432. {
  433. static const struct
  434. {
  435. const char *name;
  436. size_t len;
  437. } prefixes[] =
  438. {
  439. /* *INDENT-OFF* */
  440. { "/#ftp:", 6 },
  441. { "ftp://", 6 },
  442. { "/#smb:", 6 },
  443. { "smb://", 6 },
  444. { "/#sh:", 5 },
  445. { "sh://", 5 },
  446. { "ssh://", 6 }
  447. /* *INDENT-ON* */
  448. };
  449. char *at, *inner_colon, *dir;
  450. size_t i;
  451. char *result = p;
  452. for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
  453. {
  454. char *q;
  455. if (has_prefix)
  456. {
  457. q = strstr (p, prefixes[i].name);
  458. if (q == NULL)
  459. continue;
  460. else
  461. p = q + prefixes[i].len;
  462. }
  463. dir = strchr (p, PATH_SEP);
  464. if (dir != NULL)
  465. *dir = '\0';
  466. /* search for any possible user */
  467. at = strrchr (p, '@');
  468. if (dir)
  469. *dir = PATH_SEP;
  470. /* We have a username */
  471. if (at)
  472. {
  473. inner_colon = memchr (p, ':', at - p);
  474. if (inner_colon)
  475. memmove (inner_colon, at, strlen (at) + 1);
  476. }
  477. break;
  478. }
  479. return (result);
  480. }
  481. const char *
  482. strip_home_and_password (const char *dir)
  483. {
  484. size_t len;
  485. static char newdir[MC_MAXPATHLEN];
  486. len = strlen (home_dir);
  487. if (home_dir != NULL && strncmp (dir, home_dir, len) == 0 &&
  488. (dir[len] == PATH_SEP || dir[len] == '\0'))
  489. {
  490. newdir[0] = '~';
  491. g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
  492. return newdir;
  493. }
  494. /* We do not strip homes in /#ftp tree, I do not like ~'s there
  495. (see ftpfs.c why) */
  496. g_strlcpy (newdir, dir, sizeof (newdir));
  497. strip_password (newdir, 1);
  498. return newdir;
  499. }
  500. const char *
  501. extension (const char *filename)
  502. {
  503. const char *d = strrchr (filename, '.');
  504. return (d != NULL) ? d + 1 : "";
  505. }
  506. int
  507. exist_file (const char *name)
  508. {
  509. return access (name, R_OK) == 0;
  510. }
  511. int
  512. check_for_default (const char *default_file, const char *file)
  513. {
  514. if (!exist_file (file))
  515. {
  516. FileOpContext *ctx;
  517. FileOpTotalContext *tctx;
  518. if (!exist_file (default_file))
  519. return -1;
  520. ctx = file_op_context_new (OP_COPY);
  521. tctx = file_op_total_context_new ();
  522. file_op_context_create_ui (ctx, 0, FALSE);
  523. copy_file_file (tctx, ctx, default_file, file);
  524. file_op_total_context_destroy (tctx);
  525. file_op_context_destroy (ctx);
  526. }
  527. return 0;
  528. }
  529. char *
  530. load_file (const char *filename)
  531. {
  532. FILE *data_file;
  533. struct stat s;
  534. char *data;
  535. long read_size;
  536. data_file = fopen (filename, "r");
  537. if (data_file == NULL)
  538. {
  539. return 0;
  540. }
  541. if (fstat (fileno (data_file), &s) != 0)
  542. {
  543. fclose (data_file);
  544. return 0;
  545. }
  546. data = g_malloc (s.st_size + 1);
  547. read_size = fread (data, 1, s.st_size, data_file);
  548. data[read_size] = 0;
  549. fclose (data_file);
  550. if (read_size > 0)
  551. return data;
  552. else
  553. {
  554. g_free (data);
  555. return 0;
  556. }
  557. }
  558. char *
  559. load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename,
  560. char **allocated_filename)
  561. {
  562. char *hintfile_base, *hintfile;
  563. char *lang;
  564. char *data;
  565. hintfile_base = concat_dir_and_file (_mc_home, filename);
  566. lang = guess_message_value ();
  567. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  568. data = load_file (hintfile);
  569. if (!data)
  570. {
  571. g_free (hintfile);
  572. g_free (hintfile_base);
  573. hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
  574. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  575. data = load_file (hintfile);
  576. if (!data)
  577. {
  578. /* Fall back to the two-letter language code */
  579. if (lang[0] && lang[1])
  580. lang[2] = 0;
  581. g_free (hintfile);
  582. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  583. data = load_file (hintfile);
  584. if (!data)
  585. {
  586. g_free (hintfile);
  587. hintfile = hintfile_base;
  588. data = load_file (hintfile_base);
  589. }
  590. }
  591. }
  592. g_free (lang);
  593. if (hintfile != hintfile_base)
  594. g_free (hintfile_base);
  595. if (allocated_filename)
  596. *allocated_filename = hintfile;
  597. else
  598. g_free (hintfile);
  599. return data;
  600. }
  601. /* Check strftime() results. Some systems (i.e. Solaris) have different
  602. short-month and month name sizes for different locales */
  603. size_t
  604. i18n_checktimelength (void)
  605. {
  606. size_t length = 0;
  607. const time_t testtime = time (NULL);
  608. struct tm *lt = localtime (&testtime);
  609. if (i18n_timelength_cache <= MAX_I18NTIMELENGTH)
  610. return i18n_timelength_cache;
  611. if (lt == NULL)
  612. {
  613. /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
  614. length = str_term_width1 (_(INVALID_TIME_TEXT));
  615. }
  616. else
  617. {
  618. char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
  619. /* We are interested in the longest possible date */
  620. lt->tm_sec = lt->tm_min = lt->tm_hour = lt->tm_mday = 10;
  621. /* Loop through all months to find out the longest one */
  622. for (lt->tm_mon = 0; lt->tm_mon < 12; lt->tm_mon++) {
  623. strftime (buf, sizeof(buf) - 1, user_recent_timeformat, lt);
  624. length = max ((size_t) str_term_width1 (buf), length);
  625. strftime (buf, sizeof(buf) - 1, user_old_timeformat, lt);
  626. length = max ((size_t) str_term_width1 (buf), length);
  627. }
  628. length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
  629. }
  630. /* Don't handle big differences. Use standard value (email bug, please) */
  631. if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
  632. length = STD_I18NTIMELENGTH;
  633. /* Save obtained value to the cache */
  634. i18n_timelength_cache = length;
  635. return i18n_timelength_cache;
  636. }
  637. const char *
  638. file_date (time_t when)
  639. {
  640. static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
  641. time_t current_time = time ((time_t) 0);
  642. const char *fmt;
  643. if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
  644. || current_time < when - 60L * 60L) /* In the future. */
  645. /* The file is fairly old or in the future.
  646. POSIX says the cutoff is 6 months old;
  647. approximate this by 6*30 days.
  648. Allow a 1 hour slop factor for what is considered "the future",
  649. to allow for NFS server/client clock disagreement.
  650. Show the year instead of the time of day. */
  651. fmt = user_old_timeformat;
  652. else
  653. fmt = user_recent_timeformat;
  654. FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
  655. return timebuf;
  656. }
  657. const char *
  658. extract_line (const char *s, const char *top)
  659. {
  660. static char tmp_line[BUF_MEDIUM];
  661. char *t = tmp_line;
  662. while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
  663. *t++ = *s++;
  664. *t = 0;
  665. return tmp_line;
  666. }
  667. /* The basename routine */
  668. const char *
  669. x_basename (const char *s)
  670. {
  671. const char *where;
  672. return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
  673. }
  674. const char *
  675. unix_error_string (int error_num)
  676. {
  677. static char buffer[BUF_LARGE];
  678. gchar *strerror_currentlocale;
  679. strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
  680. g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
  681. g_free (strerror_currentlocale);
  682. return buffer;
  683. }
  684. const char *
  685. skip_separators (const char *s)
  686. {
  687. const char *su = s;
  688. for (; *su; str_cnext_char (&su))
  689. if (*su != ' ' && *su != '\t' && *su != ',')
  690. break;
  691. return su;
  692. }
  693. const char *
  694. skip_numbers (const char *s)
  695. {
  696. const char *su = s;
  697. for (; *su; str_cnext_char (&su))
  698. if (!str_isdigit (su))
  699. break;
  700. return su;
  701. }
  702. /* Remove all control sequences from the argument string. We define
  703. * "control sequence", in a sort of pidgin BNF, as follows:
  704. *
  705. * control-seq = Esc non-'['
  706. * | Esc '[' (0 or more digits or ';' or '?') (any other char)
  707. *
  708. * This scheme works for all the terminals described in my termcap /
  709. * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
  710. * terminals. If I hear from a single person who uses such a terminal
  711. * with MC, I'll be glad to add support for it. (Dugan)
  712. * Non-printable characters are also removed.
  713. */
  714. char *
  715. strip_ctrl_codes (char *s)
  716. {
  717. char *w; /* Current position where the stripped data is written */
  718. char *r; /* Current position where the original data is read */
  719. char *n;
  720. if (!s)
  721. return 0;
  722. for (w = s, r = s; *r;)
  723. {
  724. if (*r == ESC_CHAR)
  725. {
  726. /* Skip the control sequence's arguments */ ;
  727. /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
  728. if (*(++r) == '[' || *r == '(')
  729. {
  730. /* strchr() matches trailing binary 0 */
  731. while (*(++r) && strchr ("0123456789;?", *r));
  732. }
  733. else if (*r == ']')
  734. {
  735. /*
  736. * Skip xterm's OSC (Operating System Command)
  737. * http://www.xfree86.org/current/ctlseqs.html
  738. * OSC P s ; P t ST
  739. * OSC P s ; P t BEL
  740. */
  741. char *new_r = r;
  742. for (; *new_r; ++new_r)
  743. {
  744. switch (*new_r)
  745. {
  746. /* BEL */
  747. case '\a':
  748. r = new_r;
  749. goto osc_out;
  750. case ESC_CHAR:
  751. /* ST */
  752. if (*(new_r + 1) == '\\')
  753. {
  754. r = new_r + 1;
  755. goto osc_out;
  756. }
  757. }
  758. }
  759. osc_out:;
  760. }
  761. /*
  762. * Now we are at the last character of the sequence.
  763. * Skip it unless it's binary 0.
  764. */
  765. if (*r)
  766. r++;
  767. continue;
  768. }
  769. n = str_get_next_char (r);
  770. if (str_isprint (r))
  771. {
  772. memmove (w, r, n - r);
  773. w += n - r;
  774. }
  775. r = n;
  776. }
  777. *w = 0;
  778. return s;
  779. }
  780. #ifndef ENABLE_VFS
  781. char *
  782. get_current_wd (char *buffer, size_t size)
  783. {
  784. char *p;
  785. size_t len;
  786. p = g_get_current_dir ();
  787. len = strlen (p) + 1;
  788. if (len > size)
  789. {
  790. g_free (p);
  791. return NULL;
  792. }
  793. memcpy (buffer, p, len);
  794. g_free (p);
  795. return buffer;
  796. }
  797. #endif /* !ENABLE_VFS */
  798. enum compression_type
  799. get_compression_type (int fd, const char *name)
  800. {
  801. unsigned char magic[16];
  802. size_t str_len;
  803. /* Read the magic signature */
  804. if (mc_read (fd, (char *) magic, 4) != 4)
  805. return COMPRESSION_NONE;
  806. /* GZIP_MAGIC and OLD_GZIP_MAGIC */
  807. if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
  808. {
  809. return COMPRESSION_GZIP;
  810. }
  811. /* PKZIP_MAGIC */
  812. if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
  813. {
  814. /* Read compression type */
  815. mc_lseek (fd, 8, SEEK_SET);
  816. if (mc_read (fd, (char *) magic, 2) != 2)
  817. return COMPRESSION_NONE;
  818. /* Gzip can handle only deflated (8) or stored (0) files */
  819. if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
  820. return COMPRESSION_NONE;
  821. /* Compatible with gzip */
  822. return COMPRESSION_GZIP;
  823. }
  824. /* PACK_MAGIC and LZH_MAGIC and compress magic */
  825. if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
  826. {
  827. /* Compatible with gzip */
  828. return COMPRESSION_GZIP;
  829. }
  830. /* BZIP and BZIP2 files */
  831. if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
  832. {
  833. switch (magic[2])
  834. {
  835. case '0':
  836. return COMPRESSION_BZIP;
  837. case 'h':
  838. return COMPRESSION_BZIP2;
  839. }
  840. }
  841. /* Support for LZMA (only utils format with magic in header).
  842. * This is the default format of LZMA utils 4.32.1 and later. */
  843. if (mc_read (fd, (char *) magic + 4, 2) != 2)
  844. return COMPRESSION_NONE;
  845. /* LZMA utils format */
  846. if (magic[0] == 0xFF
  847. && magic[1] == 'L'
  848. && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
  849. return COMPRESSION_LZMA;
  850. /* XZ compression magic */
  851. if (magic[0] == 0xFD
  852. && magic[1] == 0x37
  853. && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
  854. return COMPRESSION_XZ;
  855. str_len = strlen (name);
  856. /* HACK: we must belive to extention of LZMA file :) ... */
  857. if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
  858. (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
  859. return COMPRESSION_LZMA;
  860. return COMPRESSION_NONE;
  861. }
  862. const char *
  863. decompress_extension (int type)
  864. {
  865. switch (type)
  866. {
  867. case COMPRESSION_GZIP:
  868. return "#ugz";
  869. case COMPRESSION_BZIP:
  870. return "#ubz";
  871. case COMPRESSION_BZIP2:
  872. return "#ubz2";
  873. case COMPRESSION_LZMA:
  874. return "#ulzma";
  875. case COMPRESSION_XZ:
  876. return "#uxz";
  877. }
  878. /* Should never reach this place */
  879. fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
  880. return 0;
  881. }
  882. /* Hooks */
  883. void
  884. add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
  885. {
  886. Hook *new_hook = g_new (Hook, 1);
  887. new_hook->hook_fn = hook_fn;
  888. new_hook->next = *hook_list;
  889. new_hook->hook_data = data;
  890. *hook_list = new_hook;
  891. }
  892. void
  893. execute_hooks (Hook * hook_list)
  894. {
  895. Hook *new_hook = 0;
  896. Hook *p;
  897. /* We copy the hook list first so tahat we let the hook
  898. * function call delete_hook
  899. */
  900. while (hook_list)
  901. {
  902. add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
  903. hook_list = hook_list->next;
  904. }
  905. p = new_hook;
  906. while (new_hook)
  907. {
  908. (*new_hook->hook_fn) (new_hook->hook_data);
  909. new_hook = new_hook->next;
  910. }
  911. for (hook_list = p; hook_list;)
  912. {
  913. p = hook_list;
  914. hook_list = hook_list->next;
  915. g_free (p);
  916. }
  917. }
  918. void
  919. delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
  920. {
  921. Hook *current, *new_list, *next;
  922. new_list = 0;
  923. for (current = *hook_list; current; current = next)
  924. {
  925. next = current->next;
  926. if (current->hook_fn == hook_fn)
  927. g_free (current);
  928. else
  929. add_hook (&new_list, current->hook_fn, current->hook_data);
  930. }
  931. *hook_list = new_list;
  932. }
  933. int
  934. hook_present (Hook * hook_list, void (*hook_fn) (void *))
  935. {
  936. Hook *p;
  937. for (p = hook_list; p; p = p->next)
  938. if (p->hook_fn == hook_fn)
  939. return 1;
  940. return 0;
  941. }
  942. void
  943. wipe_password (char *passwd)
  944. {
  945. char *p = passwd;
  946. if (!p)
  947. return;
  948. for (; *p; p++)
  949. *p = 0;
  950. g_free (passwd);
  951. }
  952. /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
  953. /* Returns a newly allocated string */
  954. char *
  955. convert_controls (const char *p)
  956. {
  957. char *valcopy = g_strdup (p);
  958. char *q;
  959. /* Parse the escape special character */
  960. for (q = valcopy; *p;)
  961. {
  962. if (*p == '\\')
  963. {
  964. p++;
  965. if ((*p == 'e') || (*p == 'E'))
  966. {
  967. p++;
  968. *q++ = ESC_CHAR;
  969. }
  970. }
  971. else
  972. {
  973. if (*p == '^')
  974. {
  975. p++;
  976. if (*p == '^')
  977. *q++ = *p++;
  978. else
  979. {
  980. char c = (*p | 0x20);
  981. if (c >= 'a' && c <= 'z')
  982. {
  983. *q++ = c - 'a' + 1;
  984. p++;
  985. }
  986. else if (*p)
  987. p++;
  988. }
  989. }
  990. else
  991. *q++ = *p++;
  992. }
  993. }
  994. *q = 0;
  995. return valcopy;
  996. }
  997. static char *
  998. resolve_symlinks (const char *path)
  999. {
  1000. char *buf, *buf2, *q, *r, c;
  1001. int len;
  1002. struct stat mybuf;
  1003. const char *p;
  1004. if (*path != PATH_SEP)
  1005. return NULL;
  1006. r = buf = g_malloc (MC_MAXPATHLEN);
  1007. buf2 = g_malloc (MC_MAXPATHLEN);
  1008. *r++ = PATH_SEP;
  1009. *r = 0;
  1010. p = path;
  1011. for (;;)
  1012. {
  1013. q = strchr (p + 1, PATH_SEP);
  1014. if (!q)
  1015. {
  1016. q = strchr (p + 1, 0);
  1017. if (q == p + 1)
  1018. break;
  1019. }
  1020. c = *q;
  1021. *q = 0;
  1022. if (mc_lstat (path, &mybuf) < 0)
  1023. {
  1024. g_free (buf);
  1025. g_free (buf2);
  1026. *q = c;
  1027. return NULL;
  1028. }
  1029. if (!S_ISLNK (mybuf.st_mode))
  1030. strcpy (r, p + 1);
  1031. else
  1032. {
  1033. len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
  1034. if (len < 0)
  1035. {
  1036. g_free (buf);
  1037. g_free (buf2);
  1038. *q = c;
  1039. return NULL;
  1040. }
  1041. buf2[len] = 0;
  1042. if (*buf2 == PATH_SEP)
  1043. strcpy (buf, buf2);
  1044. else
  1045. strcpy (r, buf2);
  1046. }
  1047. canonicalize_pathname (buf);
  1048. r = strchr (buf, 0);
  1049. if (!*r || *(r - 1) != PATH_SEP)
  1050. {
  1051. *r++ = PATH_SEP;
  1052. *r = 0;
  1053. }
  1054. *q = c;
  1055. p = q;
  1056. if (!c)
  1057. break;
  1058. }
  1059. if (!*buf)
  1060. strcpy (buf, PATH_SEP_STR);
  1061. else if (*(r - 1) == PATH_SEP && r != buf + 1)
  1062. *(r - 1) = 0;
  1063. g_free (buf2);
  1064. return buf;
  1065. }
  1066. static gboolean
  1067. mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
  1068. {
  1069. FILE *backup_fd;
  1070. char *contents;
  1071. gsize length;
  1072. gboolean ret1 = TRUE;
  1073. if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
  1074. return FALSE;
  1075. backup_fd = fopen (to_file_name, "w");
  1076. if (backup_fd == NULL)
  1077. {
  1078. g_free (contents);
  1079. return FALSE;
  1080. }
  1081. if (fwrite ((const void *) contents, 1, length, backup_fd) != length)
  1082. ret1 = FALSE;
  1083. {
  1084. int ret2;
  1085. ret2 = fflush (backup_fd);
  1086. ret2 = fclose (backup_fd);
  1087. }
  1088. g_free (contents);
  1089. return ret1;
  1090. }
  1091. /* Finds out a relative path from first to second, i.e. goes as many ..
  1092. * as needed up in first and then goes down using second */
  1093. char *
  1094. diff_two_paths (const char *first, const char *second)
  1095. {
  1096. char *p, *q, *r, *s, *buf = NULL;
  1097. int i, j, prevlen = -1, currlen;
  1098. char *my_first = NULL, *my_second = NULL;
  1099. my_first = resolve_symlinks (first);
  1100. if (my_first == NULL)
  1101. return NULL;
  1102. my_second = resolve_symlinks (second);
  1103. if (my_second == NULL)
  1104. {
  1105. g_free (my_first);
  1106. return NULL;
  1107. }
  1108. for (j = 0; j < 2; j++)
  1109. {
  1110. p = my_first;
  1111. q = my_second;
  1112. for (;;)
  1113. {
  1114. r = strchr (p, PATH_SEP);
  1115. s = strchr (q, PATH_SEP);
  1116. if (!r || !s)
  1117. break;
  1118. *r = 0;
  1119. *s = 0;
  1120. if (strcmp (p, q))
  1121. {
  1122. *r = PATH_SEP;
  1123. *s = PATH_SEP;
  1124. break;
  1125. }
  1126. else
  1127. {
  1128. *r = PATH_SEP;
  1129. *s = PATH_SEP;
  1130. }
  1131. p = r + 1;
  1132. q = s + 1;
  1133. }
  1134. p--;
  1135. for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
  1136. currlen = (i + 1) * 3 + strlen (q) + 1;
  1137. if (j)
  1138. {
  1139. if (currlen < prevlen)
  1140. g_free (buf);
  1141. else
  1142. {
  1143. g_free (my_first);
  1144. g_free (my_second);
  1145. return buf;
  1146. }
  1147. }
  1148. p = buf = g_malloc (currlen);
  1149. prevlen = currlen;
  1150. for (; i >= 0; i--, p += 3)
  1151. strcpy (p, "../");
  1152. strcpy (p, q);
  1153. }
  1154. g_free (my_first);
  1155. g_free (my_second);
  1156. return buf;
  1157. }
  1158. /* If filename is NULL, then we just append PATH_SEP to the dir */
  1159. char *
  1160. concat_dir_and_file (const char *dir, const char *file)
  1161. {
  1162. int i = strlen (dir);
  1163. if (dir[i - 1] == PATH_SEP)
  1164. return g_strconcat (dir, file, (char *) NULL);
  1165. else
  1166. return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
  1167. }
  1168. /* Append text to GList, remove all entries with the same text */
  1169. GList *
  1170. list_append_unique (GList * list, char *text)
  1171. {
  1172. GList *lc_link;
  1173. /*
  1174. * Go to the last position and traverse the list backwards
  1175. * starting from the second last entry to make sure that we
  1176. * are not removing the current link.
  1177. */
  1178. list = g_list_append (list, text);
  1179. list = g_list_last (list);
  1180. lc_link = g_list_previous (list);
  1181. while (lc_link != NULL)
  1182. {
  1183. GList *newlink;
  1184. newlink = g_list_previous (lc_link);
  1185. if (strcmp ((char *) lc_link->data, text) == 0)
  1186. {
  1187. GList *tmp;
  1188. g_free (lc_link->data);
  1189. tmp = g_list_remove_link (list, lc_link);
  1190. g_list_free_1 (lc_link);
  1191. }
  1192. lc_link = newlink;
  1193. }
  1194. return list;
  1195. }
  1196. /* Following code heavily borrows from libiberty, mkstemps.c */
  1197. /* Number of attempts to create a temporary file */
  1198. #ifndef TMP_MAX
  1199. #define TMP_MAX 16384
  1200. #endif /* !TMP_MAX */
  1201. /*
  1202. * Arguments:
  1203. * pname (output) - pointer to the name of the temp file (needs g_free).
  1204. * NULL if the function fails.
  1205. * prefix - part of the filename before the random part.
  1206. * Prepend $TMPDIR or /tmp if there are no path separators.
  1207. * suffix - if not NULL, part of the filename after the random part.
  1208. *
  1209. * Result:
  1210. * handle of the open file or -1 if couldn't open any.
  1211. */
  1212. int
  1213. mc_mkstemps (char **pname, const char *prefix, const char *suffix)
  1214. {
  1215. static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1216. static unsigned long value;
  1217. struct timeval tv;
  1218. char *tmpbase;
  1219. char *tmpname;
  1220. char *XXXXXX;
  1221. int count;
  1222. if (strchr (prefix, PATH_SEP) == NULL)
  1223. {
  1224. /* Add prefix first to find the position of XXXXXX */
  1225. tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
  1226. }
  1227. else
  1228. {
  1229. tmpbase = g_strdup (prefix);
  1230. }
  1231. tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
  1232. *pname = tmpname;
  1233. XXXXXX = &tmpname[strlen (tmpbase)];
  1234. g_free (tmpbase);
  1235. /* Get some more or less random data. */
  1236. gettimeofday (&tv, NULL);
  1237. value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
  1238. for (count = 0; count < TMP_MAX; ++count)
  1239. {
  1240. unsigned long v = value;
  1241. int fd;
  1242. /* Fill in the random bits. */
  1243. XXXXXX[0] = letters[v % 62];
  1244. v /= 62;
  1245. XXXXXX[1] = letters[v % 62];
  1246. v /= 62;
  1247. XXXXXX[2] = letters[v % 62];
  1248. v /= 62;
  1249. XXXXXX[3] = letters[v % 62];
  1250. v /= 62;
  1251. XXXXXX[4] = letters[v % 62];
  1252. v /= 62;
  1253. XXXXXX[5] = letters[v % 62];
  1254. fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
  1255. if (fd >= 0)
  1256. {
  1257. /* Successfully created. */
  1258. return fd;
  1259. }
  1260. /* This is a random value. It is only necessary that the next
  1261. TMP_MAX values generated by adding 7777 to VALUE are different
  1262. with (module 2^32). */
  1263. value += 7777;
  1264. }
  1265. /* Unsuccessful. Free the filename. */
  1266. g_free (tmpname);
  1267. *pname = NULL;
  1268. return -1;
  1269. }
  1270. /*
  1271. * Read and restore position for the given filename.
  1272. * If there is no stored data, return line 1 and col 0.
  1273. */
  1274. void
  1275. load_file_position (const char *filename, long *line, long *column, off_t * offset)
  1276. {
  1277. char *fn;
  1278. FILE *f;
  1279. char buf[MC_MAXPATHLEN + 20];
  1280. int len;
  1281. /* defaults */
  1282. *line = 1;
  1283. *column = 0;
  1284. *offset = 0;
  1285. /* open file with positions */
  1286. fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
  1287. f = fopen (fn, "r");
  1288. g_free (fn);
  1289. if (!f)
  1290. return;
  1291. len = strlen (filename);
  1292. while (fgets (buf, sizeof (buf), f))
  1293. {
  1294. const char *p;
  1295. gchar **pos_tokens;
  1296. /* check if the filename matches the beginning of string */
  1297. if (strncmp (buf, filename, len) != 0)
  1298. continue;
  1299. /* followed by single space */
  1300. if (buf[len] != ' ')
  1301. continue;
  1302. /* and string without spaces */
  1303. p = &buf[len + 1];
  1304. if (strchr (p, ' '))
  1305. continue;
  1306. pos_tokens = g_strsplit_set (p, ";", 3);
  1307. if (pos_tokens[0] != NULL)
  1308. {
  1309. *line = strtol (pos_tokens[0], NULL, 10);
  1310. if (pos_tokens[1] != NULL)
  1311. {
  1312. *column = strtol (pos_tokens[1], NULL, 10);
  1313. if (pos_tokens[2] != NULL)
  1314. *offset = strtoll (pos_tokens[2], NULL, 10);
  1315. else
  1316. *offset = 0;
  1317. }
  1318. else
  1319. {
  1320. *column = 0;
  1321. *offset = 0;
  1322. }
  1323. }
  1324. else
  1325. {
  1326. *line = 1;
  1327. *column = 0;
  1328. *offset = 0;
  1329. }
  1330. g_strfreev (pos_tokens);
  1331. }
  1332. fclose (f);
  1333. }
  1334. /* Save position for the given file */
  1335. #define TMP_SUFFIX ".tmp"
  1336. void
  1337. save_file_position (const char *filename, long line, long column, off_t offset)
  1338. {
  1339. static int filepos_max_saved_entries = 0;
  1340. char *fn, *tmp_fn;
  1341. FILE *f, *tmp_f;
  1342. char buf[MC_MAXPATHLEN + 20];
  1343. int i = 1;
  1344. gsize len;
  1345. if (filepos_max_saved_entries == 0)
  1346. filepos_max_saved_entries =
  1347. mc_config_get_int (mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries",
  1348. 1024);
  1349. fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
  1350. if (fn == NULL)
  1351. goto early_error;
  1352. len = strlen (filename);
  1353. mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
  1354. /* open file */
  1355. f = fopen (fn, "w");
  1356. if (f == NULL)
  1357. goto open_target_error;
  1358. tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
  1359. tmp_f = fopen (tmp_fn, "r");
  1360. if (tmp_f == NULL)
  1361. goto open_source_error;
  1362. /* put the new record */
  1363. if (line != 1 || column != 0)
  1364. {
  1365. if (fprintf (f, "%s %ld;%ld;%llu\n", filename, line, column, (unsigned long long) offset) <
  1366. 0)
  1367. goto write_position_error;
  1368. }
  1369. while (fgets (buf, sizeof (buf), tmp_f))
  1370. {
  1371. if (buf[len] == ' ' && strncmp (buf, filename, len) == 0 && !strchr (&buf[len + 1], ' '))
  1372. continue;
  1373. fprintf (f, "%s", buf);
  1374. if (++i > filepos_max_saved_entries)
  1375. break;
  1376. }
  1377. fclose (tmp_f);
  1378. g_free (tmp_fn);
  1379. fclose (f);
  1380. mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
  1381. g_free (fn);
  1382. return;
  1383. write_position_error:
  1384. fclose (tmp_f);
  1385. open_source_error:
  1386. g_free (tmp_fn);
  1387. fclose (f);
  1388. mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
  1389. open_target_error:
  1390. g_free (fn);
  1391. early_error:
  1392. return;
  1393. }
  1394. #undef TMP_SUFFIX
  1395. extern const char *
  1396. cstrcasestr (const char *haystack, const char *needle)
  1397. {
  1398. char *nee = str_create_search_needle (needle, 0);
  1399. const char *result = str_search_first (haystack, nee, 0);
  1400. str_release_search_needle (nee, 0);
  1401. return result;
  1402. }
  1403. const char *
  1404. cstrstr (const char *haystack, const char *needle)
  1405. {
  1406. return strstr (haystack, needle);
  1407. }
  1408. extern char *
  1409. str_unconst (const char *s)
  1410. {
  1411. return (char *) s;
  1412. }
  1413. #define ASCII_A (0x40 + 1)
  1414. #define ASCII_Z (0x40 + 26)
  1415. #define ASCII_a (0x60 + 1)
  1416. #define ASCII_z (0x60 + 26)
  1417. extern int
  1418. ascii_alpha_to_cntrl (int ch)
  1419. {
  1420. if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
  1421. {
  1422. ch &= 0x1f;
  1423. }
  1424. return ch;
  1425. }
  1426. const char *
  1427. Q_ (const char *s)
  1428. {
  1429. const char *result, *sep;
  1430. result = _(s);
  1431. sep = strchr (result, '|');
  1432. return (sep != NULL) ? sep + 1 : result;
  1433. }
  1434. gboolean
  1435. mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
  1436. {
  1437. struct stat stat_buf;
  1438. char *backup_path;
  1439. gboolean ret;
  1440. if (!exist_file (file_name))
  1441. return FALSE;
  1442. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1443. if (backup_path == NULL)
  1444. return FALSE;
  1445. ret = mc_util_write_backup_content (file_name, backup_path);
  1446. if (ret)
  1447. {
  1448. /* Backup file will have same ownership with main file. */
  1449. if (stat (file_name, &stat_buf) == 0)
  1450. chmod (backup_path, stat_buf.st_mode);
  1451. else
  1452. chmod (backup_path, S_IRUSR | S_IWUSR);
  1453. }
  1454. g_free (backup_path);
  1455. return ret;
  1456. }
  1457. gboolean
  1458. mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
  1459. {
  1460. gboolean ret;
  1461. char *backup_path;
  1462. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1463. if (backup_path == NULL)
  1464. return FALSE;
  1465. ret = mc_util_write_backup_content (backup_path, file_name);
  1466. g_free (backup_path);
  1467. return ret;
  1468. }
  1469. gboolean
  1470. mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
  1471. {
  1472. char *backup_path;
  1473. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1474. if (backup_path == NULL)
  1475. return FALSE;
  1476. if (exist_file (backup_path))
  1477. mc_unlink (backup_path);
  1478. g_free (backup_path);
  1479. return TRUE;
  1480. }
  1481. /* partly taken from dcigettext.c, returns "" for default locale */
  1482. /* value should be freed by calling function g_free() */
  1483. char *
  1484. guess_message_value (void)
  1485. {
  1486. static const char *const var[] = {
  1487. /* Setting of LC_ALL overwrites all other. */
  1488. /* Do not use LANGUAGE for check user locale and drowing hints */
  1489. "LC_ALL",
  1490. /* Next comes the name of the desired category. */
  1491. "LC_MESSAGES",
  1492. /* Last possibility is the LANG environment variable. */
  1493. "LANG",
  1494. /* NULL exit loops */
  1495. NULL
  1496. };
  1497. unsigned i = 0;
  1498. const char *locale = NULL;
  1499. while (var[i] != NULL)
  1500. {
  1501. locale = getenv (var[i]);
  1502. if (locale != NULL && locale[0] != '\0')
  1503. break;
  1504. i++;
  1505. }
  1506. if (locale == NULL)
  1507. locale = "";
  1508. return g_strdup (locale);
  1509. }