wildcard.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Wildcard matching engine for use with SFTP-based file transfer
  3. * programs (PSFTP, new-look PSCP): since SFTP has no notion of
  4. * getting the remote side to do globbing (and rightly so) we have
  5. * to do it locally, by retrieving all the filenames in a directory
  6. * and checking each against the wildcard pattern.
  7. */
  8. #include <assert.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include "putty.h"
  12. /*
  13. * Definition of wildcard syntax:
  14. *
  15. * - * matches any sequence of characters, including zero.
  16. * - ? matches exactly one character which can be anything.
  17. * - [abc] matches exactly one character which is a, b or c.
  18. * - [a-f] matches anything from a through f.
  19. * - [^a-f] matches anything _except_ a through f.
  20. * - [-_] matches - or _; [^-_] matches anything else. (The - is
  21. * non-special if it occurs immediately after the opening
  22. * bracket or ^.)
  23. * - [a^] matches an a or a ^. (The ^ is non-special if it does
  24. * _not_ occur immediately after the opening bracket.)
  25. * - \*, \?, \[, \], \\ match the single characters *, ?, [, ], \.
  26. * - All other characters are non-special and match themselves.
  27. */
  28. /*
  29. * Some notes on differences from POSIX globs (IEEE Std 1003.1, 2003 ed.):
  30. * - backslashes act as escapes even within [] bracket expressions
  31. * - does not support [!...] for non-matching list (POSIX are weird);
  32. * NB POSIX allows [^...] as well via "A bracket expression starting
  33. * with an unquoted circumflex character produces unspecified
  34. * results". If we wanted to allow [!...] we might want to define
  35. * [^!] as having its literal meaning (match '^' or '!').
  36. * - none of the scary [[:class:]] stuff, etc
  37. */
  38. /*
  39. * The wildcard matching technique we use is very simple and
  40. * potentially O(N^2) in running time, but I don't anticipate it
  41. * being that bad in reality (particularly since N will be the size
  42. * of a filename, which isn't all that much). Perhaps one day, once
  43. * PuTTY has grown a regexp matcher for some other reason, I might
  44. * come back and reimplement wildcards by translating them into
  45. * regexps or directly into NFAs; but for the moment, in the
  46. * absence of any other need for the NFA->DFA translation engine,
  47. * anything more than the simplest possible wildcard matcher is
  48. * vast code-size overkill.
  49. *
  50. * Essentially, these wildcards are much simpler than regexps in
  51. * that they consist of a sequence of rigid fragments (? and [...]
  52. * can never match more or less than one character) separated by
  53. * asterisks. It is therefore extremely simple to look at a rigid
  54. * fragment and determine whether or not it begins at a particular
  55. * point in the test string; so we can search along the string
  56. * until we find each fragment, then search for the next. As long
  57. * as we find each fragment in the _first_ place it occurs, there
  58. * will never be a danger of having to backpedal and try to find it
  59. * again somewhere else.
  60. */
  61. enum {
  62. WC_TRAILINGBACKSLASH = 1,
  63. WC_UNCLOSEDCLASS,
  64. WC_INVALIDRANGE
  65. };
  66. /*
  67. * Error reporting is done by returning various negative values
  68. * from the wildcard routines. Passing any such value to wc_error
  69. * will give a human-readable message.
  70. */
  71. const char *wc_error(int value)
  72. {
  73. value = abs(value);
  74. switch (value) {
  75. case WC_TRAILINGBACKSLASH:
  76. return "'\' occurred at end of string (expected another character)";
  77. case WC_UNCLOSEDCLASS:
  78. return "expected ']' to close character class";
  79. case WC_INVALIDRANGE:
  80. return "character range was not terminated (']' just after '-')";
  81. }
  82. return "INTERNAL ERROR: unrecognised wildcard error number";
  83. }
  84. /*
  85. * This is the routine that tests a target string to see if an
  86. * initial substring of it matches a fragment. If successful, it
  87. * returns 1, and advances both `fragment' and `target' past the
  88. * fragment and matching substring respectively. If unsuccessful it
  89. * returns zero. If the wildcard fragment suffers a syntax error,
  90. * it returns <0 and the precise value indexes into wc_error.
  91. */
  92. static int wc_match_fragment(const char **fragment, const char **target,
  93. const char *target_end)
  94. {
  95. const char *f, *t;
  96. f = *fragment;
  97. t = *target;
  98. /*
  99. * The fragment terminates at either the end of the string, or
  100. * the first (unescaped) *.
  101. */
  102. while (*f && *f != '*' && t < target_end) {
  103. /*
  104. * Extract one character from t, and one character's worth
  105. * of pattern from f, and step along both. Return 0 if they
  106. * fail to match.
  107. */
  108. if (*f == '\\') {
  109. /*
  110. * Backslash, which means f[1] is to be treated as a
  111. * literal character no matter what it is. It may not
  112. * be the end of the string.
  113. */
  114. if (!f[1])
  115. return -WC_TRAILINGBACKSLASH; /* error */
  116. if (f[1] != *t)
  117. return 0; /* failed to match */
  118. f += 2;
  119. } else if (*f == '?') {
  120. /*
  121. * Question mark matches anything.
  122. */
  123. f++;
  124. } else if (*f == '[') {
  125. bool invert = false;
  126. bool matched = false;
  127. /*
  128. * Open bracket introduces a character class.
  129. */
  130. f++;
  131. if (*f == '^') {
  132. invert = true;
  133. f++;
  134. }
  135. while (*f != ']') {
  136. if (*f == '\\')
  137. f++; /* backslashes still work */
  138. if (!*f)
  139. return -WC_UNCLOSEDCLASS; /* error again */
  140. if (f[1] == '-') {
  141. int lower, upper, ourchr;
  142. lower = (unsigned char) *f++;
  143. f++; /* eat the minus */
  144. if (*f == ']')
  145. return -WC_INVALIDRANGE; /* different error! */
  146. if (*f == '\\')
  147. f++; /* backslashes _still_ work */
  148. if (!*f)
  149. return -WC_UNCLOSEDCLASS; /* error again */
  150. upper = (unsigned char) *f++;
  151. ourchr = (unsigned char) *t;
  152. if (lower > upper) {
  153. int t = lower; lower = upper; upper = t;
  154. }
  155. if (ourchr >= lower && ourchr <= upper)
  156. matched = true;
  157. } else {
  158. matched |= (*t == *f++);
  159. }
  160. }
  161. if (invert == matched)
  162. return 0; /* failed to match character class */
  163. f++; /* eat the ] */
  164. } else {
  165. /*
  166. * Non-special character matches itself.
  167. */
  168. if (*f != *t)
  169. return 0;
  170. f++;
  171. }
  172. /*
  173. * Now we've done that, increment t past the character we
  174. * matched.
  175. */
  176. t++;
  177. }
  178. if (!*f || *f == '*') {
  179. /*
  180. * We have reached the end of f without finding a mismatch;
  181. * so we're done. Update the caller pointers and return 1.
  182. */
  183. *fragment = f;
  184. *target = t;
  185. return 1;
  186. }
  187. /*
  188. * Otherwise, we must have reached the end of t before we
  189. * reached the end of f; so we've failed. Return 0.
  190. */
  191. return 0;
  192. }
  193. /*
  194. * This is the real wildcard matching routine. It returns 1 for a
  195. * successful match, 0 for an unsuccessful match, and <0 for a
  196. * syntax error in the wildcard.
  197. */
  198. static int wc_match_inner(
  199. const char *wildcard, const char *target, size_t target_len)
  200. {
  201. const char *target_end = target + target_len;
  202. int ret;
  203. /*
  204. * Every time we see a '*' _followed_ by a fragment, we just
  205. * search along the string for a location at which the fragment
  206. * matches. The only special case is when we see a fragment
  207. * right at the start, in which case we just call the matching
  208. * routine once and give up if it fails.
  209. */
  210. if (*wildcard != '*') {
  211. ret = wc_match_fragment(&wildcard, &target, target_end);
  212. if (ret <= 0)
  213. return ret; /* pass back failure or error alike */
  214. }
  215. while (*wildcard) {
  216. assert(*wildcard == '*');
  217. while (*wildcard == '*')
  218. wildcard++;
  219. /*
  220. * It's possible we've just hit the end of the wildcard
  221. * after seeing a *, in which case there's no need to
  222. * bother searching any more because we've won.
  223. */
  224. if (!*wildcard)
  225. return 1;
  226. /*
  227. * Now `wildcard' points at the next fragment. So we
  228. * attempt to match it against `target', and if that fails
  229. * we increment `target' and try again, and so on. When we
  230. * find we're about to try matching against the empty
  231. * string, we give up and return 0.
  232. */
  233. ret = 0;
  234. while (*target) {
  235. const char *save_w = wildcard, *save_t = target;
  236. ret = wc_match_fragment(&wildcard, &target, target_end);
  237. if (ret < 0)
  238. return ret; /* syntax error */
  239. if (ret > 0 && !*wildcard && target != target_end) {
  240. /*
  241. * Final special case - literally.
  242. *
  243. * This situation arises when we are matching a
  244. * _terminal_ fragment of the wildcard (that is,
  245. * there is nothing after it, e.g. "*a"), and it
  246. * has matched _too early_. For example, matching
  247. * "*a" against "parka" will match the "a" fragment
  248. * against the _first_ a, and then (if it weren't
  249. * for this special case) matching would fail
  250. * because we're at the end of the wildcard but not
  251. * at the end of the target string.
  252. *
  253. * In this case what we must do is measure the
  254. * length of the fragment in the target (which is
  255. * why we saved `target'), jump straight to that
  256. * distance from the end of the string using
  257. * strlen, and match the same fragment again there
  258. * (which is why we saved `wildcard'). Then we
  259. * return whatever that operation returns.
  260. */
  261. target = target_end - (target - save_t);
  262. wildcard = save_w;
  263. return wc_match_fragment(&wildcard, &target, target_end);
  264. }
  265. if (ret > 0)
  266. break;
  267. target++;
  268. }
  269. if (ret > 0)
  270. continue;
  271. return 0;
  272. }
  273. /*
  274. * If we reach here, it must be because we successfully matched
  275. * a fragment and then found ourselves right at the end of the
  276. * wildcard. Hence, we return 1 if and only if we are also
  277. * right at the end of the target.
  278. */
  279. return target == target_end;
  280. }
  281. int wc_match(const char *wildcard, const char *target)
  282. {
  283. return wc_match_inner(wildcard, target, strlen(target));
  284. }
  285. int wc_match_pl(const char *wildcard, ptrlen target)
  286. {
  287. return wc_match_inner(wildcard, target.ptr, target.len);
  288. }
  289. /*
  290. * Another utility routine that translates a non-wildcard string
  291. * into its raw equivalent by removing any escaping backslashes.
  292. * Expects a target string buffer of anything up to the length of
  293. * the original wildcard. You can also pass NULL as the output
  294. * buffer if you're only interested in the return value.
  295. *
  296. * Returns true on success, or false if a wildcard character was
  297. * encountered. In the latter case the output string MAY not be
  298. * zero-terminated and you should not use it for anything!
  299. */
  300. bool wc_unescape(char *output, const char *wildcard)
  301. {
  302. while (*wildcard) {
  303. if (*wildcard == '\\') {
  304. wildcard++;
  305. /* We are lenient about trailing backslashes in non-wildcards. */
  306. if (*wildcard) {
  307. if (output)
  308. *output++ = *wildcard;
  309. wildcard++;
  310. }
  311. } else if (*wildcard == '*' || *wildcard == '?' ||
  312. *wildcard == '[' || *wildcard == ']') {
  313. return false; /* it's a wildcard! */
  314. } else {
  315. if (output)
  316. *output++ = *wildcard;
  317. wildcard++;
  318. }
  319. }
  320. if (output)
  321. *output = '\0';
  322. return true; /* it's clean */
  323. }
  324. #ifdef TEST
  325. struct test {
  326. const char *wildcard;
  327. const char *target;
  328. int expected_result;
  329. };
  330. const struct test fragment_tests[] = {
  331. /*
  332. * We exhaustively unit-test the fragment matching routine
  333. * itself, which should save us the need to test all its
  334. * intricacies during the full wildcard tests.
  335. */
  336. {"abc", "abc", 1},
  337. {"abc", "abd", 0},
  338. {"abc", "abcd", 1},
  339. {"abcd", "abc", 0},
  340. {"ab[cd]", "abc", 1},
  341. {"ab[cd]", "abd", 1},
  342. {"ab[cd]", "abe", 0},
  343. {"ab[^cd]", "abc", 0},
  344. {"ab[^cd]", "abd", 0},
  345. {"ab[^cd]", "abe", 1},
  346. {"ab\\", "abc", -WC_TRAILINGBACKSLASH},
  347. {"ab\\*", "ab*", 1},
  348. {"ab\\?", "ab*", 0},
  349. {"ab?", "abc", 1},
  350. {"ab?", "ab", 0},
  351. {"ab[", "abc", -WC_UNCLOSEDCLASS},
  352. {"ab[c-", "abb", -WC_UNCLOSEDCLASS},
  353. {"ab[c-]", "abb", -WC_INVALIDRANGE},
  354. {"ab[c-e]", "abb", 0},
  355. {"ab[c-e]", "abc", 1},
  356. {"ab[c-e]", "abd", 1},
  357. {"ab[c-e]", "abe", 1},
  358. {"ab[c-e]", "abf", 0},
  359. {"ab[e-c]", "abb", 0},
  360. {"ab[e-c]", "abc", 1},
  361. {"ab[e-c]", "abd", 1},
  362. {"ab[e-c]", "abe", 1},
  363. {"ab[e-c]", "abf", 0},
  364. {"ab[^c-e]", "abb", 1},
  365. {"ab[^c-e]", "abc", 0},
  366. {"ab[^c-e]", "abd", 0},
  367. {"ab[^c-e]", "abe", 0},
  368. {"ab[^c-e]", "abf", 1},
  369. {"ab[^e-c]", "abb", 1},
  370. {"ab[^e-c]", "abc", 0},
  371. {"ab[^e-c]", "abd", 0},
  372. {"ab[^e-c]", "abe", 0},
  373. {"ab[^e-c]", "abf", 1},
  374. {"ab[a^]", "aba", 1},
  375. {"ab[a^]", "ab^", 1},
  376. {"ab[a^]", "abb", 0},
  377. {"ab[^a^]", "aba", 0},
  378. {"ab[^a^]", "ab^", 0},
  379. {"ab[^a^]", "abb", 1},
  380. {"ab[-c]", "ab-", 1},
  381. {"ab[-c]", "abc", 1},
  382. {"ab[-c]", "abd", 0},
  383. {"ab[^-c]", "ab-", 0},
  384. {"ab[^-c]", "abc", 0},
  385. {"ab[^-c]", "abd", 1},
  386. {"ab[\\[-\\]]", "abZ", 0},
  387. {"ab[\\[-\\]]", "ab[", 1},
  388. {"ab[\\[-\\]]", "ab\\", 1},
  389. {"ab[\\[-\\]]", "ab]", 1},
  390. {"ab[\\[-\\]]", "ab^", 0},
  391. {"ab[^\\[-\\]]", "abZ", 1},
  392. {"ab[^\\[-\\]]", "ab[", 0},
  393. {"ab[^\\[-\\]]", "ab\\", 0},
  394. {"ab[^\\[-\\]]", "ab]", 0},
  395. {"ab[^\\[-\\]]", "ab^", 1},
  396. {"ab[a-fA-F]", "aba", 1},
  397. {"ab[a-fA-F]", "abF", 1},
  398. {"ab[a-fA-F]", "abZ", 0},
  399. };
  400. const struct test full_tests[] = {
  401. {"a", "argh", 0},
  402. {"a", "ba", 0},
  403. {"a", "a", 1},
  404. {"a*", "aardvark", 1},
  405. {"a*", "badger", 0},
  406. {"*a", "park", 0},
  407. {"*a", "pArka", 1},
  408. {"*a", "parka", 1},
  409. {"*a*", "park", 1},
  410. {"*a*", "perk", 0},
  411. {"?b*r?", "abracadabra", 1},
  412. {"?b*r?", "abracadabr", 0},
  413. {"?b*r?", "abracadabzr", 0},
  414. };
  415. int main(void)
  416. {
  417. int i;
  418. int fails, passes;
  419. fails = passes = 0;
  420. for (i = 0; i < sizeof(fragment_tests)/sizeof(*fragment_tests); i++) {
  421. const char *f, *t;
  422. int eret, aret;
  423. f = fragment_tests[i].wildcard;
  424. t = fragment_tests[i].target;
  425. eret = fragment_tests[i].expected_result;
  426. aret = wc_match_fragment(&f, &t, t + strlen(t));
  427. if (aret != eret) {
  428. printf("failed test: /%s/ against /%s/ returned %d not %d\n",
  429. fragment_tests[i].wildcard, fragment_tests[i].target,
  430. aret, eret);
  431. fails++;
  432. } else
  433. passes++;
  434. }
  435. for (i = 0; i < sizeof(full_tests)/sizeof(*full_tests); i++) {
  436. const char *f, *t;
  437. int eret, aret;
  438. f = full_tests[i].wildcard;
  439. t = full_tests[i].target;
  440. eret = full_tests[i].expected_result;
  441. aret = wc_match(f, t);
  442. if (aret != eret) {
  443. printf("failed test: /%s/ against /%s/ returned %d not %d\n",
  444. full_tests[i].wildcard, full_tests[i].target,
  445. aret, eret);
  446. fails++;
  447. } else
  448. passes++;
  449. }
  450. printf("passed %d, failed %d\n", passes, fails);
  451. return 0;
  452. }
  453. #endif /* TEST */