EncodingScheme.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "benc/String.h"
  16. #include "benc/Dict.h"
  17. #include "memory/Allocator.h"
  18. #include "switch/EncodingScheme.h"
  19. #include "util/Bits.h"
  20. #include "util/Endian.h"
  21. #include "util/Hex.h"
  22. int EncodingScheme_getFormNum(struct EncodingScheme* scheme, uint64_t routeLabel)
  23. {
  24. if (scheme->count == 1) {
  25. return 0;
  26. }
  27. for (int i = 0; i < scheme->count; i++) {
  28. struct EncodingScheme_Form* form = &scheme->forms[i];
  29. Assert_true(form->prefixLen > 0 && form->prefixLen < 32);
  30. Assert_true(form->bitCount > 0 && form->bitCount < 32);
  31. if (0 == ((form->prefix ^ (uint32_t)routeLabel) << (32 - form->prefixLen))) {
  32. return i;
  33. }
  34. }
  35. return EncodingScheme_getFormNum_INVALID;
  36. }
  37. static bool is358(struct EncodingScheme* scheme)
  38. {
  39. struct EncodingScheme_Form v358[3] = {
  40. { .bitCount = 3, .prefixLen = 1, .prefix = 1, },
  41. { .bitCount = 5, .prefixLen = 2, .prefix = 1<<1, },
  42. { .bitCount = 8, .prefixLen = 2, .prefix = 0, }
  43. };
  44. if (scheme->count != 3) { return false; }
  45. for (int i = 0; i < 3; i++) {
  46. if (Bits_memcmp(&v358[i], &scheme->forms[i], sizeof(struct EncodingScheme_Form))) {
  47. return false;
  48. }
  49. }
  50. return true;
  51. }
  52. uint64_t EncodingScheme_convertLabel(struct EncodingScheme* scheme,
  53. uint64_t routeLabel,
  54. int convertTo)
  55. {
  56. int formNum = EncodingScheme_getFormNum(scheme, routeLabel);
  57. if (formNum == EncodingScheme_getFormNum_INVALID) {
  58. return EncodingScheme_convertLabel_INVALID;
  59. }
  60. struct EncodingScheme_Form* currentForm = &scheme->forms[formNum];
  61. if (scheme->count == 1
  62. || (routeLabel & Bits_maxBits64(currentForm->prefixLen + currentForm->bitCount)) == 1)
  63. {
  64. // fixed width encoding or it's a self label, this is easy
  65. switch (convertTo) {
  66. case 0:
  67. case EncodingScheme_convertLabel_convertTo_CANNONICAL: return routeLabel;
  68. default: return EncodingScheme_convertLabel_INVALID;
  69. }
  70. }
  71. routeLabel >>= currentForm->prefixLen;
  72. uint64_t director = routeLabel & Bits_maxBits64(currentForm->bitCount);
  73. routeLabel >>= currentForm->bitCount;
  74. // ACKTUNG: Magic afoot!
  75. // Conversions are necessary for two reasons.
  76. // #1 ensure 0001 always references interface 1, the self interface.
  77. // #2 reuse interface the binary encoding for interface 1 in other EncodingForms
  78. // because interface 1 cannot be expressed as anything other than 0001
  79. if (!is358(scheme)) {
  80. // don't pull this bug-workaround crap for sane encodings schemes.
  81. } else if ((currentForm->prefix & Bits_maxBits64(currentForm->prefixLen)) == 1) {
  82. // Swap 0 and 1 if the prefix is 1, this makes 0001 alias to 1
  83. // because 0 can never show up in the wild, we reuse it for 1.
  84. Assert_true(director != 0);
  85. if (director == 1) { director--; }
  86. } else if (director) {
  87. // Reuse the number 1 for 2 and 2 for 3 etc. to gain an extra slot in all other encodings.
  88. director++;
  89. }
  90. if (convertTo == EncodingScheme_convertLabel_convertTo_CANNONICAL) {
  91. // Take into account the fact that if the destination form does not have a 1 prefix,
  92. // an extra number will be available.
  93. int minBitsA = Bits_log2x64(director) + 1;
  94. int minBitsB = Bits_log2x64(director-1) + 1;
  95. for (int i = 0; i < scheme->count; i++) {
  96. struct EncodingScheme_Form* form = &scheme->forms[i];
  97. int minBits = ((form->prefix & Bits_maxBits64(form->prefixLen)) == 1)
  98. ? minBitsA : minBitsB;
  99. if (form->bitCount >= minBits) {
  100. convertTo = i;
  101. break;
  102. }
  103. }
  104. }
  105. if (convertTo < 0 || convertTo >= scheme->count) {
  106. // convertTo value is insane
  107. return EncodingScheme_convertLabel_INVALID;
  108. }
  109. struct EncodingScheme_Form* nextForm = &scheme->forms[convertTo];
  110. if (!is358(scheme)) {
  111. // don't pull this bug-workaround crap for sane encodings schemes.
  112. } else if ((nextForm->prefix & Bits_maxBits64(nextForm->prefixLen)) == 1) {
  113. // Swap 1 and 0 back if necessary.
  114. if (director == 0) { director++; }
  115. } else if (director) {
  116. // Or move the numbers down by one.
  117. director--;
  118. }
  119. if ((Bits_log2x64(director) + 1) > nextForm->bitCount) {
  120. // won't fit in requested form
  121. return EncodingScheme_convertLabel_INVALID;
  122. }
  123. if (Bits_log2x64(routeLabel) + EncodingScheme_formSize(nextForm) > 59) {
  124. return EncodingScheme_convertLabel_INVALID;
  125. }
  126. routeLabel <<= nextForm->bitCount;
  127. routeLabel |= director;
  128. routeLabel <<= nextForm->prefixLen;
  129. routeLabel |= nextForm->prefix;
  130. if ((routeLabel & Bits_maxBits64(nextForm->prefixLen + nextForm->bitCount)) == 1) {
  131. // looks like a self-route
  132. return EncodingScheme_convertLabel_INVALID;
  133. }
  134. return routeLabel;
  135. }
  136. /**
  137. * Decode a form from its binary representation.
  138. * Can only use a maximum of 41 bits.
  139. *
  140. * One or more of these binary representation are bitwise concatenated to
  141. * give an unsigned integer; which is encoded in **little endian** to give
  142. * the serialization of Encoding Scheme.
  143. *
  144. * Ten least significant bits of a form are:
  145. *
  146. * 1
  147. * 0 1 2 3 4 5 6 7 0 1
  148. * +-+-+-+-+-+-+-+-+-+-+
  149. * 0 | bitcount| preflen |
  150. * +-+-+-+-+-+-+-+-+-+-+
  151. *
  152. * Previous 'preflen' bits are the prefix
  153. *
  154. * @param out the output which will be populated with the encoding form data.
  155. * @param data the binary data in host order.
  156. * @return the number of bits of data which were consumed by the decoding.
  157. * If the content is definitely not an encoding form, 0 is returned.
  158. */
  159. static inline int decodeForm(struct EncodingScheme_Form* out, uint64_t d)
  160. {
  161. out->prefixLen = d & Bits_maxBits64(5);
  162. d >>= 5;
  163. int bitCount = d & Bits_maxBits64(5);
  164. if (bitCount < 1) {
  165. return 0;
  166. }
  167. out->bitCount = bitCount;
  168. d >>= 5;
  169. out->prefix = d & Bits_maxBits64(out->prefixLen);
  170. return 5 + 5 + out->prefixLen;
  171. }
  172. static inline int encodeForm(struct EncodingScheme_Form* in, uint64_t* data, int bits)
  173. {
  174. *data |= ((uint64_t)in->prefixLen & Bits_maxBits64(5)) << bits;
  175. bits += 5;
  176. *data |= ((uint64_t)in->bitCount & Bits_maxBits64(5)) << bits;
  177. bits += 5;
  178. *data |= ((uint64_t)in->prefix & Bits_maxBits64(in->prefixLen)) << bits;
  179. return 5 + 5 + in->prefixLen;
  180. }
  181. bool EncodingScheme_isSane(struct EncodingScheme* scheme)
  182. {
  183. // Check for obviously insane encoding.
  184. if (scheme->count == 0) {
  185. // No encoding schemes
  186. return false;
  187. }
  188. if (scheme->count > 31) {
  189. // impossible, each form must have a different bitCount and bitCount
  190. // can only be expressed in 5 bits limiting it to 31 bits max and a form
  191. // using zero bits is not allowed so there are only 31 max possibilities.
  192. return false;
  193. }
  194. if (scheme->count == 1) {
  195. // Fixed width encoding, prefix is not allowed and bitcount must be non-zero
  196. if (scheme->forms[0].prefixLen != 0 || scheme->forms[0].prefix != 0) {
  197. // prefixLen must be 0
  198. return false;
  199. }
  200. if (scheme->forms[0].bitCount == 0 || scheme->forms[0].bitCount > 31) {
  201. // bitcount must be non-zero and can't overflow the number
  202. return false;
  203. }
  204. return true;
  205. }
  206. // Variable width encoding.
  207. for (int i = 0; i < scheme->count; i++) {
  208. struct EncodingScheme_Form* form = &scheme->forms[i];
  209. if (form->prefixLen == 0 || form->prefixLen > 31) {
  210. // Prefix must exist in order to distinguish between forms
  211. return false;
  212. }
  213. if (form->bitCount == 0 || form->bitCount > 31) {
  214. // Bitcount must be non-zero
  215. return false;
  216. }
  217. if (EncodingScheme_formSize(form) > 59) {
  218. // cannot be represented in the usable space in a label
  219. return false;
  220. }
  221. if (i > 0 && form->bitCount <= scheme->forms[i-1].bitCount) {
  222. // Forms must be in ascending order.
  223. return false;
  224. }
  225. for (int j = 0; j < scheme->count; j++) {
  226. // Forms must be distinguishable by their prefixes.
  227. if (j != i
  228. && (scheme->forms[j].prefix & Bits_maxBits64(form->prefixLen)) == form->prefix)
  229. {
  230. return false;
  231. }
  232. }
  233. }
  234. return true;
  235. }
  236. List* EncodingScheme_asList(struct EncodingScheme* list, struct Allocator* alloc)
  237. {
  238. Assert_ifParanoid(EncodingScheme_isSane(list));
  239. List* scheme = List_new(alloc);
  240. for (int i = (int)list->count - 1; i >= 0; i--) {
  241. Dict* form = Dict_new(alloc);
  242. Dict_putIntC(form, "prefixLen", list->forms[i].prefixLen, alloc);
  243. Dict_putIntC(form, "bitCount", list->forms[i].bitCount, alloc);
  244. if (list->forms[i].prefixLen == 0) {
  245. Dict_putStringCC(form, "prefix", "", alloc);
  246. } else {
  247. String* pfx = String_newBinary(NULL, 8, alloc);
  248. uint32_t prefix_be = Endian_hostToBigEndian32(list->forms[i].prefix);
  249. Hex_encode(pfx->bytes, 8, (uint8_t*)&prefix_be, 4);
  250. while (pfx->bytes[0] == '0' && pfx->len > 2) {
  251. pfx->bytes += 2;
  252. pfx->len -= 2;
  253. }
  254. Dict_putStringC(form, "prefix", pfx, alloc);
  255. }
  256. List_addDict(scheme, form, alloc);
  257. }
  258. return scheme;
  259. }
  260. struct EncodingScheme* EncodingScheme_fromList(List* scheme, struct Allocator* alloc)
  261. {
  262. struct EncodingScheme* list = Allocator_malloc(alloc, sizeof(struct EncodingScheme));
  263. list->count = List_size(scheme);
  264. list->forms = Allocator_malloc(alloc, sizeof(struct EncodingScheme_Form) * list->count);
  265. for (int i = 0; i < (int)list->count; i++) {
  266. Dict* form = List_getDict(scheme, i);
  267. uint64_t* prefixLen = Dict_getIntC(form, "prefixLen");
  268. uint64_t* bitCount = Dict_getIntC(form, "bitCount");
  269. String* prefixStr = Dict_getStringC(form, "prefix");
  270. if (!prefixLen || !bitCount || !prefixStr || prefixStr->len != 8) {
  271. return NULL;
  272. }
  273. uint32_t prefix_be;
  274. if (Hex_decode((uint8_t*)&prefix_be, 4, prefixStr->bytes, 8) != 4) {
  275. return NULL;
  276. }
  277. list->forms[i].prefixLen = *prefixLen;
  278. list->forms[i].bitCount = *bitCount;
  279. list->forms[i].prefix = Endian_bigEndianToHost32(prefix_be);
  280. }
  281. if (!EncodingScheme_isSane(list)) {
  282. return NULL;
  283. }
  284. return list;
  285. }
  286. String* EncodingScheme_serialize(struct EncodingScheme* list,
  287. struct Allocator* alloc)
  288. {
  289. Assert_ifParanoid(EncodingScheme_isSane(list));
  290. // Create the string as the largest that is possible for the list size.
  291. String* out = String_newBinary(NULL, list->count * 6, alloc);
  292. int bits = 0;
  293. int outIndex = 0;
  294. uint64_t block = 0;
  295. for (int listIndex = 0; listIndex < (int)list->count; listIndex++) {
  296. bits += encodeForm(&list->forms[listIndex], &block, bits);
  297. while (bits > 8) {
  298. Assert_true(outIndex < (int)out->len);
  299. out->bytes[outIndex++] = (uint8_t) (block & 0xff);
  300. bits -= 8;
  301. block >>= 8;
  302. }
  303. }
  304. if (bits > 0) {
  305. out->bytes[outIndex++] = (uint8_t) (block & 0xff);
  306. }
  307. out->len = outIndex;
  308. return out;
  309. }
  310. struct EncodingScheme* EncodingScheme_deserialize(String* data,
  311. struct Allocator* alloc)
  312. {
  313. struct EncodingScheme_Form* forms = NULL;
  314. int outCount = 0;
  315. uint64_t block = 0;
  316. int bits = 0;
  317. int dataIndex = 0;
  318. for (;;) {
  319. // load data into the block from the incoming data source
  320. while (bits < 56 && dataIndex < (int)data->len) {
  321. block |= (((uint64_t)data->bytes[dataIndex++] & 0xff) << bits);
  322. bits += 8;
  323. }
  324. struct EncodingScheme_Form next;
  325. int ret = decodeForm(&next, block);
  326. bits -= ret;
  327. if (!ret || bits < 0) {
  328. if (block || dataIndex < (int)data->len || bits < 0) {
  329. // Invalid encoding
  330. return NULL;
  331. }
  332. break;
  333. }
  334. block >>= ret;
  335. Assert_true((next.prefix >> next.prefixLen) == 0);
  336. outCount += 1;
  337. forms = Allocator_realloc(alloc, forms, outCount * sizeof(struct EncodingScheme_Form));
  338. Bits_memcpy(&forms[outCount-1], &next, sizeof(struct EncodingScheme_Form));
  339. }
  340. struct EncodingScheme* out = Allocator_clone(alloc, (&(struct EncodingScheme) {
  341. .forms = forms,
  342. .count = outCount
  343. }));
  344. return EncodingScheme_isSane(out) ? out : NULL;
  345. }
  346. struct EncodingScheme* EncodingScheme_defineFixedWidthScheme(int bitCount, struct Allocator* alloc)
  347. {
  348. struct NumberCompress_FixedWidthScheme
  349. {
  350. struct EncodingScheme scheme;
  351. struct EncodingScheme_Form form;
  352. };
  353. struct NumberCompress_FixedWidthScheme* out =
  354. Allocator_malloc(alloc, sizeof(struct NumberCompress_FixedWidthScheme));
  355. struct NumberCompress_FixedWidthScheme scheme = {
  356. .scheme = { .count = 1, .forms = &out->form },
  357. .form = { .bitCount = bitCount, .prefixLen = 0, .prefix = 0, },
  358. };
  359. Bits_memcpy(out, &scheme, sizeof(struct NumberCompress_FixedWidthScheme));
  360. Assert_true(EncodingScheme_isSane(&out->scheme));
  361. return &out->scheme;
  362. }
  363. struct EncodingScheme* EncodingScheme_defineDynWidthScheme(struct EncodingScheme_Form* forms,
  364. int formCount,
  365. struct Allocator* alloc)
  366. {
  367. struct EncodingScheme_Form* formsCopy =
  368. Allocator_malloc(alloc, sizeof(struct EncodingScheme_Form) * formCount);
  369. Bits_memcpy(formsCopy, forms, sizeof(struct EncodingScheme_Form) * formCount);
  370. struct EncodingScheme* scheme = Allocator_clone(alloc, (&(struct EncodingScheme) {
  371. .count = formCount,
  372. .forms = formsCopy
  373. }));
  374. Assert_ifParanoid(EncodingScheme_isSane(scheme));
  375. return scheme;
  376. }
  377. int EncodingScheme_compare(struct EncodingScheme* a, struct EncodingScheme* b)
  378. {
  379. if (a->count == b->count) {
  380. return Bits_memcmp(a->forms, b->forms, sizeof(struct EncodingScheme_Form) * a->count);
  381. }
  382. return a->count > b->count ? 1 : -1;
  383. }
  384. /**
  385. * Return true if the route is to the switch's router interface.
  386. */
  387. int EncodingScheme_isSelfRoute(struct EncodingScheme* scheme, uint64_t routeLabel)
  388. {
  389. int formNum = EncodingScheme_getFormNum(scheme, routeLabel);
  390. if (formNum == EncodingScheme_getFormNum_INVALID) {
  391. return 0;
  392. }
  393. struct EncodingScheme_Form* currentForm = &scheme->forms[formNum];
  394. return (routeLabel & Bits_maxBits64(currentForm->prefixLen + currentForm->bitCount)) == 1;
  395. }
  396. int EncodingScheme_isOneHop(struct EncodingScheme* scheme, uint64_t routeLabel)
  397. {
  398. int fn = EncodingScheme_getFormNum(scheme, routeLabel);
  399. if (fn == EncodingScheme_getFormNum_INVALID) { return 0; }
  400. struct EncodingScheme_Form* form = &scheme->forms[fn];
  401. return (Bits_log2x64(routeLabel) == form->prefixLen + form->bitCount);
  402. }