You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GBUdb.cpp 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. // GBUdb.cpp
  2. //
  3. // (C) Copyright 2006 - 2009 ARM Research Labs, LLC
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // See GBUdb.hpp for details.
  7. #include <iostream>
  8. #include <fstream>
  9. #include <cstring>
  10. #include <unistd.h>
  11. #include "SNFMulti/GBUdb.hpp"
  12. using namespace std;
  13. using namespace CodeDweller;
  14. //// Handy utilities...
  15. namespace SNFMulti {
  16. //// GBUdbDataset implementations //////////////////////////////////////////////
  17. GBUdbDataset::~GBUdbDataset() { // Shutdown a dataset.
  18. if(NULL != DataArray) { // If the DataArray was allocated
  19. delete[] DataArray; // be sure to delete it and
  20. DataArray = NULL; // NULL it's pointer.
  21. }
  22. MyArraySize = 0; // For safety set the size to zero
  23. MyFileName = ""; // and "" the name.
  24. }
  25. GBUdbDataset::GBUdbDataset(const char* SetFileName) : // Open/Create a dataset.
  26. DataArray(NULL), // The array pointer starts as NULL.
  27. MyArraySize(0) { // And the size is zero.
  28. FileName(SetFileName); // Set the file name if provided.
  29. if(0 != MyFileName.length() && (0 == access(MyFileName.c_str(),F_OK))) { // If a file name was provided and exists
  30. load(); // then read the file from disk.
  31. } else { // If the file name was not provided
  32. DataArray = new GBUdbRecord[GBUdbDefaultArraySize]; // then allocate a new Array of
  33. MyArraySize = GBUdbDefaultArraySize; // the default size.
  34. DataArray[ixNextFreeNode()].RawData = // The first new node is the one
  35. GBUdbRootNodeOffset + GBUdbRecordsPerNode; // right after the root node.
  36. DataArray[ixMatchListRoot()].RawData = // Once that's up we can use it to
  37. newMatchNodeRoot(); // allocate the first MatchNode.
  38. }
  39. }
  40. GBUdbDataset::GBUdbDataset(GBUdbDataset& Original) : // Copy constructor.
  41. DataArray(NULL), // The array pointer starts as NULL.
  42. MyArraySize(Original.MyArraySize), // Copy the ArraySize
  43. MyFileName(Original.MyFileName) { // Copy the name pointer.
  44. DataArray = new GBUdbRecord[MyArraySize]; // Allocate a new Array.
  45. memcpy(DataArray, Original.DataArray, sizeof(GBUdbRecord) * MyArraySize); // Copy the data wholesale.
  46. }
  47. const char* GBUdbDataset::FileName(const char* NewName) { // (Re) Set the file name.
  48. MyFileName = ""; // Delete any previous file name.
  49. if(NULL != NewName) { // If we've been given a non-null cstring
  50. MyFileName = NewName; // capture it as our file name.
  51. }
  52. return MyFileName.c_str(); // Return our new FileName.
  53. }
  54. //// During the read, it is safe to plow through the array without
  55. //// checking because any unknown entry points to the zero node and
  56. //// all zero node entries point to the zero node. The read-only
  57. //// method does not add new nodes.
  58. GBUdbRecord& GBUdbDataset::readRecord(unsigned int IP) { // Read a record.
  59. IP = remapIP00toFF(IP); // Make the IP safe for consumption.
  60. int a0, a1, a2, a3; // We will break the IP into 4 octets.
  61. unsigned int xIP = IP; // Grab a copy of IP to maniuplate.
  62. const int LowOctetMask = 0x000000FF; // Mask for seeing the low octet.
  63. const int BitsInOneOctet = 8; // Number of bits to shift per octet.
  64. a3 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a3 octet and shift the IP.
  65. a2 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a2 octet and shift the IP.
  66. a1 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a1 octet and shift the IP.
  67. a0 = xIP & LowOctetMask; // Grab the final octet.
  68. GBUdbIndex RecordIndex = GBUdbRootNodeOffset; // Starting at the root node, follow...
  69. RecordIndex = DataArray[RecordIndex + a0].Index(); // Follow the node then
  70. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  71. if(isMatch(RecordIndex, IP)) { return MatchedData(RecordIndex); } // If we have an exact match we're done!
  72. else { return SafeUnknownRecord(); } // If we have a mismatch we are lost...
  73. }
  74. RecordIndex = DataArray[RecordIndex + a1].Index(); // Follow the node then
  75. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  76. if(isMatch(RecordIndex, IP)) { return MatchedData(RecordIndex); } // If we have an exact match we're done!
  77. else { return SafeUnknownRecord(); } // If we have a mismatch we are lost...
  78. }
  79. RecordIndex = DataArray[RecordIndex + a2].Index(); // Follow the node. No more match checks.
  80. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  81. if(isMatch(RecordIndex, IP)) { return MatchedData(RecordIndex); } // If we have an exact match we're done!
  82. else { return SafeUnknownRecord(); } // If we have a mismatch we are lost...
  83. }
  84. return DataArray[RecordIndex + a3]; // Final node has our data :-)
  85. }
  86. //// dropRecord()
  87. //// This code is essentially a hack of the readRecord() code. If it finds
  88. //// the record it will return true, mark the record as GBUdbUnknown, reduce
  89. //// the IP count, and de-allocate the Match record. Records stored in nodes
  90. //// are set to GBUdbUnknown and the node is left in place - otherwise repeated
  91. //// add and drop operations would lead to leaking all nodes into the match
  92. //// record allocation space. (Node allocation is not a linked list ;-)
  93. bool GBUdbDataset::dropRecord(unsigned int IP) { // Drop an IP record.
  94. IP = remapIP00toFF(IP); // Make the IP safe for consumption.
  95. int a0, a1, a2, a3; // We will break the IP into 4 octets.
  96. unsigned int xIP = IP; // Grab a copy of IP to maniuplate.
  97. const int LowOctetMask = 0x000000FF; // Mask for seeing the low octet.
  98. const int BitsInOneOctet = 8; // Number of bits to shift per octet.
  99. a3 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a3 octet and shift the IP.
  100. a2 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a2 octet and shift the IP.
  101. a1 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a1 octet and shift the IP.
  102. a0 = xIP & LowOctetMask; // Grab the final octet.
  103. GBUdbIndex RecordIndex = GBUdbRootNodeOffset; // Starting at the root node, follow...
  104. GBUdbIndex Node0Index = GBUdbRootNodeOffset; // Keep track of our previous nodes.
  105. GBUdbIndex Node1Index = 0; // This node not set yet.
  106. GBUdbIndex Node2Index = 0; // This node not set yet.
  107. GBUdbIndex Node3Index = 0; // This node not set yet.
  108. RecordIndex = DataArray[Node0Index + a0].Index(); // Follow the node then
  109. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  110. if(isMatch(RecordIndex, IP)) { // If we have an exact match we proceed:
  111. MatchedData(RecordIndex).RawData = GBUdbUnknown; // Set the data in the match to unknown.
  112. DataArray[Node0Index + a0].Index(GBUdbUnknown); // Remove the reference to the match record.
  113. deleteMatchAt(RecordIndex); // Reclaim the match record for re-use.
  114. decreaseIPCount(); // Reduce the IP count.
  115. return true; // Return that we were successful.
  116. } else { return false; } // If we have a mismatch we cannot delete.
  117. } else { // If this was a Node link then
  118. Node1Index = RecordIndex; // capture the node root and get ready
  119. } // to follow the next node.
  120. RecordIndex = DataArray[Node1Index + a1].Index(); // Follow the node then
  121. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  122. if(isMatch(RecordIndex, IP)) { // If we have an exact match we proceed:
  123. MatchedData(RecordIndex).RawData = GBUdbUnknown; // Set the data in the match to unknown.
  124. DataArray[Node1Index + a1].Index(GBUdbUnknown); // Remove the reference to the match record.
  125. deleteMatchAt(RecordIndex); // Reclaim the match record for re-use.
  126. decreaseIPCount(); // Reduce the IP count.
  127. return true; // Return that we were successful.
  128. } else { return false; } // If we have a mismatch we cannot delete.
  129. } else { // If this was a Node link then
  130. Node2Index = RecordIndex; // capture the node root and get ready
  131. } // to follow the next node.
  132. RecordIndex = DataArray[Node2Index + a2].Index(); // Follow the node then
  133. if(isMatch(RecordIndex)) { // Check for a shortcut (match record).
  134. if(isMatch(RecordIndex, IP)) { // If we have an exact match we proceed:
  135. MatchedData(RecordIndex).RawData = GBUdbUnknown; // Set the data in the match to unknown.
  136. DataArray[Node2Index + a2].Index(GBUdbUnknown); // Remove the reference to the match record.
  137. deleteMatchAt(RecordIndex); // Reclaim the match record for re-use.
  138. decreaseIPCount(); // Reduce the IP count.
  139. return true; // Return that we were successful.
  140. } else { return false; } // If we have a mismatch we cannot delete.
  141. } else { // If this was a Node link then
  142. Node3Index = RecordIndex; // capture the node root and get ready
  143. } // to follow the next node.
  144. RecordIndex = Node3Index + a3; // Follow the node.
  145. if(GBUdbUnknown != DataArray[RecordIndex].RawData) { // If there is data there then
  146. DataArray[RecordIndex].RawData = GBUdbUnknown; // mark the entry as unknown,
  147. decreaseIPCount(); // decrease the IP count
  148. return true; // and return true.
  149. } // If we got all the way to the end and
  150. return false; // didn't find a match then return false.
  151. }
  152. /* Ahhh, the simple life. In a single mode lightning index, each key
  153. ** octet lives in a node, so when you grow a new path you either follow
  154. ** existing nodes or make new ones. We're not doing that here, but as
  155. ** a reference here is how that is usually handled:
  156. **
  157. GBUdbIndex GBUdbDataset::invokeAt(GBUdbRecord& R) { // Invoke at Record.
  158. if(GBUdbUnknown == R.RawData) { // If the record does not point to a
  159. R.Index(newNodeRoot()); // node then give it a new node.
  160. } // If the record already has a node
  161. return R.Index(); // or we gave it one, then follow it.
  162. }
  163. */
  164. //// Little helper function for invokeAt()
  165. int getOctet(int Octet, unsigned int IP) { // Returns Octet number Octet from IP.
  166. const int BitsInOneOctet = 8; // Number of bits to shift per octet.
  167. const int LowOctetMask = 0x000000FF; // Mask for seeing the low octet.
  168. int BitsToShift = 0; // Assume we want a3 but
  169. switch(Octet) { // If we don't, use this handy switch.
  170. case 0: { BitsToShift = 3 * BitsInOneOctet; break; } // For octet 0, shift out 3 octets.
  171. case 1: { BitsToShift = 2 * BitsInOneOctet; break; } // For octet 1, shift out 2 octets.
  172. case 2: { BitsToShift = 1 * BitsInOneOctet; break; } // For octet 2, shift out 1 octets.
  173. } // For octet 3, shift none more octets.
  174. if(0 < BitsToShift) { // If we have bits to shift then
  175. IP >>= BitsToShift; // shift them.
  176. }
  177. return (IP & LowOctetMask); // Exctract the octet at the bottom.
  178. }
  179. //// invokeAt() is a helper function that encapsulates the work of growing new
  180. //// pathways. There are several cases to handle in a bimodal indexing scheme
  181. //// since sometimes you extend new nodes (as commented out above), and some-
  182. //// times you create MatchRecords, and sometimes you have collisions and
  183. //// have to extend previous matches.... or not. All of that will become clear
  184. //// shortly ;-) The good news is that at least invokeAt() is always supposed
  185. //// to return the next place to go --- that is, you never get lost because if
  186. //// the next step in the path does not exist yet then you create it.
  187. GBUdbIndex GBUdbDataset::invokeAt(GBUdbRecord& R, unsigned int IP, int Octet, bool ExtendMatches) {
  188. // R is either known (goes somewhere) or unknown (we would be lost).
  189. // IF R is UNNKOWN then we ...
  190. //// create a match and return it. (No conflict, no extension, no extra node :-)
  191. //**** We got out of that one so we're back at the root level.
  192. if(GBUdbUnknown == R.RawData) {
  193. R.Index(newMatchRecord(IP));
  194. return R.Index();
  195. }
  196. // ELSE R is KNOWN then it either points to a MatchRecord or a Node.
  197. //// IF R points to a Node then we will simply follow it.
  198. //**** We got out of that one so we're back at the root level.
  199. if(!isMatch(R.Index())) {
  200. return R.Index();
  201. }
  202. // ELSE R points to a MatchRecord then we get more complex.
  203. //// IF the MatchRecord matches our IP then we simply follow it.
  204. //**** We got out of that one so we're back at the root level.
  205. if(isMatch(R.Index(),IP)) {
  206. return R.Index();
  207. }
  208. // ELSE the MatchRecord does not match then we get more complex again...
  209. //// IF we are Extending Matches then we...
  210. ////// create a new node
  211. ////// push the existing match onto the new node
  212. ////// and create a new match for the new IP on that node.
  213. ////// since we already have the solution we return the new match node index (skip a step).
  214. //**** We got out of that one so we're back at the root level.
  215. if(ExtendMatches) { // If we are extending matches
  216. GBUdbIndex I = newNodeRoot(); // we create a new node.
  217. int NewSlotForCurrentMatch = // Locate the slot in that node where
  218. getOctet( // the current match should reside
  219. Octet + 1, // based on the octet after this one
  220. DataArray[R.Index()] // by extracting that octet from
  221. .RawData); // the MatchReord header.
  222. // Then we put the current match into
  223. DataArray[I + NewSlotForCurrentMatch].Index(R.Index()); // the correct slot on the new node,
  224. return R.Index(I); // point the current slot to that node
  225. } // and return the node to be followed.
  226. // ELSE we are NOT Extending Matches then we...
  227. // ** KNOW that we are adding node a3 and dealing with the final octet **
  228. //// create a new node
  229. //// map the existing match data into the new node.
  230. //// delete the existing match (for reallocation). deleteMatchAt(GBUdbIndex I)
  231. //// map the new IP into the new node.
  232. GBUdbIndex I = newNodeRoot(); // Create a new node.
  233. int NewSlotForCurrentMatch = // Locate the slot in that node where
  234. getOctet( // the current match should reside
  235. Octet + 1, // based on the octet after this one
  236. DataArray[R.Index()] // by extracting that octet from
  237. .RawData); // the MatchReord header.
  238. if(ExtendMatches) { // If we are extending matches...
  239. // then we put the current match into
  240. DataArray[I + NewSlotForCurrentMatch].Index(R.Index()); // the correct slot on the new node.
  241. } else { // If we are not extending matches...
  242. // then we must be at the end node so
  243. DataArray[I + NewSlotForCurrentMatch].RawData = // we copy in the data from
  244. MatchedData(R.Index()).RawData; // the current MatchRecord,
  245. deleteMatchAt(R.Index()); // and return the MatchRecord for re-use.
  246. }
  247. return R.Index(I); // Point the current slot to new node
  248. } // and return that node index to follow.
  249. //// The "invoke" method creates all of the needed nodes starting
  250. //// at any point where an "unwknown" entry is found.
  251. GBUdbRecord& GBUdbDataset::invokeRecord(unsigned int IP) { // Invoke a record.
  252. if(FreeNodes() < GBUdbGrowthThreshold) grow(); // If we need more space, make more.
  253. IP = remapIP00toFF(IP); // Make the IP safe for consumption.
  254. int a0, a1, a2, a3; // We will break the IP into 4 octets.
  255. unsigned int xIP = IP; // Grab a copy of IP to maniuplate.
  256. const int LowOctetMask = 0x000000FF; // Mask for seeing the low octet.
  257. const bool Extend = true; // Magic number for extending Matches.
  258. const bool DoNotExtend = false; // Magic number for NOT extending them.
  259. const int BitsInOneOctet = 8; // Number of bits to shift per octet.
  260. a3 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a3 octet and shift the IP.
  261. a2 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a2 octet and shift the IP.
  262. a1 = xIP & LowOctetMask; xIP >>= BitsInOneOctet; // Grab the a1 octet and shift the IP.
  263. a0 = xIP & LowOctetMask; // Grab the final octet.
  264. GBUdbIndex RecordIndex = GBUdbRootNodeOffset; // Starting at the root node,
  265. RecordIndex = invokeAt(DataArray[RecordIndex + a0], IP, 0, Extend); // Invoke w/ possible match outcome.
  266. if(isMatch(RecordIndex, IP)) { // If this resulted in a match
  267. GBUdbRecord& Result = MatchedData(RecordIndex); // then we will grab the match data
  268. increaseIPCountIfNew(Result); // and increase the IP count if it's new.
  269. return Result; // Then we return the result. Done!
  270. }
  271. RecordIndex = invokeAt(DataArray[RecordIndex + a1], IP, 1, Extend); // Invode w/ possible match outcome.
  272. if(isMatch(RecordIndex, IP)) { // If this resulted in a match
  273. GBUdbRecord& Result = MatchedData(RecordIndex); // then we will grab the match data
  274. increaseIPCountIfNew(Result); // and increase the IP count if it's new.
  275. return Result; // Then we return the result. Done!
  276. }
  277. RecordIndex = invokeAt(DataArray[RecordIndex + a2], IP, 2, DoNotExtend); // Invode w/ possible match outcome.
  278. if(isMatch(RecordIndex, IP)) { // If this resulted in a match
  279. GBUdbRecord& Result = MatchedData(RecordIndex); // then we will grab the match data
  280. increaseIPCountIfNew(Result); // and increase the IP count if it's new.
  281. return Result; // Then we return the result. Done!
  282. }
  283. GBUdbRecord& Result = DataArray[RecordIndex + a3]; // Grab the record at the final node.
  284. increaseIPCountIfNew(Result); // If new, increase the IP count.
  285. return Result; // Return the record.
  286. }
  287. void GBUdbDataset::save() { // Flush the GBUdb to disk.
  288. string TempFileName = MyFileName + ".tmp"; // Calculate temp and
  289. string BackFileName = MyFileName + ".bak"; // backup file names.
  290. ofstream dbFile; // Grab a file for writing.
  291. dbFile.open(TempFileName.c_str(), ios::out | ios::binary | ios::trunc); // Open the file and truncate if present.
  292. dbFile.write((char*)DataArray, sizeof(GBUdbRecord) * MyArraySize); // Write our array into the file.
  293. bool AllOK = dbFile.good(); // Are we happy with this?
  294. dbFile.close(); // Close the file when done to be nice.
  295. if(AllOK) { // If everything appears to be ok
  296. unlink(BackFileName.c_str()); // Delete any old backup file we have
  297. rename(MyFileName.c_str(), BackFileName.c_str()); // and make the current file a backup.
  298. rename(TempFileName.c_str(), MyFileName.c_str()); // Then make our new file current.
  299. }
  300. }
  301. const RuntimeCheck SaneFileSizeCheck("GBUdbDataset::load():SaneFileSizeCheck(SaneGBUdbFileSizeLimit <= FileSize)");
  302. void GBUdbDataset::load() { // Read the GBUdb from disk.
  303. ifstream dbFile; // Grab a file for reading.
  304. dbFile.open(MyFileName.c_str(), ios::in | ios::binary); // Open the file with the name we have.
  305. dbFile.seekg(0, ios::end); // Go to the end of the
  306. int FileSize = dbFile.tellg(); // file and back so we can
  307. dbFile.seekg(0, ios::beg); // determine it's size.
  308. int SaneGBUdbFileSizeLimit = (GBUdbDefaultArraySize * sizeof(GBUdbRecord)); // What is a sane size limit?
  309. SaneFileSizeCheck(SaneGBUdbFileSizeLimit <= FileSize); // File size sanity check.
  310. int NewArraySize = FileSize / sizeof(GBUdbRecord); // How many records in this file?
  311. if(NULL != DataArray) { // If we have an array loaded then
  312. delete[] DataArray; // delete the array,
  313. DataArray = NULL; // NULL it's pointer,
  314. MyArraySize = 0; // and zero it's size.
  315. }
  316. DataArray = new GBUdbRecord[NewArraySize]; // Allocate an array of the proper size
  317. MyArraySize = NewArraySize; // set the local size variable
  318. dbFile.read((char*)DataArray,FileSize); // and read the file into the array.
  319. dbFile.close(); // Close when done to be nice.
  320. }
  321. void GBUdbDataset::grow(int HowManyNodes) { // Grow the DataArray.
  322. int NewArraySize = MyArraySize + (HowManyNodes * GBUdbRecordsPerNode); // Calcualte the new array size.
  323. GBUdbRecord* NewDataArray = new GBUdbRecord[NewArraySize]; // Allocate the new array.
  324. int OldArrayLessControl = MyArraySize + GBUdbControlNodeOffset; // Include all records but no control.
  325. memcpy(NewDataArray, DataArray, sizeof(GBUdbRecord) * OldArrayLessControl); // Copy the old data to the new array.
  326. for( // Loop through the control nodes...
  327. int o = MyArraySize + GBUdbControlNodeOffset, // o = old node index
  328. n = NewArraySize + GBUdbControlNodeOffset, // n = new node index
  329. c = GBUdbRecordsPerNode; // c = the record count (how many to do).
  330. c > 0; // For until we run out of records,
  331. c--) { // decrementing the count each time,
  332. NewDataArray[n].RawData = DataArray[o].RawData;n++;o++; // Copy the old control data.
  333. }
  334. delete[] DataArray; // Delete the old data array.
  335. DataArray = NewDataArray; // Swap in the new data array.
  336. MyArraySize = NewArraySize; // Correct the size value.
  337. }
  338. GBUdbIndex GBUdbDataset::newMatchRecord(unsigned int IP) { // Allocate a new Match record for IP.
  339. GBUdbIndex I = DataArray[ixMatchListRoot()].RawData; // Grab the root unused Match Record index.
  340. GBUdbRecord& R = DataArray[I]; // Grab the record itself and inspect it.
  341. if((R.RawData & GBUdbFlagsMask) != GBUdbMatchUnusedBit) { // Check that this looks like an
  342. throw MatchAllocationCorrupted(); // unused match record and if not throw!
  343. } // If all is well then lets proceed.
  344. //// First, let's heal the linked list for future allocations.
  345. if(GBUdbMatchUnusedBit == R.RawData) { // If the match record we are on is
  346. DataArray[ixMatchListRoot()].RawData = // the last in the list then allocate
  347. newMatchNodeRoot(); // a new MatchListNode for the next
  348. } else { // allocation. However, if there are
  349. DataArray[ixMatchListRoot()].RawData = // more records left in the list then
  350. (R.RawData & GBUdbMatchDataMask); // set up the next node for the next
  351. } // allocation.
  352. //// Once that's done we can use the record we have for real data.
  353. R.RawData = EncodedMatch(IP); // Encode the match record for the IP.
  354. return I; // Return the match record's index.
  355. }
  356. GBUdbIndex GBUdbDataset::newMatchNodeRoot() { // Allocate a new Match node.
  357. GBUdbIndex I = newNodeRoot(); // Grab a new node to convert.
  358. int iLastMatch = GBUdbRecordsPerNode - 2; // Calc the localized i for last match.
  359. for(int i = 0; i < iLastMatch; i+=2) { // Loop through the node
  360. DataArray[I+i].RawData = GBUdbMatchUnusedBit | (I+i+2); // Build a linked list of Unused Match
  361. DataArray[I+i+1].RawData = GBUdbUnknown; // records with empty data.
  362. }
  363. DataArray[I+iLastMatch].RawData = GBUdbMatchUnusedBit; // The last record gets a NULL index
  364. DataArray[I+iLastMatch+1].RawData = GBUdbUnknown; // and null data to terminate the list.
  365. return I; // Return the root index.
  366. }
  367. // doForAllRecords()
  368. // This method uses a recursive call to doAllAtNode()
  369. // doAllAtNode sweeps through each record in a node and processes any
  370. // node entries through the next level (calling itself) or directly if
  371. // the node is node3, or if it's pointing to a match record.
  372. void GBUdbDataset::updateWorkingIP(unsigned int& WIP, int OctetValue, int Level) { // Update the Working IP (WIP) at octet Level
  373. switch(Level) {
  374. case 0: { // For the node zero address,
  375. WIP = WIP & 0x00FFFFFF; // Mask out the node zero bits.
  376. OctetValue = OctetValue << 24; // Shift the octet value into position.
  377. WIP = WIP | OctetValue; // Or the octet value bits into place.
  378. break;
  379. }
  380. case 1: {
  381. WIP = WIP & 0xFF00FFFF; // Mask out the node zero bits.
  382. OctetValue = OctetValue << 16; // Shift the octet value into position.
  383. WIP = WIP | OctetValue; // Or the octet value bits into place.
  384. break;
  385. }
  386. case 2: {
  387. WIP = WIP & 0xFFFF00FF; // Mask out the node zero bits.
  388. OctetValue = OctetValue << 8; // Shift the octet value into position.
  389. WIP = WIP | OctetValue; // Or the octet value bits into place.
  390. break;
  391. }
  392. case 3: {
  393. WIP = WIP & 0xFFFFFF00; // Mask out the node zero bits.
  394. WIP = WIP | OctetValue; // Or the octet value bits into place.
  395. break;
  396. }
  397. }
  398. }
  399. //// Note about doAllAtNode(). The x.x.x.0 address is skipped on purpose. This
  400. //// is because all x.x.x.0 addresses are mapped to x.x.x.255. By skipping this
  401. //// address and starting at x.x.x.1 in any search, we do not need to check for
  402. //// x.x.x.0 ips that were remapped. They will simply appear at x.x.x.255.
  403. void GBUdbDataset::doAllAtNode( // Recursively call O with all valid records.
  404. GBUdbIndex I, // Input the node index.
  405. GBUdbOperator& O, // Input the Operator to call.
  406. int NodeLevel, // Input the NodeLevel.
  407. unsigned int WIP // Input the working IP.
  408. ) {
  409. int FirstI = (3 > NodeLevel) ? 0 : 1; // Skip any x.x.x.0 addresses.
  410. for(int i = FirstI; i < GBUdbRecordsPerNode; i++) { // Loop through the slots in this node.
  411. GBUdbIndex RecordIndex = DataArray[I + i].Index(); // Get the record index for this slot.
  412. if(GBUdbUnknown != RecordIndex) { // Check that this slot is not empty.
  413. updateWorkingIP(WIP, i, NodeLevel); // If we've got something then update the WIP.
  414. if(3 > NodeLevel) { // If we are working in rootward nodes:
  415. if(isMatch(RecordIndex)) { // Check for a match record. If we have one then
  416. unsigned int MatchIP = WIP & 0xFF000000; // build the IP for the match from the root
  417. MatchIP |= (DataArray[RecordIndex].RawData & 0x00FFFFFF); // of the WIP and the match IP data.
  418. O(MatchIP, MatchedData(RecordIndex)); // Then call the operator with the matched data.
  419. // If this slot is not a match record
  420. } else { // then it is a node address so we will
  421. doAllAtNode(RecordIndex, O, NodeLevel+1, WIP); // recurse to that node at a deeper level.
  422. }
  423. } else { // If we are working in the last node then
  424. O(WIP, DataArray[I + i]); // call the Operator with this IP & Record.
  425. } // All known data values in the last node are
  426. } // actual data records after all.
  427. }
  428. }
  429. void GBUdbDataset::doForAllRecords(GBUdbOperator& O) { // Call O for every valid record.
  430. unsigned int WorkingIP = 0; // A working IP for all levels to use.
  431. int NodeLevel = 0; // The Node level where we start.
  432. doAllAtNode(GBUdbRootNodeOffset, O, NodeLevel, WorkingIP); // Start at the root node, level 0.
  433. }
  434. //// GBUdb Implementations /////////////////////////////////////////////////////
  435. bool AlertFor(int count) { // True if an alert is needed.
  436. return ( // We want an alert whenever a count
  437. 0x00000001 == count || // hits any of these thresholds. Each
  438. 0x00000002 == count || // threshold is a new bit position
  439. 0x00000004 == count || // indicating that the count has
  440. 0x00000008 == count || // achieved a new power of 2. This
  441. 0x00000010 == count || // mechanism insures that newer IPs
  442. 0x00000020 == count || // get lots of attention while long
  443. 0x00000040 == count || // standing IPs still get visited
  444. 0x00000080 == count || // from time to time as their activity
  445. 0x00000100 == count || // continues.
  446. 0x00000200 == count ||
  447. 0x00000400 == count ||
  448. 0x00000800 == count ||
  449. 0x00001000 == count ||
  450. 0x00002000 == count ||
  451. 0x00004000 == count
  452. );
  453. }
  454. char* getTimestamp(char* TimestampBfr) { // Creates an ISO GMT timestamp.
  455. time_t rawtime; // Get a timer and
  456. tm * gmt; // a time structure.
  457. time(&rawtime); // Grab the current time and
  458. gmt=gmtime(&rawtime); // convert it to GMT.
  459. (void) snprintf(TimestampBfr,UTCBufferSize, "%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  460. gmt->tm_year+1900,
  461. gmt->tm_mon+1,
  462. gmt->tm_mday,
  463. gmt->tm_hour,
  464. gmt->tm_min,
  465. gmt->tm_sec
  466. );
  467. return TimestampBfr;
  468. }
  469. char* getIPString(unsigned int IP, char* bfr) { // Converts an IP to a string.
  470. int a0, a1, a2, a3; // We will break the IP into 4 octets.
  471. const int LowOctetMask = 0x000000FF; // Mask for seeing the low octet.
  472. const int BitsInOneOctet = 8; // Number of bits to shift per octet.
  473. a3 = IP & LowOctetMask; IP >>= BitsInOneOctet; // Grab the a3 octet and shift the IP.
  474. a2 = IP & LowOctetMask; IP >>= BitsInOneOctet; // Grab the a2 octet and shift the IP.
  475. a1 = IP & LowOctetMask; IP >>= BitsInOneOctet; // Grab the a1 octet and shift the IP.
  476. a0 = IP & LowOctetMask; // Grab the final octet.
  477. sprintf(bfr,"%d.%d.%d.%d",a0,a1,a2,a3);
  478. return bfr;
  479. }
  480. void GBUdb::recordAlertFor(unsigned int IP, GBUdbRecord& R, unsigned int C) { // Record an alert event for R if needed.
  481. if(AlertFor(C)) { // If an alert is needed at this level...
  482. GBUdbAlert NewAlert; // Create a new alert record.
  483. NewAlert.IP = IP; // Assign the IP.
  484. NewAlert.R = R; // Assign the Record.
  485. ScopeMutex JustMe(AlertsMutex); // Lock the alerts list mutex.
  486. MyAlerts.push_back(NewAlert); // Add our new alert to the list.
  487. }
  488. }
  489. GBUdbAlert::GBUdbAlert() : // Default constructor gets timestamp.
  490. IP(0) { // IP to zero, R will init to zero
  491. getTimestamp(UTC); // on it's own... Get timestamp.
  492. }
  493. string GBUdbAlert::toXML() { // Convert this alert to XML text
  494. stringstream Alert; // We'll use a stringstream.
  495. const char* FlagName = "ERROR"; // We will want the Flag as text.
  496. switch(R.Flag()) { // Switch on the Flag() value.
  497. case Good: { FlagName = "Good"; break; } // Convert each value to it's name.
  498. case Bad: { FlagName = "Bad"; break; }
  499. case Ugly: { FlagName = "Ugly"; break; }
  500. case Ignore: { FlagName = "Ignore"; break; }
  501. }
  502. char IPStringBfr[20]; // We need a buffer for our IP.
  503. Alert
  504. << "<gbu time=\'" << UTC // GBU alert + timestamp followed
  505. << "\' ip=\'" << getIPString(IP,IPStringBfr) // with the IP,
  506. << "\' t=\'" << FlagName // the type flag,
  507. << "\' b=\'" << R.Bad() // the bad count,
  508. << "\' g=\'" << R.Good() // and the good count.
  509. << "\'/>"; // That's the end.
  510. return Alert.str(); // Return the string.
  511. }
  512. //// Alert import and export - for sharing data between nodes.
  513. void GBUdb::GetAlerts(list<GBUdbAlert>& ListToFill) { // Get all current alerts & clear;
  514. ListToFill.clear(); // Clear out the list to fill.
  515. ScopeMutex JustMe(AlertsMutex); // Lock for a moment.
  516. ListToFill = MyAlerts; // Copy our alerts to the new list.
  517. MyAlerts.clear(); // Clear our alerts.
  518. }
  519. // In order to allow gbudb nodes to interact without swamping their individuality,
  520. // the default mode for integrating thier data is to represent the remote peer's
  521. // influence on a logarithmic scale.
  522. unsigned int rescaleGBUdbCount(unsigned int C) { // Rescale count C for integration.
  523. if(C < 0x00000001) { return 0; } else // Log2, really, .. the short way.
  524. if(C < 0x00000002) { return 1; } else // How many significant bits are in
  525. if(C < 0x00000004) { return 2; } else // the number. Put another way, what
  526. if(C < 0x00000008) { return 3; } else // power of 2 is required to for
  527. if(C < 0x00000010) { return 4; } else // this number.
  528. if(C < 0x00000020) { return 5; } else
  529. if(C < 0x00000040) { return 6; } else
  530. if(C < 0x00000080) { return 7; } else
  531. if(C < 0x00000100) { return 8; } else
  532. if(C < 0x00000200) { return 9; } else
  533. if(C < 0x00000400) { return 10; } else
  534. if(C < 0x00000800) { return 11; } else
  535. if(C < 0x00001000) { return 12; } else
  536. if(C < 0x00002000) { return 13; } else
  537. if(C < 0x00004000) { return 14; } else
  538. return 15;
  539. }
  540. void GBUdb::ImportAlerts(list<GBUdbAlert>& PeerAlerts) { // Integrate peer alerts using log2.
  541. list<GBUdbAlert>::iterator iA;
  542. for(iA = PeerAlerts.begin(); iA != PeerAlerts.end(); iA++) { // Go through the list of PeerAlerts.
  543. GBUdbRecord R = (*iA).R; // Grab the Record in this alert.
  544. R.Bad(rescaleGBUdbCount(R.Bad())); // Adjust the bad and good counts
  545. R.Good(rescaleGBUdbCount(R.Good())); // for integration.
  546. adjustCounts((*iA).IP, R); // Adjust the local counts w/ R.
  547. }
  548. }
  549. //// doForAllRecords
  550. //// This method handles GBUdbOperators and their locking semantics.
  551. //// For full dataset locking the mutex is acquired before calling the
  552. //// dataset's doForAllRecords(). For record locking, the O passed to
  553. //// this method is wrapped in a record locking shim (below) and that is
  554. //// passed to the dataset. If None is selected then the Operator is
  555. //// passed to the dataset as is -- assuming that the Operator will handle
  556. //// it's own locking as needed.
  557. class GBUdbRecordLockingShim : public GBUdbOperator { // Record locking shim for doForAllRecords.
  558. private:
  559. GBUdbOperator& MyOperator; // Reference the Operator we will be servicing.
  560. Mutex& MyMutex; // Reference the Mutex for the GBUdb we are in.
  561. public:
  562. GBUdbRecordLockingShim(GBUdbOperator& O, Mutex& M) : // On construction we grab our critical pieces.
  563. MyOperator(O),
  564. MyMutex(M) {
  565. }
  566. GBUdbRecord& operator()(unsigned int IP, GBUdbRecord& R) { // When our operator() is called
  567. ScopeMutex JustMe(MyMutex); // we lock the mutex in scope and
  568. return MyOperator(IP, R); // call the Operator we're servicing.
  569. } // When we leave scope we unlock (see above).
  570. };
  571. void GBUdb::doForAllRecords(GBUdbOperator& O, GBUdbLocking L) { // Calls O(IP, Record) w/Every record.
  572. if(Dataset == L) { // If we are locking for the Dataset, then
  573. ScopeMutex JustMe(MyMutex); // we will lock the mutex during this
  574. MyDataset->doForAllRecords(O); // entire operation.
  575. } else
  576. if(Record == L) { // If we are locking per record then
  577. GBUdbRecordLockingShim X(O, MyMutex); // we create a record locking shim instance
  578. MyDataset->doForAllRecords(X); // and call O() through that.
  579. } else { // If locking is NOT enabled, then
  580. MyDataset->doForAllRecords(O); // we will call O() without any locking.
  581. }
  582. }
  583. //// The saveSnapshot() method allows us to save a snapshot of our dataset
  584. //// while keeping the mutex locked for as short a time as possible: Just long
  585. //// enough to make a copy of the dataset in RAM.
  586. void GBUdb::saveSnapshot() { // Saves a snapshot of the current db.
  587. GBUdbDataset* Snapshot = NULL; // We need a pointer for our snapshot.
  588. if(NULL == MyDataset) { // If we do not have a dataset to copy
  589. return; // then we simply return.
  590. } else { // If we do have a Dataset to copy...
  591. ScopeMutex JustMe(MyMutex); // Lock the mutex and
  592. Snapshot = new GBUdbDataset(*MyDataset); // make a copy in memory.
  593. } // Then we can unlock the mutex.
  594. Snapshot->save(); // Then outside the mutex we can save.
  595. delete Snapshot; // Once saved we can delete the snapshot.
  596. PostsCounter = 0; // Reset the posts counter.
  597. }
  598. //// reduce()
  599. //// Using the doForAllRecords() functionality, this method reduces all counts
  600. //// by 2 thus renormalizing all records at lower count values. Unknown flagged
  601. //// records who's counts drop to zero will achieve the state GBUdbUnknown. As
  602. //// such, those values would not be carried over in a compress() operation.
  603. class ReduceAll : public GBUdbOperator { // To reduce the good and bad counts.
  604. public:
  605. GBUdbRecord& operator()(unsigned int IP, GBUdbRecord& R) { // Given each record,
  606. R.Good(R.Good() >> 1); // Reduce the Good count by half.
  607. R.Bad(R.Bad() >> 1); // Reduce the Bad count by half.
  608. return R; // Return the record.
  609. }
  610. } ReduceAllOperator;
  611. void GBUdb::reduce() { // Reduce all counts by half.
  612. doForAllRecords(ReduceAllOperator); // Call do for all records with the
  613. } // ReduceAllOperator.
  614. //// compress()
  615. //// Using the doForAllRecords() functionality, this method creates a temporary
  616. //// dataset, copies the existing data into that dataset except where the data
  617. //// is GBUdbUnknown, and then swaps the new dataset in place of the old.
  618. class CompressAll : public GBUdbOperator {
  619. private:
  620. GBUdbDataset* MyOldDataset; // Where do we find the old dataset.
  621. GBUdbDataset* MyNewDataset; // Where do we store our new dataset.
  622. int CountConverted;
  623. int CountDropped;
  624. public:
  625. // Note - There is no destructor. It is expected that the calling function
  626. // will extract the NewDataset and replace the OldDataset when the operation
  627. // has been successful.
  628. CompressAll(GBUdbDataset* OldDataset) : // Startup by
  629. MyOldDataset(OldDataset), // Grabbing the old dataset,
  630. MyNewDataset(NULL), // The new one isn't there yet.
  631. CountConverted(0), // Converted and Dropped
  632. CountDropped(0) { // Counts are zero.
  633. MyNewDataset = new GBUdbDataset(NULL); // Allocate a new Dataset.
  634. MyNewDataset->FileName(OldDataset->FileName()); // Set it's name the same as the old.
  635. } // We don't want to Load() it that way ;-)
  636. GBUdbRecord& operator()(unsigned int IP, GBUdbRecord& R) { // The ForAll Operator goes like this...
  637. if(GBUdbUnknown != R.RawData) { // If the record is not GBUdbUnknown then
  638. MyNewDataset->invokeRecord(IP).RawData = R.RawData; // invoke it and copy it's data.
  639. ++CountConverted; // Increment the converted count.
  640. } else { // If the record is GBUdbUnknown then
  641. ++CountDropped; // count it as dropped and forget it.
  642. }
  643. return R; // Return the record reference.
  644. }
  645. GBUdbDataset* Old() {return MyOldDataset;} // Here we can get our OldDataset pointer.
  646. GBUdbDataset* New() {return MyNewDataset;} // Here we can get our NewDataset pointer.
  647. int Converted() {return CountConverted;} // Here we can get the converted count.
  648. int Dropped() {return CountDropped;} // Here we can get the dropped count.
  649. };
  650. void GBUdb::compress() { // Remove any unknown records (reduced to zero).
  651. CompressAll BuildCompressedDataset(MyDataset); // Create a CompressAll operator for this dataset.
  652. ScopeMutex Freeze(MyMutex); // Lock the mutex for the rest of this operation.
  653. MyDataset->doForAllRecords(BuildCompressedDataset); // Copy all of the active data records.
  654. MyDataset = BuildCompressedDataset.New(); // Put the new dataset in place.
  655. delete BuildCompressedDataset.Old(); // Delete the old dataset.
  656. } // All done, so we're unlocked.
  657. int GBUdb::readIgnoreList(const char* FileName) { // setIgnore for a list of IPs
  658. int IPCount = 0; // Keep track of the IPs we read.
  659. try { // Capture any exceptions.
  660. char IPLineBuffer[256]; // Create a line buffer.
  661. const int SafeBufferSize = sizeof(IPLineBuffer) - 1; // Safe size always leaves a NULL on the end.
  662. ifstream ListFile(FileName, ios::in); // Open up the list file.
  663. while(ListFile.good()) { // While we've got a good file (not eof)
  664. memset(IPLineBuffer, 0, sizeof(IPLineBuffer)); // Clear the buffer.
  665. ListFile.getline(IPLineBuffer, SafeBufferSize); // Read the line. (safely NULL terminated)
  666. // Now we have an IP on a line (in theory). We will parse
  667. // the ip and process any that parse correctly.
  668. // First eat anything that's not a digit.
  669. unsigned long IP = 0L; // We need an IP buffer.
  670. char* cursor = IPLineBuffer; // Start on the first byte.
  671. if('#' == *cursor) continue; // Lines that start with # are comments.
  672. while(0 < *cursor && isspace(*cursor)) ++cursor; // Eat any leading spaces.
  673. // First octet.
  674. if(!isdigit(*cursor)) continue; // If it's not a digit skip this line.
  675. if(255 < atoi(cursor)) continue; // If the octet is out of range skip!
  676. IP += atoi(cursor); IP <<= 8; // Grab the first int and shift it.
  677. while(isdigit(*cursor)) ++cursor; // Eat those digits.
  678. if('.'!=(*cursor)) continue; // If we don't find a dot skip this line.
  679. ++cursor; // If we do, skip the dot.
  680. // Second octet.
  681. if(!isdigit(*cursor)) continue; // If we're not at digit skip this line.
  682. if(255 < atoi(cursor)) continue; // If the octet is out of range skip!
  683. IP += atoi(cursor); IP <<= 8; // Grab the octet and shift things left.
  684. while(isdigit(*cursor)) ++cursor; // Eat those digits.
  685. if('.'!=(*cursor)) continue; // If we don't find a dot skip this line.
  686. ++cursor; // If we do, skip the dot.
  687. // Third octet.
  688. if(!isdigit(*cursor)) continue; // If we're not at digit skip this line.
  689. if(255 < atoi(cursor)) continue; // If the octet is out of range skip!
  690. IP += atoi(cursor); IP <<= 8; // Grab the octet and shift things left.
  691. while(isdigit(*cursor)) ++cursor; // Eat those digits.
  692. if('.'!=(*cursor)) continue; // If we don't find a dot skip this line.
  693. ++cursor; // If we do, skip the dot.
  694. // Last octet.
  695. if(!isdigit(*cursor)) continue; // If we're not at a digit skip this line.
  696. if(255 < atoi(cursor)) continue; // If the octet is out of range skip!
  697. IP += atoi(cursor); // Grab the octet. IP finished!
  698. setIgnore(IP); // Set the IP to Ignore.
  699. ++IPCount; // Bump the IP count.
  700. }
  701. ListFile.close();
  702. }
  703. catch(...) { } // If we have an exception we stop.
  704. return IPCount; // Always return the number of lines read.
  705. }
  706. }