1
0

mnemonic.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /* mnemonic.c
  2. Copyright (c) 2000 Oren Tirosh <oren@hishome.net>
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #include <ctype.h>
  20. #include <string.h>
  21. #include "mnemonic.h"
  22. /*
  23. * mn_words_required
  24. *
  25. * Description:
  26. * Calculate the number of words required to encode data using mnemonic
  27. * encoding.
  28. *
  29. * Parameters:
  30. * size - Size in bytes of data to be encoded
  31. *
  32. * Return value:
  33. * number of words required for the encoding
  34. */
  35. int
  36. mn_words_required (int size)
  37. {
  38. return ((size + 1) * 3) / 4;
  39. }
  40. /*
  41. * mn_encode_word_index
  42. *
  43. * Description:
  44. * Perform one step of encoding binary data into words. Returns word index.
  45. *
  46. * Parameters:
  47. * src - Pointer to data buffer to encode
  48. * srcsize - Size in bytes of data to encode
  49. * n - Sequence number of word to encode
  50. * 0 <= n < mn_words_required(srcsize)
  51. *
  52. * Return value:
  53. * 0 - no more words to encode / n is out of range
  54. * 1..MN_WORDS - word index. May be used as index to the mn_words[] array
  55. */
  56. mn_index mn_encode_word_index (void *vsrc, int srcsize, int n)
  57. {
  58. mn_word32 x = 0; /* Temporary for MN_BASE arithmetic */
  59. int offset; /* Offset into src */
  60. int remaining; /* Octets remaining to end of src */
  61. int extra = 0; /* Index 7 extra words for 24 bit data */
  62. int i;
  63. mn_byte *src = vsrc;
  64. if (n < 0 || n >= mn_words_required (srcsize))
  65. return 0; /* word out of range */
  66. offset = (n / 3) * 4; /* byte offset into src */
  67. remaining = srcsize - offset;
  68. if (remaining <= 0)
  69. return 0;
  70. if (remaining >= 4)
  71. remaining = 4;
  72. for (i = 0; i < remaining; i++)
  73. x |= (unsigned long)src[offset + i] << (i * 8); /* endianness-agnostic */
  74. switch (n % 3)
  75. {
  76. case 2: /* Third word of group */
  77. if (remaining == 3) /* special case for 24 bits */
  78. extra = MN_BASE; /* use one of the 7 3-letter words */
  79. x /= (MN_BASE * MN_BASE);
  80. break;
  81. case 1: /* Second word of group */
  82. x /= MN_BASE;
  83. }
  84. return x % MN_BASE + extra + 1;
  85. }
  86. /*
  87. * mn_encode_word
  88. *
  89. * Description:
  90. * Perform one step of encoding binary data into words. Returns pointer
  91. * to word.
  92. *
  93. * Parameters:
  94. * src - Pointer to data buffer to encode
  95. * srcsize - Size of data to encode in bytes
  96. * n - Sequence number of word to encode.
  97. * 0 <= n < mn_words_required(srcsize)
  98. *
  99. * Return value:
  100. * NULL - no more words to encode / n is out of range
  101. * valid pointer - pointer to null-terminated lowercase word. length<=7
  102. */
  103. const char *
  104. mn_encode_word (void *src, int srcsize, int n)
  105. {
  106. return mn_words[mn_encode_word_index (src, srcsize, n)];
  107. }
  108. /*
  109. * mn_next_word_index
  110. *
  111. * Description:
  112. * Perform one step of decoding a null-terminated buffer into word indices.
  113. * A word is defined as a sequence of letter character separated by one
  114. * or more non-letter separator characters.
  115. *
  116. * Parameters:
  117. * ptr - Pointer to a pointer to the next character in the buffer.
  118. * *ptr is modified by the function; see Return Value below.
  119. *
  120. * Return value:
  121. * 0 - If *ptr==0 (points to the null at the end of the buffer) no more
  122. * words were found in the buffer. Otherwise *ptr points to beginning
  123. * of an unrecognized word.
  124. * >0 - index of word found, suitable for decoding with mn_decode_word_index
  125. * or comparison to values returned from mn_encode_index. *ptr points
  126. * to first character of next word or to terminating null.
  127. */
  128. mn_index
  129. mn_next_word_index (char **ptr)
  130. {
  131. char *wordstart;
  132. char wordbuf[MN_WORD_BUFLEN];
  133. int i = 0;
  134. char c;
  135. mn_index idx;
  136. while (**ptr && !isalpha (**ptr)) /* skip separator chars */
  137. (*ptr)++;
  138. wordstart = *ptr; /* save for error reporting */
  139. while (**ptr && isalpha (**ptr) && i < MN_WORD_BUFLEN - 1)
  140. {
  141. c = *(*ptr)++;
  142. if (c >= 'A' && c <= 'Z')
  143. c += 'a' - 'A'; /* convert to lowercase */
  144. wordbuf[i++] = c;
  145. }
  146. wordbuf[i] = '\0';
  147. while (**ptr && isalpha (**ptr)) /* skip tail of long words */
  148. (*ptr)++;
  149. while (**ptr && !isalpha (**ptr)) /* skip separators */
  150. (*ptr)++;
  151. if (wordbuf[0] == '\0')
  152. return 0; /* EOF, no word found */
  153. for (idx = 1; idx <= MN_WORDS; idx++)
  154. {
  155. if (!strcmp (wordbuf, mn_words[idx]))
  156. return idx;
  157. /* FIXME: some fancy code should go here
  158. to accept misspellings and soundalikes.
  159. (replacing the linear search would also be nice) */
  160. }
  161. *ptr = wordstart;
  162. return 0; /* not found */
  163. }
  164. /*
  165. * mn_decode_word_index
  166. *
  167. * Description:
  168. * Perform one step of decoding a sequence of words into binary data.
  169. *
  170. * Parameters:
  171. * index - Index of word, e.g. return value of mn_next_word_index. Use
  172. * the value MN_EOF(=0) to signal the end of input.
  173. * dest - Points to buffer to receive decoded binary result.
  174. * destsize - Size of buffer
  175. * offset - Pointer to an integer offset into the destination buffer for
  176. * next data byte. Initialize *offset to 0 before first call to
  177. * function. Modified by function and may be used as an
  178. * indication for the amount of data actually decoded.
  179. *
  180. * Return value:
  181. * The return value indicates the status of the decoding function. It is
  182. * ok to ignore this value on all calls to the function except the last
  183. * one (with index=MN_EOF). Any errors encountered will be reported on.
  184. * the last call. The error code is also returned in *offset (negative
  185. * values indicate error).
  186. *
  187. * MN_OK (==0)
  188. * for index!=MN_EOF a return value of MN_OK means that
  189. * decoding has been successful so far.
  190. * for index==MN_EOF a return value of MN_OK means that decoding
  191. * of the entire buffer has been successful and the decoder is in
  192. * a valid state for the end of the message. A total of *offset
  193. * valid decoded bytes is in the buffer.
  194. * MN_EREM
  195. * returned on MN_EOF when an unaccounted arithmetic remainder is
  196. * in the decoder. Most likely indicates a truncated word sequence.
  197. * MN_EOVERRUN
  198. * Not enough room in buffer for decoded data.
  199. * MN_EOVERRUN24
  200. * Returned when decoding of data is attempted after decoding one
  201. * of the 7 words reserved for 24 bit remainders at the end of the
  202. * message. Probably indicates a garbled messages.
  203. * MN_EINDEX
  204. * Bad input index. Naturally this should not happen when using
  205. * the result of mn_next_word_index.
  206. * MN_EINDEX24
  207. * Returned when one of the 7 words reserved for 24 bit remainders
  208. * is received at an offset inappropriate for a 24 bit remainder.
  209. * MN_EENCODING
  210. * Indicates an overflow in MN_BASE arithmetic. Approximately 0.09%
  211. * of the 3 word combinations are unused and will generate this error.
  212. */
  213. int
  214. mn_decode_word_index (mn_index index, void *vdest, int destsize, int *offset)
  215. {
  216. mn_word32 x; /* Temporary for MN_BASE arithmetic */
  217. int groupofs;
  218. int i;
  219. mn_byte *dest = vdest;
  220. if (*offset < 0) /* Error from previous call? report it */
  221. return *offset;
  222. if (index > MN_WORDS) /* Word index out of range */
  223. {
  224. *offset = MN_EINDEX;
  225. return *offset;
  226. }
  227. if (*offset > destsize) /* out of range? */
  228. {
  229. *offset = MN_EOVERRUN;
  230. return *offset;
  231. }
  232. if (index > MN_BASE && *offset % 4 != 2)
  233. { /* Unexpected 24 bit remainder word */
  234. *offset = MN_EINDEX24;
  235. return *offset;
  236. }
  237. groupofs = *offset & ~3; /* Offset of 4 byte group containing offet */
  238. x = 0;
  239. for (i = 0; i < 4; i++)
  240. if (groupofs + i < destsize) /* Ignore any bytes outside buffer */
  241. x |= (unsigned long)dest[groupofs + i] << (i * 8); /* assemble number */
  242. if (index == MN_EOF) /* Got EOF signal */
  243. {
  244. switch (*offset % 4)
  245. {
  246. case 3: /* group was three words and the last */
  247. return MN_OK; /* word was a 24 bit remainder */
  248. case 2: /* last group has two words */
  249. if (x <= 0xFFFF) /* should encode 16 bit data */
  250. return MN_OK;
  251. else
  252. {
  253. *offset = MN_EREM;
  254. return *offset;
  255. }
  256. case 1: /* last group has just one word */
  257. if (x <= 0xFF) /* should encode 8 bits */
  258. return MN_OK;
  259. else
  260. {
  261. *offset = MN_EREM;
  262. return *offset;
  263. }
  264. case 0: /* last group was full 3 words */
  265. return MN_OK;
  266. }
  267. }
  268. if (*offset == destsize) /* At EOF but didn't get MN_EOF */
  269. {
  270. *offset = MN_EOVERRUN;
  271. return *offset;
  272. }
  273. index--; /* 1 based to 0 based index */
  274. switch (*offset % 4)
  275. {
  276. case 3: /* Got data past 24 bit remainder */
  277. *offset = MN_EOVERRUN24;
  278. return *offset;
  279. case 2:
  280. if (index >= MN_BASE)
  281. { /* 24 bit remainder */
  282. x += (index - MN_BASE) * MN_BASE * MN_BASE;
  283. (*offset)++; /* *offset%4 == 3 for next time */
  284. }
  285. else
  286. { /* catch invalid encodings */
  287. if (index >= 1625 || (index == 1624 && x > 1312671))
  288. {
  289. *offset = MN_EENCODING;
  290. return *offset;
  291. }
  292. x += index * MN_BASE * MN_BASE;
  293. (*offset) += 2; /* *offset%4 == 0 for next time */
  294. }
  295. break;
  296. case 1:
  297. x += index * MN_BASE;
  298. (*offset)++;
  299. break;
  300. case 0:
  301. x = index;
  302. (*offset)++;
  303. break;
  304. }
  305. for (i = 0; i < 4; i++)
  306. if (groupofs + i < destsize) /* Don't step outside the buffer */
  307. {
  308. dest[groupofs + i] = (mn_byte) x % 256;
  309. x /= 256;
  310. }
  311. return MN_OK;
  312. }
  313. /*
  314. * mn_encode
  315. *
  316. * Description:
  317. * Encode a binary data buffer into a null-terminated sequence of words.
  318. * The word separators are taken from the format string.
  319. *
  320. * Parameters:
  321. * src - Pointer to the beginning of the binary data buffer.
  322. * srcsize - Size in bytes of binary data buffer
  323. * dest - Pointer to the beginning of a character buffer
  324. * destsize - Size in characters of character buffer
  325. * format - Null-terminated string describing the output format.
  326. * In the format string any letter or sequence of letters
  327. * acts as a placeholder for the encoded words. The word
  328. * placeholders are separated by one or more non-letter
  329. * characters. When the encoder reaches the end of the
  330. * format string it starts reading it again.
  331. * For sample formats see MN_F* constants in mnemonic.h
  332. * If format is empty or NULL the format MN_FDEFAULT
  333. * is used.
  334. *
  335. * Return value:
  336. * MN_OK(=0)
  337. * Encoding was successful.
  338. * MN_EOVERRUN
  339. * Output size exceeds size of destination buffer
  340. * MN_EFORMAT
  341. * Invalid format string. This function enforces formats which
  342. * will result in a string which can be successfully decoded by
  343. * the mn_decode function.
  344. */
  345. int
  346. mn_encode (void *src, int srcsize, char *dest, int destsize, char *format)
  347. {
  348. int n;
  349. char *fmt;
  350. char *destend = dest + destsize;
  351. const char *word;
  352. if (format == 0 || format[0] == '\0')
  353. format = MN_FDEFAULT;
  354. fmt = format;
  355. for (n = 0; n < mn_words_required (srcsize); n++)
  356. {
  357. while (dest < destend && *fmt != '\0' && !isalpha (*fmt))
  358. *dest++ = *fmt++;
  359. if (dest >= destend)
  360. return MN_EOVERRUN;
  361. if (*fmt == '\0')
  362. {
  363. if (isalpha (fmt[-1]) && isalpha (format[0]))
  364. return MN_EFORMAT;
  365. fmt = format;
  366. while (dest < destend && *fmt != '\0' && !isalpha (*fmt))
  367. *dest++ = *fmt++;
  368. if (!isalpha (*fmt))
  369. return MN_EFORMAT;
  370. }
  371. word = mn_encode_word (src, srcsize, n);
  372. if (word == 0)
  373. return MN_EOVERRUN; /* shouldn't happen, actually */
  374. while (isalpha (*fmt))
  375. fmt++;
  376. while (dest < destend && *word != '\0')
  377. *dest++ = *word++;
  378. }
  379. if (dest < destend)
  380. *dest++ = '\0';
  381. else
  382. return MN_EOVERRUN;
  383. return MN_OK;
  384. }
  385. /*
  386. * mn_decode
  387. *
  388. * Description:
  389. * Decode a text representation in null-terminated character buffer src to
  390. * binary buffer dest.
  391. *
  392. * Parameters:
  393. * src - Pointer to null-terminated character buffer
  394. * dest - Pointer to beginning of destination buffer
  395. * destsize - Size in bytes of destination buffer
  396. *
  397. * Return value:
  398. * This function may return all the value returned by mn_decode_word_index
  399. * plus the following result code:
  400. *
  401. * MN_EWORD - Unrecognized word.
  402. */
  403. int
  404. mn_decode (char *src, void *dest, int destsize)
  405. {
  406. mn_index index;
  407. int offset = 0;
  408. int status;
  409. while ((index = mn_next_word_index (&src)) != 0)
  410. {
  411. (void) mn_decode_word_index (index, dest, destsize, &offset);
  412. }
  413. if (*src != 0)
  414. return MN_EWORD;
  415. status = mn_decode_word_index (MN_EOF, dest, destsize, &offset);
  416. if (status < 0)
  417. return status;
  418. return offset;
  419. }