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.

FilterChain.cpp 72KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. // FilterChain.cpp
  2. //
  3. // (C) 2002-2009 MicroNeil Research Corporation
  4. //
  5. // Main code file for module FilterChain.
  6. // 20041116 _M Added UrlDecode module. The module will repeat a decoded version of
  7. // any anchor tag that it sees which contains decodable %xx bytes. Other anchor
  8. // tags are not repeated.
  9. // 20041116 _M Upgrades to the Defunker module. The module now decodes any HTML
  10. // encoded bytes that could have been normal ascii.
  11. // 20041114 _M Completed basic defunker engine which strips out all HTML and some
  12. // basic   encoding.
  13. // 20041113 _M Began heavy upgrades to this module to improve performance and
  14. // provide additional obfuscation removal. This modification will include a move
  15. // from the use of switch(State) mechanisms to the use of function pointers. This
  16. // should save a few cycles on every byte processed.
  17. #include "FilterChain.hpp"
  18. // FilterChainBase64 Methods.
  19. // GetByte()
  20. // Returns the next byte from this filter module.
  21. unsigned char FilterChainBase64::GetByte() {
  22. switch(State) { // What are we doing?
  23. case SCANNING:{ // We're scanning to turn on...
  24. // In this mode we are hunting for a reason to turn
  25. // ourselves on. If we find our startup sequence then
  26. // we will go into decoding mode. Until then, we try
  27. // to match each incoming character with our startup
  28. // sequence.
  29. while(true) { // Search for our startup string or get out.
  30. try { // Try this...
  31. x=FilterChain::GetByte(); // Get the next byte from source.
  32. } // If we get the empty signal
  33. // here, we've failed to match.
  34. catch(Empty) { // If so - and we haven't
  35. if(0==ScanIx) throw Empty("FilterChainBase64: No more data"); // started then just throw Empty.
  36. x=Base64Start[ScanIx]-1; // If we did start then make
  37. } // sure we won't match below.
  38. // It's important that no empty's get beyond this point unless
  39. // we've got a match started. Otherwise we'll return corruption.
  40. if(x!=Base64Start[ScanIx]){ // If the byte doesnt match,
  41. // and we've started matching
  42. if(0!=ScanIx) { // the sequence then save the
  43. Buffer=x; // byte for later, change to
  44. State=DEQUEING;DequeIx=0; // DEQUING mode, and return
  45. return GetByte(); // the first Dequeued byte.
  46. }
  47. // If there's no match
  48. else return x; // started then shortcut that:
  49. } // just send back the byte.
  50. // We've handled non matches, now time for the good stuff...
  51. else { // This byte matches :-)
  52. ScanIx++; // Move forward!
  53. if(ScanIx>=sizeof(Base64Start)-1){ // If we've matched it all
  54. // then prep for decoding.
  55. // At this point we've got our trigger - but we need to
  56. // eat up any extra junk before we start decoding. What
  57. // we're looking for is a blank line (CRLFCRLF) within
  58. // the next couple of lines. While we're at this if we
  59. // get an exception we'll just pass it through.
  60. ScanIx=DequeIx=0; // Let's reset our indexes.
  61. // We're SCANNING now - so if we fail to get to good base64
  62. // stuff then we'll be starting from scratch - and that's ok.
  63. // Here we will allow some number of additional header lines
  64. // to occur before we give up on this being a base64 segment.
  65. // If we give up then we go back to scanning agian.
  66. // 20030114 _M Increased limit to 150 - lots of X- headers cause
  67. // the engine to stop decoding base64!! 30 was too small.
  68. const int LineLimit = 150; // We'll allow this many.
  69. for(int LineCount=0; LineCount<LineLimit; LineCount++) {
  70. do{ // Eat up characters through
  71. x=FilterChain::GetByte(); // the end of the line.
  72. } while(x!='\n');
  73. x=FilterChain::GetByte(); // Get the next byte.
  74. if(x=='\n'){ // Next line is blank?
  75. State=DECODING; // Then get ready to DECODE!
  76. break; // NO MORE LOOPING!
  77. }
  78. // If the line is not blank then we'll go around again up
  79. // to the number of lines we allow. Then we're done trying
  80. // and we will fall through.
  81. }
  82. // At this point we are either ready to decode base64 data
  83. // or we're still in SCANNING mode because of too much junk.
  84. if(DECODING==State) { // If we're ready to decode
  85. Workspace = 0x0000000a; // then set up a pair of
  86. DequeIx=3; // <LF> lines so they will
  87. ScanIx=2; // be the first bytes decoded.
  88. } // Here we pump <LF> into the
  89. // workspace. Then we return one <LF>
  90. return x; // (usually).
  91. // The deal is, if we're decoding then we will pump in LF and
  92. // return what must be the last LF. If we're not decoding then we
  93. // end up returning the last byte we read before giving up which should
  94. // be the first byte of the next line.
  95. }
  96. }
  97. }
  98. // The above will be tried repeatedly in the first call to
  99. // this object's GetByte() until we either return a byte or
  100. // throw an exception. The result is that once we start to match
  101. // our startup sequence we will either match all of it or we will
  102. // grab as much of it as we can until we don't match - then we'll
  103. // fail and move into DEQUEING.
  104. // You may be asking yourself, why go through all that complex
  105. // Turing engine stuff when a simple line load and string comparison
  106. // would do nicely. The answer is SPEED. Without getting too deep,
  107. // the above code will identify the startup string in roughly 2
  108. // comparisons per byte. If I were to load the entire line first
  109. // then that alone would be 2 comparisons before I got started. This
  110. // way I cut the number of comparisons down by at least 50%.
  111. break;
  112. }
  113. case DEQUEING:{ // We're recovering from a false start...
  114. // When we get here, ScanIx will be one greater than the last
  115. // matching byte. The last byte read will be stored in our buffer
  116. // so that it can be returned here as the last step. The calling
  117. // program will request each byte one at a time... starting with
  118. // the first byte coming out of this code. For all positions in our
  119. // startup string less than ScanIx, we know we had a matching input.
  120. // We start our output at the first byte. The Scanning engine should
  121. // have set our DequeIx to 0 before we got here - so that part should
  122. // be automatic. Here goes...
  123. if(DequeIx < ScanIx) { // If we're still returning a
  124. unsigned char x = // partial match, grab the next byte
  125. Base64Start[DequeIx]; // from the startup string, Increment
  126. DequeIx++; // our Deque index for next time, and
  127. return x; // return the byte that's needed.
  128. } else { // When we're done with that part,
  129. State=SCANNING; // we set our mode back to scanning,
  130. ScanIx=DequeIx=0; // reset our indexes to start again,
  131. return Buffer; // and return the unmatching byte that
  132. } // got us to DEQUEING mode.
  133. break;
  134. }
  135. case DECODING:{ // We're decoding data...
  136. // DequeIx will be used here to indicate how many decoded
  137. // bytes are ready to be delivered. This is compatible with
  138. // the normal startup for other modes.
  139. // ScanIx will be used here to indicate which byte position
  140. // we should be reading from. This combination helps to handle
  141. // pads and simplifies processing. For example, if we've got two
  142. // pads then we'll have a single byte to read starting at index
  143. // zero.
  144. // If we get an exception from up the chain while we're decoding
  145. // then we'll just pass it along.
  146. if(0==DequeIx) { // If there are no bytes ready then get some!
  147. // First Byte:
  148. // Eat anything up to the first byte that doesn't look like
  149. // a base64 digit. If we hit a '\n-' then we'll assume we've got
  150. // a segment boundary and we'll quit. Everything else will be
  151. // ignored to get us to the next line.
  152. do{ // Empty out any in-between bytes.
  153. y=x;x=FilterChain::GetByte(); // Read one byte at a time.
  154. if('-'==x && '\n'==y) { // If we get to a segment separator
  155. ScanIx=DequeIx=0; // then reset our indexes, set our
  156. State=SCANNING; // state to SCANNING...
  157. do { // Eat up the rest of this line
  158. x=FilterChain::GetByte(); // one byte at a time including
  159. } while('\n'!=x); // the <LF> at the end, then
  160. return '\n'; // return the that <LF> byte.
  161. // On the next incoming call, the scanner section "should"
  162. // return the following <LF> byte to complete the end of line.
  163. // This ensures that we put a new line at the end of our
  164. // decoded segment. Four message scanning purposes this is
  165. // desireable. If we wanted a clean segment then we'd probably
  166. // eat through the new line rather than the carriage return.
  167. }
  168. } while(XX64==Base64Table[x]); // Eat all invalid bytes.
  169. // At this point x should have the first valid byte for us :-)
  170. if('='==x) { // First byte can't be a pad.
  171. ScanIx=DequeIx=0; // If it is then we reset ourself,
  172. do{ // eat the rest of this line,
  173. y=x;x=FilterChain::GetByte(); // and then go on with scanning.
  174. }while('\n'!=x);
  175. return x;
  176. }
  177. // At this point we have a clean byte, presumably at the start
  178. // of a base64 block which we can decode.
  179. x = Base64Table[x]; // Convert the byte.
  180. // This first one we assign to clear out the register. The rest
  181. // get added to keep things in place.
  182. Workspace = // Add it to the workspace in the
  183. x << base64_seg0_shift; // correct position.
  184. // Byte number 2 of the block...
  185. x=FilterChain::GetByte(); // Grab the byte...
  186. if('='==x) { // This byte can't be a pad.
  187. ScanIx=DequeIx=0; // If it is then we reset ourself,
  188. do{ // eat the rest of this line,
  189. y=x;x=FilterChain::GetByte(); // and then go on with scanning.
  190. }while('\n'!=x);
  191. return x;
  192. }
  193. x=Base64Table[x]; // Convert the byte.
  194. if(XX64==x) { // The byte can't be invalid...
  195. ScanIx=DequeIx=0; // If it is then we reset ourself,
  196. do{ // eat the rest of this line,
  197. y=x;x=FilterChain::GetByte(); // and then go on with scanning.
  198. }while('\n'!=x);
  199. return x;
  200. }
  201. // At this point we have a clean byte...
  202. Workspace += // Add it to the workspace in the
  203. x << base64_seg1_shift; // correct position.
  204. // Byte number 3 of the block...
  205. x=FilterChain::GetByte(); // Grab the byte...
  206. // This one and the next one can be pads. Here's where we start
  207. // deciding how many bytes we have. If we have a pad in this spot
  208. // then our output bytes will only be 1.
  209. if('='==x) DequeIx = 1; // If we've got a pad here we'll only
  210. else DequeIx = 3; // have one valid output byte. Otherwise
  211. // we could have 3.
  212. x=Base64Table[x]; // Convert the byte.
  213. if(XX64==x) { // The byte can't be invalid...
  214. ScanIx=DequeIx=0; // If it is then we reset ourself,
  215. do{ // eat the rest of this line,
  216. y=x;x=FilterChain::GetByte(); // and then go on with scanning.
  217. }while('\n'!=x);
  218. return x;
  219. }
  220. // At this point we have a clean byte...
  221. Workspace += // Add it to the workspace in the
  222. x << base64_seg2_shift; // correct position.
  223. // Byte number 4 of the block...
  224. x=FilterChain::GetByte(); // Grab the byte...
  225. if('='==x && DequeIx > 2) // If we've got a pad here the most
  226. DequeIx=2; // we can have are 2 valid outputs.
  227. x=Base64Table[x]; // Convert the byte.
  228. if(XX64==x) { // The byte can't be invalid...
  229. ScanIx=DequeIx=0; // If it is then we reset ourself,
  230. do{ // eat the rest of this line,
  231. y=x;x=FilterChain::GetByte(); // and then go on with scanning.
  232. }while('\n'!=x);
  233. return x;
  234. }
  235. // At this point we have a clean byte...
  236. Workspace += // Add it to the workspace in the
  237. x << base64_seg3_shift; // correct position.
  238. // At this point we are ready to begin outputting our bytes.
  239. ScanIx=2; // Output always starts byte three.
  240. return GetByte(); // Return our first decoded byte.
  241. } else { // If there are bytes ready then spit them out.
  242. x=(Workspace >> (ScanIx * 8)) & 0xFF; // Grab the byte we want.
  243. ScanIx--; // Decrement our output index.
  244. DequeIx--; // Decrement our output count.
  245. return x; // Send back our byte.
  246. }
  247. break;
  248. }
  249. }
  250. // We should never get to this point.
  251. return 0; // Dummy to make the compiler happy.
  252. }
  253. // FilterChainQuotedPrintable Methods.
  254. // isHexDigit()
  255. // Returns true if i is a valid hex digit.
  256. bool FilterChainQuotedPrintable::isHexDigit(unsigned char i) {
  257. if(
  258. (i >= '0' && i <= '9') || // Hex digits must be 0-9 or
  259. (i >= 'A' && i <= 'F') || // A-F or
  260. (i >= 'a' && i <= 'f') // a-f if somebody used lower case.
  261. ) {
  262. return true; // If i is one of these we are true
  263. } else {
  264. return false; // IF i is not then we are false
  265. }
  266. }
  267. // convertHexDigit()
  268. // Returns an integer value for the hex digit i
  269. int FilterChainQuotedPrintable::convertHexDigit(unsigned char i) {
  270. if(i >= '0' && i <= '9') { // Digit chars convert directly.
  271. return i - '0';
  272. } else if (i >= 'A' && i <= 'F') { // Cap A-F convert to 10 - 15
  273. return i - 'A' + 10;
  274. } else if (i >= 'a' && i <= 'f') { // Small A-F convert to 10 - 15
  275. return i - 'a' + 10;
  276. }
  277. return -1; // Return -1 if i was not a hex digit!
  278. }
  279. // GetByte()
  280. // Returns the next byte from this filter module.
  281. unsigned char FilterChainQuotedPrintable::GetByte() {
  282. switch(State) { // What are we doing?
  283. case SCANNING: // We're scanning to turn on...
  284. Buffer[0]=FilterChain::GetByte();
  285. if('='== Buffer[0]) { // If we've found an = then we're on.
  286. Buffer[1]=FilterChain::GetByte(); // Fill up the decoding buffer with
  287. Buffer[2]=FilterChain::GetByte(); // the next two bytes,
  288. BufferIndex = 0; // Setup the buffer index.
  289. BufferLength = 3; // Setup the buffer length.
  290. State = DECODING; // Set our mode and get the result
  291. return GetByte(); // by calling ourselves!
  292. } else
  293. return Buffer[0]; // Otherwise just pass through.
  294. break;
  295. case DEQUEING: // We're recovering from a false start...
  296. if(BufferIndex < BufferLength) { // If we've got buffered stuff then
  297. return Buffer[BufferIndex++]; // return it and move the pointer.
  298. } else { // If we've run out of stuff then
  299. BufferIndex = 0; // Reset our index and our
  300. BufferLength = 0; // buffer length, then set our
  301. State = SCANNING; // mode to SCANNING and return
  302. return GetByte(); // the next byte from there.
  303. }
  304. break;
  305. case DECODING: // We're decoding data...
  306. // Now we are decoding quoted printable data. First we will handle the case
  307. // where this is a soft line break. In that case we simply eat the encoded bytes
  308. // and set up to dequeue the last byte.
  309. if(Buffer[1] == '\n') { // If this is a soft break the
  310. BufferIndex = 2; // point our dequeue index at the last byte
  311. State = DEQUEING; // establish our DEQUEING state and
  312. return GetByte(); // return by letteing DEQUEING do it!
  313. }
  314. // If it wasn't a soft break then we _may_ need to decode it. We will find
  315. // out by looking for hex digits in the next two locations. If they are there
  316. // we are decoding. If not then we will simply dequeue the entire buffer.
  317. if(
  318. isHexDigit(Buffer[1]) && // If the next two bytes are hex
  319. isHexDigit(Buffer[2]) // digits then we can convert them.
  320. ) {
  321. Workspace= // Set our workspace to convert the
  322. (convertHexDigit(Buffer[1]) << 4) | // two hex digits into a single
  323. (convertHexDigit(Buffer[2])); // byte.
  324. Buffer[2] = Workspace & 0xFF; // Store that byte in our buffer.
  325. BufferIndex = 2; // Set the index and change our
  326. State = DEQUEING; // state to DEQUEING then let that
  327. return GetByte(); // code spit it out!
  328. } else { // If either byte was not a valid
  329. State = DEQUEING; // hex digit DEQUEUE the entire
  330. return GetByte(); // buffer.
  331. }
  332. break;
  333. };
  334. return FilterChain::GetByte(); // Dummy
  335. }
  336. /////////////////////////////////////////////////////////////////////////////////////////
  337. // FilterChainDefunker
  338. /////////////////////////////////////////////////////////////////////////////////////////
  339. const char* DefunkerPreamble = "\n----[DEFUNKER]----\n";
  340. // Patterns to match
  341. const char* patMatchBR = "<br>";
  342. const char* patMatchP = "<p>";
  343. const char* patNBSP = "&nbsp;";
  344. const char* patAMP = "&amp;";
  345. const char* patAPOS = "&apos;";
  346. const char* patLT = "&lt;";
  347. const char* patGT = "&gt;";
  348. const char* patQUOT = "&quot;";
  349. // SkipHeaders() waits for the headers to go by before launching Store().
  350. unsigned char FilterChainDefunker::SkipHeaders() { // While waiting EOH...
  351. unsigned char x = FilterChain::GetByte(); // Get a byte.
  352. if(LastRawByte == '\n' && x == '\n') { // If we're at EOH
  353. Master = &FilterChainDefunker::Store; // Go to store mode.
  354. return x; // and return the byte.
  355. } // If we're not at EOH
  356. LastRawByte = x; // then remember this byte
  357. return x; // and return it.
  358. }
  359. // Store() puts the original data into the buffer for later.
  360. unsigned char FilterChainDefunker::Store() { // While in Store mode,
  361. unsigned char x; // we need a byte.
  362. try {
  363. if(DefunkerSize-10 < InputPosition) {
  364. cout << "watch this" << endl;
  365. }
  366. if(DefunkerSize <= InputPosition)
  367. throw Empty("FilterChainDefunker: No more data"); // Careful about the buffer.
  368. x = FilterChain::GetByte(); // Try getting the next byte
  369. StoreBuffer[InputPosition++] = x; // and storing it.
  370. }
  371. catch(Empty) { // When we get the Empty
  372. Master = &FilterChainDefunker::ReadOut; // signal it is time for us
  373. return GetByte(); // to read out our data.
  374. }
  375. return x; // Otherwis pass on the byte.
  376. }
  377. // ReadOut() retrieves the stored data through the state engine.
  378. unsigned char FilterChainDefunker::ReadOut() { // Read out and dedup spaces.
  379. if(LastReadOut == ' ') { // If the last byte was a space
  380. while(LastReadOut == ' ') { // then eat all of the spaces
  381. LastReadOut = SpaceConvChart[GetInternal()]; // that come next with spaces
  382. } // converted.
  383. } else { // If it was not a space then
  384. LastReadOut = SpaceConvChart[GetInternal()]; // simply read the next byte
  385. } // with spaces converted.
  386. return LastReadOut; // Output the byte we found.
  387. }
  388. // GetStore() retrieves the raw store for the state engine.
  389. unsigned char FilterChainDefunker::GetStore() { // Read from the Store.
  390. if(OutputPosition >= InputPosition) {
  391. throw Empty("FilterChainDefunker: No more data"); // If we're out of bytes throw Empty.
  392. }
  393. return LastGetStore = StoreBuffer[OutputPosition++]; // If we have more, trap and send it.
  394. }
  395. //// The following functions make up the state engine with the state maintained
  396. //// as a function pointer in the (*Internal)() handle.
  397. unsigned char FilterChainDefunker::Preamble() { // Emit the preamble.
  398. for(
  399. int p=0; // Load the preamble into
  400. DefunkerPreamble[p]; // the queue.
  401. p++) EnQueue(DefunkerPreamble[p]);
  402. Internal = &FilterChainDefunker::DeQueue; // Set up the DeQueue mode
  403. return GetInternal(); // and return the next byte.
  404. }
  405. unsigned char FilterChainDefunker::DefunkRoot() { // While in DefunkRoot state
  406. unsigned char x = GetStore(); // grab the next byte.
  407. if(x == '<') { // If it matches < then
  408. Internal = &FilterChainDefunker::OpenTag; // go to OpenTag state and
  409. return GetInternal(); // return the next byte.
  410. } else
  411. if(x == '&') { // If it matches & then
  412. Internal = &FilterChainDefunker::OpenAmp; // go to OpenAnd state and
  413. EnQueue(x); // push in the amphersand.
  414. return GetInternal(); // return the next byte.
  415. } // If we did not match then
  416. return x; // return what we grabbed.
  417. }
  418. unsigned char FilterChainDefunker::OpenTag() { // While in OpenTag state
  419. unsigned char x = GetStore(); // grab the next byte.
  420. switch(tolower(x)) { // Check the lower case of x.
  421. case 'b': // If we have a 'b' then
  422. Internal = &FilterChainDefunker::MatchBR; // our mode is MatchBR.
  423. break;
  424. case 'p': // If we have a 'p' then
  425. Internal = &FilterChainDefunker::MatchP; // our mode is MatchP.
  426. break;
  427. default: // If we did not match then
  428. Internal = &FilterChainDefunker::EatTag; // our mode is EatTag.
  429. break;
  430. }
  431. return GetInternal(); // Return the next byte.
  432. }
  433. unsigned char FilterChainDefunker::OpenAmp() { // While in OpenAmp state
  434. unsigned char x = GetStore(); // grab the next byte.
  435. if(tolower(x) == 'n') { // If it matched n then
  436. EnQueue(x); // push in the n -
  437. Internal = &FilterChainDefunker::MatchNBSP; // we are working on &nbsp;
  438. return GetInternal(); // return the next byte.
  439. } else
  440. if(tolower(x) == 'a') { // If it matched a then
  441. EnQueue(x); // push in the a -
  442. Internal = &FilterChainDefunker::SwitchAMPAPOS; // is it AMP or APOS?
  443. return GetInternal(); // return the next byte.
  444. } else
  445. if(tolower(x) == 'l') { // If it matched l then
  446. EnQueue(x); // push in the l -
  447. Internal = &FilterChainDefunker::MatchLT; // we are working on &lt;
  448. return GetInternal(); // return the next byte.
  449. } else
  450. if(tolower(x) == 'g') { // If it matched g then
  451. EnQueue(x); // push in the g -
  452. Internal = &FilterChainDefunker::MatchGT; // we are working on &gt;
  453. return GetInternal(); // return the next byte.
  454. } else
  455. if(tolower(x) == 'q') { // If it matched q then
  456. EnQueue(x); // push in the q -
  457. Internal = &FilterChainDefunker::MatchQUOT; // we are working on &quot;
  458. return GetInternal(); // return the next byte.
  459. } else
  460. if(x == '#') { // If it matched # then
  461. EnQueue(x); // push in the # -
  462. Internal = &FilterChainDefunker::DecodeNum; // we are working on &#...;
  463. return GetInternal(); // return the next byte.
  464. }
  465. Internal = &FilterChainDefunker::DeQueue; // If nothing matched then
  466. return GetInternal(); // punt and dequeue.
  467. }
  468. unsigned char FilterChainDefunker::MatchBR() { // If our mode is MatchBR
  469. if(MatchTagPattern(patMatchBR)) { // If we matched our pattern
  470. Internal = &FilterChainDefunker::DefunkRoot; // go to DefunkRoot state
  471. return ' '; // and return a space.
  472. } // If we did not match then
  473. Internal = &FilterChainDefunker::EatTag; // go to EatTag state and
  474. return GetInternal(); // return the next byte.
  475. }
  476. unsigned char FilterChainDefunker::MatchP() { // If our mode is MatchP
  477. if(MatchTagPattern(patMatchP)) { // if we matched our pattern
  478. Internal = &FilterChainDefunker::DefunkRoot; // go to DefunkRoot state
  479. return ' '; // and return a space.
  480. } // If we did not match then
  481. Internal = &FilterChainDefunker::EatTag; // go to EatTag state and
  482. return GetInternal(); // return the next byte.
  483. }
  484. unsigned char FilterChainDefunker::MatchNBSP() { // If our mode is MatchNBSP
  485. int pos = 2; // We've seen &n so far.
  486. while(patNBSP[pos]){ // Look through the pattern
  487. unsigned char x = GetStore(); // getting one byte at a time.
  488. EnQueue(x); // Push each into the queue.
  489. if(tolower(x)!=patNBSP[pos]) break; // If we fall off, get out.
  490. pos++; // otherwise keep going.
  491. }
  492. // At this point our pattern[pos] is either 0 (a match) or not.
  493. if(patNBSP[pos]) { // If we did not match then
  494. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  495. return GetInternal(); // and return the next byte.
  496. }
  497. // If we did match the pattern
  498. ClearQueue(); // then clear the queue and
  499. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  500. return ' '; // return a space.
  501. }
  502. unsigned char FilterChainDefunker::MatchLT() { // If our mode is MatchLT
  503. int pos = 2; // We've seen &l so far.
  504. while(patLT[pos]){ // Look through the pattern
  505. unsigned char x = GetStore(); // getting one byte at a time.
  506. EnQueue(x); // Push each into the queue.
  507. if(tolower(x)!=patLT[pos]) break; // If we fall off, get out.
  508. pos++; // otherwise keep going.
  509. }
  510. // At this point our pattern[pos] is either 0 (a match) or not.
  511. if(patLT[pos]) { // If we did not match then
  512. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  513. return GetInternal(); // and return the next byte.
  514. }
  515. // If we did match the pattern
  516. ClearQueue(); // then clear the queue and
  517. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  518. return '<'; // return a <.
  519. }
  520. unsigned char FilterChainDefunker::MatchGT() { // If our mode is MatchGT
  521. int pos = 2; // We've seen &g so far.
  522. while(patGT[pos]){ // Look through the pattern
  523. unsigned char x = GetStore(); // getting one byte at a time.
  524. EnQueue(x); // Push each into the queue.
  525. if(tolower(x)!=patGT[pos]) break; // If we fall off, get out.
  526. pos++; // otherwise keep going.
  527. }
  528. // At this point our pattern[pos] is either 0 (a match) or not.
  529. if(patGT[pos]) { // If we did not match then
  530. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  531. return GetInternal(); // and return the next byte.
  532. }
  533. // If we did match the pattern
  534. ClearQueue(); // then clear the queue and
  535. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  536. return '>'; // return a >.
  537. }
  538. unsigned char FilterChainDefunker::MatchQUOT() { // If our mode is MatchQUOT
  539. int pos = 2; // We've seen &q so far.
  540. while(patQUOT[pos]){ // Look through the pattern
  541. unsigned char x = GetStore(); // getting one byte at a time.
  542. EnQueue(x); // Push each into the queue.
  543. if(tolower(x)!=patQUOT[pos]) break; // If we fall off, get out.
  544. pos++; // otherwise keep going.
  545. }
  546. // At this point our pattern[pos] is either 0 (a match) or not.
  547. if(patQUOT[pos]) { // If we did not match then
  548. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  549. return GetInternal(); // and return the next byte.
  550. }
  551. // If we did match the pattern
  552. ClearQueue(); // then clear the queue and
  553. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  554. return '\"'; // return a quote.
  555. }
  556. unsigned char FilterChainDefunker::SwitchAMPAPOS() { // We are chosing AMP or APOS.
  557. unsigned char x = GetStore(); // Get the next byte.
  558. EnQueue(x); // Put it into the queue.
  559. if(tolower(x)=='m') { // If we matched m then we
  560. Internal = &FilterChainDefunker::MatchAMP; // are working on MatchAMP.
  561. return GetInternal(); // Go get it.
  562. } else
  563. if(tolower(x)=='p') { // If we matched p then we
  564. Internal = &FilterChainDefunker::MatchAPOS; // are working on MatchAPOS.
  565. return GetInternal(); // Go get it.
  566. }
  567. Internal = &FilterChainDefunker::DeQueue; // If we didn't match either
  568. return GetInternal(); // we punt and DeQueue.
  569. }
  570. unsigned char FilterChainDefunker::MatchAPOS() { // If our mode is MatchAPOS
  571. int pos = 3; // We've seen &ap so far.
  572. while(patAPOS[pos]){ // Look through the pattern
  573. unsigned char x = GetStore(); // getting one byte at a time.
  574. EnQueue(x); // Push each into the queue.
  575. if(tolower(x)!=patAPOS[pos]) break; // If we fall off, get out.
  576. pos++; // otherwise keep going.
  577. }
  578. // At this point our pattern[pos] is either 0 (a match) or not.
  579. if(patAMP[pos]) { // If we did not match then
  580. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  581. return GetInternal(); // and return the next byte.
  582. }
  583. // If we did match the pattern
  584. ClearQueue(); // then clear the queue and
  585. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  586. return '\''; // return an apostrophie.
  587. }
  588. unsigned char FilterChainDefunker::MatchAMP() { // If our mode is MatchAMP
  589. int pos = 3; // We've seen &am so far.
  590. while(patAMP[pos]){ // Look through the pattern
  591. unsigned char x = GetStore(); // getting one byte at a time.
  592. EnQueue(x); // Push each into the queue.
  593. if(tolower(x)!=patAMP[pos]) break; // If we fall off, get out.
  594. pos++; // otherwise keep going.
  595. }
  596. // At this point our pattern[pos] is either 0 (a match) or not.
  597. if(patAMP[pos]) { // If we did not match then
  598. Internal = &FilterChainDefunker::DeQueue; // set our state to dequeue
  599. return GetInternal(); // and return the next byte.
  600. }
  601. // If we did match the pattern
  602. ClearQueue(); // then clear the queue and
  603. Internal = &FilterChainDefunker::DefunkRoot; // go back to root mode then
  604. return '&'; // return an amphersand.
  605. }
  606. unsigned char FilterChainDefunker::EatTag() { // If our mode is EatTag
  607. if(LastGetStore != '>') { // and our last byte was not
  608. while(GetStore()!='>')continue; // endtag then eat through
  609. } // the end tag. Then set our
  610. Internal = &FilterChainDefunker::DefunkRoot; // mode to DefunkRoot and
  611. return GetInternal(); // return the next byte.
  612. }
  613. unsigned char FilterChainDefunker::DecodeNum() { // If our mode is DecodeNum
  614. unsigned char NumBfr[5]; // A buffer for digits.
  615. memset(NumBfr,0,sizeof(NumBfr)); // Clear the buffer.
  616. for( // Let's read the number...
  617. unsigned int i=0; // NumBfr position = 0;
  618. i<(sizeof(NumBfr)-1) && // Stay well within the NunBfr.
  619. (EnQueue(NumBfr[i]=GetStore()), // Read and EnQueue each byte.
  620. isdigit(NumBfr[i])); // Keep going if it's a digit.
  621. i++)continue; // Move the buffer pointer.
  622. // Check for a proper finish...
  623. if(LastGetStore != ';') { // If we didn't end properly
  624. Internal = &FilterChainDefunker::DeQueue; // then we will punt and
  625. return GetInternal(); // DeQueue.
  626. }
  627. // At this point, NumBfr contains a c_str of the number to be decoded.
  628. // Also, the Qbfr has each byte we read in case we want to punt.
  629. int Decoded = atol((const char*)NumBfr); // Read the number.
  630. if(Decoded < 32 || Decoded > 255) { // If the number we read is
  631. Internal = &FilterChainDefunker::DeQueue; // out of range then we
  632. return GetInternal(); // punt and DeQueue.
  633. }
  634. // If we decoded a character
  635. ClearQueue(); // that is in range of normal
  636. Internal = &FilterChainDefunker::DefunkRoot; // ascii then clear the queue,
  637. return (unsigned char) Decoded; // go back to DefunkRoot, and
  638. } // return the decoded byte.
  639. /////////////////////////////////////////////////////////////////////////////////////////
  640. // FilterChainUrlDecode
  641. /////////////////////////////////////////////////////////////////////////////////////////
  642. unsigned char FilterChainUrlDecode::Bypass() { // In Bypass mode...
  643. unsigned char c = FilterChain::GetByte(); // Get the raw byte.
  644. if(c == '<') { // If it was '<' we begin.
  645. Internal = &FilterChainUrlDecode::Tag; // Go to Tag mode.
  646. AddToBfr(c); // Write the byte to our buffer.
  647. }
  648. return c; // Always return the byte.
  649. }
  650. unsigned char FilterChainUrlDecode::Tag() { // In Tag mode...
  651. unsigned char c = FilterChain::GetByte(); // Get the raw byte.
  652. if(tolower(c) == 'a') { // If we're in an anchor tag
  653. Internal = &FilterChainUrlDecode::Root; // Go to Decode Root mode.
  654. AddToBfr(c); // Write the byte to our buffer.
  655. } else
  656. if(tolower(c) == 'i') { // If we might be in an img tag
  657. Internal = &FilterChainUrlDecode::Img1; // Go to Img1 mode.
  658. AddToBfr(c); // Write the byte to our buffer.
  659. } else { // If we didn't match
  660. DecodeBfr[0] = 0; // we clear out the Decode
  661. DecodeBfr[1] = 0; // buffer. (Save some bytes by
  662. DecodeLength = 0; // doing it manually) Then we
  663. Internal = &FilterChainUrlDecode::Bypass; // Go to Bypass mode again.
  664. }
  665. return c; // Always return the byte.
  666. }
  667. unsigned char FilterChainUrlDecode::Img1() { // In Img1 mode...
  668. unsigned char c = FilterChain::GetByte(); // Get the raw byte.
  669. if(tolower(c)=='m') { // If we're still in an img tag
  670. Internal = &FilterChainUrlDecode::Img2; // Go to Img2 mode.
  671. AddToBfr(c); // Write the byte to our buffer.
  672. } else { // If we didn't match
  673. DecodeBfr[0] = 0; // we clear out the Decode
  674. DecodeBfr[1] = 0; // buffer and go back to
  675. DecodeBfr[2] = 0; // Bypass mode again.
  676. DecodeLength = 0;
  677. Internal = &FilterChainUrlDecode::Bypass;
  678. }
  679. return c; // Always return the byte.
  680. }
  681. unsigned char FilterChainUrlDecode::Img2() { // In Img2 mode...
  682. unsigned char c = FilterChain::GetByte(); // Get the raw byte.
  683. if(tolower(c)=='g') { // If we're still in an img tag
  684. Internal = &FilterChainUrlDecode::Root; // Go to Decode Root mode.
  685. AddToBfr(c); // Write the byte to our buffer.
  686. } else { // If we didn't match
  687. DecodeBfr[0] = 0; // we clear out the Decode
  688. DecodeBfr[1] = 0; // buffer and go back to
  689. DecodeBfr[2] = 0; // Bypass mode again.
  690. DecodeBfr[3] = 0;
  691. DecodeLength = 0;
  692. Internal = &FilterChainUrlDecode::Bypass;
  693. }
  694. return c; // Always return the byte.
  695. }
  696. unsigned char FilterChainUrlDecode::Root() { // While in Decode Root mode...
  697. unsigned char c = FilterChain::GetByte(); // Get the raw byte.
  698. AddToBfr(c); // Push it into the buffer.
  699. // Now we will switch modes based on the byte we get.
  700. if(c == '%') { // If we have '%' then it is
  701. Internal = &FilterChainUrlDecode::GetD1; // time to start decoding.
  702. } else
  703. if(c == '>') { // If we have '>' and
  704. if(DecodeFlag) { // we did some decoding then
  705. Internal = &FilterChainUrlDecode::Inject; // it is time to inject the result.
  706. } else { // If there was no decoding then
  707. Clear(); // we clear out our buffer and
  708. Internal = &FilterChainUrlDecode::Bypass; // it is time to go to sleep.
  709. }
  710. }
  711. // This next bit protects against malformed HTML by watching for any new tag
  712. // start. If one occurs, then we throw away our current decoding and assume a state
  713. // that starts with the new open "<".
  714. if(c == '<') { // If found a new < then we
  715. Clear(); // clear the buffer,
  716. AddToBfr(c); // Add the '<' back in, and
  717. Internal = &FilterChainUrlDecode::Tag; // go back to Tag mode.
  718. }
  719. return c; // Always return the byte.
  720. }
  721. unsigned char FilterChainUrlDecode::GetD1() { // Get the first digit.
  722. unsigned char c = FilterChain::GetByte(); // Read the raw byte.
  723. AddToBfr(c); // Add it to the buffer.
  724. Internal = &FilterChainUrlDecode::GetD2; // Move to GetD2 mode.
  725. return c; // Always return the byte.
  726. }
  727. // isHexDigit()
  728. // Returns true if i is a valid hex digit.
  729. bool FilterChainUrlDecode::isHexDigit(unsigned char i) {
  730. if(
  731. (i >= '0' && i <= '9') || // Hex digits must be 0-9 or
  732. (i >= 'A' && i <= 'F') || // A-F or
  733. (i >= 'a' && i <= 'f') // a-f if somebody used lower case.
  734. ) {
  735. return true; // If i is one of these we are true
  736. } else {
  737. return false; // IF i is not then we are false
  738. }
  739. }
  740. // convertHexDigit()
  741. // Returns an integer value for the hex digit i
  742. int FilterChainUrlDecode::convertHexDigit(unsigned char i) {
  743. if(i >= '0' && i <= '9') { // Digit chars convert directly.
  744. return i - '0';
  745. } else if (i >= 'A' && i <= 'F') { // Cap A-F convert to 10 - 15
  746. return i - 'A' + 10;
  747. } else if (i >= 'a' && i <= 'f') { // Small A-F convert to 10 - 15
  748. return i - 'a' + 10;
  749. }
  750. return -1; // Return -1 if i was not a hex digit!
  751. }
  752. // convertHexByte()
  753. // Returns an integer value for a hex string representing a byte.
  754. unsigned char FilterChainUrlDecode::convertHexByte(unsigned char* x) {
  755. unsigned char working = convertHexDigit(x[1]); // Convert the low order nybl.
  756. working = working + (16 * convertHexDigit(x[0])); // Convert the high order nybl.
  757. return working; // Return the result.
  758. }
  759. unsigned char FilterChainUrlDecode::GetD2() { // Get the second digit.
  760. unsigned char c = FilterChain::GetByte(); // Read the raw byte.
  761. AddToBfr(c); // Add it to the buffer.
  762. // At this point the end of our DecodeBfr has a c_str of a small hex integer (we hope)
  763. // that we can decode. If we successfully decode it then we will replace %xx in our
  764. // DecodeBfr with the character that is represented by that byte.
  765. // Do we really have an encoded byte to decode?
  766. int codepos = DecodeLength-3; // Grab the position of the hex.
  767. if(
  768. DecodeBfr[codepos]=='%' && // If the first char is %
  769. isHexDigit(DecodeBfr[codepos+1]) && // and the second is a hex digit
  770. isHexDigit(DecodeBfr[codepos+2]) // and the third is a hex digit
  771. ){ // then we can decode the string.
  772. unsigned char q = convertHexByte(DecodeBfr+codepos+1); // Decode the byte.
  773. if(q >= 32) { // If the byte is in range then
  774. DecodeBfr[codepos] = q; // Replace the % with the byte
  775. DecodeBfr[--DecodeLength] = 0; // backup over and erase the hex
  776. DecodeBfr[--DecodeLength] = 0; // digits themselves.
  777. DecodeFlag = true; // Set the decode flag.
  778. }
  779. // If we decided the byte was not decodable for some reason then the original data
  780. // remains in the buffer as it was originally read.
  781. }
  782. Internal = &FilterChainUrlDecode::Root; // Get ready to decode more.
  783. return c; // Always return the byte.
  784. }
  785. unsigned char FilterChainUrlDecode::Inject() { // Inject the decoded result.
  786. if(
  787. DecodeBfr[DecodePosition] && // If we've got more bytes
  788. DecodePosition < sizeof(DecodeBfr)) { // and we're safely in our buffer
  789. return DecodeBfr[DecodePosition++]; // then return the byte and move
  790. } // ahead.
  791. // Once the buffer is empty we
  792. Clear(); // clear out the system, and go
  793. Internal = &FilterChainUrlDecode::Bypass; // back to bypass mode. Then
  794. return GetByte(); // return the next bypassed byte.
  795. }
  796. ////////////////////////////////////////////////////////////////////////////////
  797. // FilterChainHeaderAnalysis
  798. ////////////////////////////////////////////////////////////////////////////////
  799. int FilterChainHeaderAnalysis::FollowPattern(char c) { // Follow the pattern.
  800. c = tolower(c); // Convert c to lower case.
  801. if(c != MatchPattern[MatchIndex]) { // If c doesn't match the pattern
  802. return -1; // then return -1 indicating we fell off.
  803. } else { // If it did match the pattern then
  804. MatchIndex++; // move ahead to the next byte and
  805. if(0 == MatchPattern[MatchIndex]) { // take a look. If that's all there was
  806. return 0; // then we've finished :-)
  807. }
  808. } // If we matched and there's more to do
  809. return 1; // then we return 1.
  810. }
  811. unsigned char FilterChainHeaderAnalysis::doSeekNL() { // Looking for a new line.
  812. unsigned char c = GetCheckedByte(); // Get the next byte (and check for high bits)
  813. if('\n' == c) { // If it was a new line then
  814. Mode = &FilterChainHeaderAnalysis::doSeekDispatch; // move on to the next mode
  815. } // for the next byte and
  816. return c; // return the byte we got.
  817. }
  818. unsigned char FilterChainHeaderAnalysis::doSeekDispatch() { // Looking at the first char after NL.
  819. unsigned char c = GetCheckedByte(); // Get the next byte (and check for high bits)
  820. switch(tolower(c)) { // Switch modes based on what this byte is.
  821. case '\n': { // If it is a New Line then the headers are
  822. Mode = &FilterChainHeaderAnalysis::doEndOfHeaders; // finished - so we set up our EndOfHeaders
  823. return GetByte(); // mode and return the next byte from there.
  824. break; // The extra NL will be emitted at the end.
  825. }
  826. case 'r': { // If it is an R as in (R)eceived:
  827. SetFollowPattern("eceived:"); // establish the follow pattern and
  828. Mode = &FilterChainHeaderAnalysis::doReceived; // switch to doReceived mode.
  829. break;
  830. }
  831. case 'f': { // If it is an F as in (F)rom:
  832. SetFollowPattern("rom:"); // establish the follow pattern and
  833. Mode = &FilterChainHeaderAnalysis::doFrom; // switch to doFrom mode.
  834. break;
  835. }
  836. case 't': { // If it is an T as in (T)o:
  837. SetFollowPattern("o:"); // establish the follow pattern and
  838. Mode = &FilterChainHeaderAnalysis::doTo; // switch to doTo mode.
  839. break;
  840. }
  841. case 'c': { // If it is a C as in (C)C:
  842. SetFollowPattern("c:"); // establish the follow pattern and
  843. Mode = &FilterChainHeaderAnalysis::doCC; // switch to doCC mode.
  844. break;
  845. }
  846. case 'm': { // If it is an M as in (M)essage-id:
  847. SetFollowPattern("essage-id:"); // establish the follow pattern and
  848. Mode = &FilterChainHeaderAnalysis::doMessageID; // switch to doMessageID mode.
  849. break;
  850. }
  851. case 'd': { // If it is a D as in (D)ate:
  852. SetFollowPattern("ate:"); // establish the follow pattern and
  853. Mode = &FilterChainHeaderAnalysis::doDate; // switch to doDate mode.
  854. break;
  855. }
  856. case 's': { // If it is an S as in (S)ubject:
  857. SetFollowPattern("ubject:"); // establish the follow pattern and
  858. Mode = &FilterChainHeaderAnalysis::doSubject; // switch to doSubject mode.
  859. break;
  860. }
  861. default: { // If we don't recognize the byte then
  862. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for a new line.
  863. break;
  864. }
  865. } // Once all of our mode switching is handled
  866. return c; // we return the byte we got.
  867. }
  868. unsigned char FilterChainHeaderAnalysis::doReceived() { // Identifying a Received: header.
  869. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  870. switch(FollowPattern(c)) { // See if we're still on the path.
  871. case -1: { // If we're not on the right tag then
  872. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  873. break;
  874. }
  875. case 0: { // If we've found the end of our tag (match!)
  876. Mode = &FilterChainHeaderAnalysis::doFindIP; // start looking for the IP.
  877. IPToTest = ""; // Clear the IPToTest buffer.
  878. break;
  879. }
  880. default: { // If we're still following along then
  881. break; // keep on keepin' on.
  882. }
  883. } // Once we know what we're doing we
  884. return c; // return the character we got.
  885. }
  886. unsigned char FilterChainHeaderAnalysis::doFindIP() { // Seeking the [IP] in a Received header.
  887. unsigned char c = GetCheckedByte(); // Get a checked byte.
  888. switch(c) {
  889. case '[': { // If we find the [ then
  890. Mode = &FilterChainHeaderAnalysis::doTestIP; // set up to grab and test the IP.
  891. break;
  892. }
  893. case '\n': { // If we come across a newline then
  894. Mode = &FilterChainHeaderAnalysis::doSeekNL; // we must be lost so go back to basics.
  895. break;
  896. }
  897. default: { // For anything else we keep on going.
  898. break;
  899. }
  900. }
  901. return c; // Return the byte.
  902. }
  903. //// 20070614 _M Improved IP exctaction from received headers so that if the
  904. //// apparent IP contains any unusual bytes (not digits or dots) then the
  905. //// attempt is abandoned.
  906. unsigned char FilterChainHeaderAnalysis::doTestIP() { // Gets and tests the [IP].
  907. unsigned char c = FilterChain::GetByte(); // Get the next byte.
  908. switch(c) {
  909. case ']': { // If we come to ] we've got it!
  910. IPTester.test(IPToTest, IPTestResult); // Do the test with this IP.
  911. if(0 == IPTestResult.length()) { // If the IP test wants us to truncate
  912. throw Empty("FilterChainHeaderAnalysis: Truncate"); // the message then throw Empty!
  913. } // Otherwise, proceed as per normal...
  914. SetOutputBuffer(IPTestResult); // Put the result in the output buffer.
  915. Mode = &FilterChainHeaderAnalysis::doInjectIPTestResult; // Set the mode to inject the result.
  916. break; // That will start on the next byte.
  917. }
  918. case '0': // IPs are made of digits and dots.
  919. case '1':
  920. case '2':
  921. case '3':
  922. case '4':
  923. case '5':
  924. case '6':
  925. case '7':
  926. case '8':
  927. case '9':
  928. case '.': { // Capture the IP between [ and ]
  929. IPToTest += c; // one byte at a time.
  930. break;
  931. }
  932. default: { // If we find anything else we must be
  933. Mode = &FilterChainHeaderAnalysis::doSeekNL; // lost so we go back to the basics.
  934. break;
  935. }
  936. }
  937. return c;
  938. }
  939. unsigned char FilterChainHeaderAnalysis::doFrom() { // Identifying a From: header.
  940. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  941. switch(FollowPattern(c)) { // See if we're still on the path.
  942. case -1: { // If we're not on the right tag then
  943. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  944. break;
  945. }
  946. case 0: { // If we've found the end of our tag (match!)
  947. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  948. FoundFrom = true; // record that this tag was present.
  949. break;
  950. }
  951. default: { // If we're still following along then
  952. break; // keep on keepin' on.
  953. }
  954. } // Once we know what we're doing we
  955. return c; // return the character we got.
  956. }
  957. unsigned char FilterChainHeaderAnalysis::doTo() { // Identifying a To: header.
  958. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  959. switch(FollowPattern(c)) { // See if we're still on the path.
  960. case -1: { // If we're not on the right tag then
  961. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  962. break;
  963. }
  964. case 0: { // If we've found the end of our tag (match!)
  965. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  966. FoundTo = true; // record that this tag was present.
  967. break;
  968. }
  969. default: { // If we're still following along then
  970. break; // keep on keepin' on.
  971. }
  972. } // Once we know what we're doing we
  973. return c; // return the character we got.
  974. }
  975. unsigned char FilterChainHeaderAnalysis::doCC() { // Identifying a CC: header.
  976. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  977. switch(FollowPattern(c)) { // See if we're still on the path.
  978. case -1: { // If we're not on the right tag then
  979. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  980. break;
  981. }
  982. case 0: { // If we've found the end of our tag (match!)
  983. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  984. FoundCC = true; // record that this tag was present.
  985. break;
  986. }
  987. default: { // If we're still following along then
  988. break; // keep on keepin' on.
  989. }
  990. } // Once we know what we're doing we
  991. return c; // return the character we got.
  992. }
  993. unsigned char FilterChainHeaderAnalysis::doMessageID() { // Identifying a MessageID header.
  994. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  995. switch(FollowPattern(c)) { // See if we're still on the path.
  996. case -1: { // If we're not on the right tag then
  997. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  998. break;
  999. }
  1000. case 0: { // If we've found the end of our tag (match!)
  1001. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  1002. FoundMessageID = true; // record that this tag was present.
  1003. break;
  1004. }
  1005. default: { // If we're still following along then
  1006. break; // keep on keepin' on.
  1007. }
  1008. } // Once we know what we're doing we
  1009. return c; // return the character we got.
  1010. }
  1011. unsigned char FilterChainHeaderAnalysis::doDate() { // Identifying a Date: header.
  1012. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  1013. switch(FollowPattern(c)) { // See if we're still on the path.
  1014. case -1: { // If we're not on the right tag then
  1015. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  1016. break;
  1017. }
  1018. case 0: { // If we've found the end of our tag (match!)
  1019. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  1020. FoundDate = true; // record that this tag was present.
  1021. break;
  1022. }
  1023. default: { // If we're still following along then
  1024. break; // keep on keepin' on.
  1025. }
  1026. } // Once we know what we're doing we
  1027. return c; // return the character we got.
  1028. }
  1029. unsigned char FilterChainHeaderAnalysis::doSubject() { // Identifying a Subject: header.
  1030. unsigned char c = FilterChain::GetByte(); // Get the next byte of the header tag.
  1031. switch(FollowPattern(c)) { // See if we're still on the path.
  1032. case -1: { // If we're not on the right tag then
  1033. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to looking for the next one.
  1034. break;
  1035. }
  1036. case 0: { // If we've found the end of our tag (match!)
  1037. Mode = &FilterChainHeaderAnalysis::doSeekNL; // start looking for the the next tag and
  1038. FoundSubject = true; // record that this tag was present.
  1039. break;
  1040. }
  1041. default: { // If we're still following along then
  1042. break; // keep on keepin' on.
  1043. }
  1044. } // Once we know what we're doing we
  1045. return c; // return the character we got.
  1046. }
  1047. unsigned char FilterChainHeaderAnalysis::doEndOfHeaders() { // IdentifyEndOfHeaders & Emit Results.
  1048. // We know we've reached the end of the headers so now
  1049. // we have to formulate the results we want to inject and
  1050. // er... inject them.
  1051. EndOfHeaderResults = "X-SNFHDR: "; // Emit an X header (internal only)
  1052. if(MissingCC()) { EndOfHeaderResults.append("-CC "); } // Emit -CC if no CC header.
  1053. if(MissingTo()) { EndOfHeaderResults.append("-TO "); } // Emit -TO if no TO header (together no to)
  1054. if(MissingFrom()) { EndOfHeaderResults.append("-FROM "); } // Emit -FROM if no FROM header.
  1055. if(MissingDate()) { EndOfHeaderResults.append("-DATE "); } // Emit -DATE if no DATE header.
  1056. if(MissingMessageID()) { EndOfHeaderResults.append("-MESSAGEID "); } // Emit -MESSAGEID if no MESSAGE-ID header.
  1057. if(MissingSubject()) { EndOfHeaderResults.append("-SUBJECT "); } // Emit -SUBJECT if no SUBJECT header.
  1058. if(HighBitCharacters()) { EndOfHeaderResults.append("+HIGHBIT"); } // Emit +HIGHBIT if non-ascii chars present.
  1059. EndOfHeaderResults.append("\n\n"); // Emit the double newline - end of headers.
  1060. SetOutputBuffer(EndOfHeaderResults); // Setup the output string.
  1061. Mode = &FilterChainHeaderAnalysis::doInjectAnalysis; // Switch to the output injection mode.
  1062. return GetByte(); // Return the first byte from there :-)
  1063. }
  1064. void FilterChainHeaderAnalysis::SetOutputBuffer(string& s) { // Setup the OutputBuffer.
  1065. OutputBuffer = (char*) s.c_str(); OutputIndex = 0; // Capture the c_str and reset the index.
  1066. }
  1067. unsigned char FilterChainHeaderAnalysis::doInjectIPTestResult() { // Inject OutputBuffer and go to doSeekNL.
  1068. unsigned char c = OutputBuffer[OutputIndex++]; // Get the next byte in the output buffer.
  1069. if(0 == c) { // If it is the null terminator then we
  1070. Mode = &FilterChainHeaderAnalysis::doSeekNL; // go back to seeking lines and return that
  1071. return GetByte(); // byte instead.
  1072. } // If we have a normal byte then we
  1073. return c; // return it.
  1074. }
  1075. unsigned char FilterChainHeaderAnalysis::doInjectAnalysis() { // Inject OutputBuffer and go to doOff.
  1076. unsigned char c = OutputBuffer[OutputIndex++]; // Get the next byte in the output buffer.
  1077. if(0 == c) { // If it is the null terminator then we
  1078. Mode = &FilterChainHeaderAnalysis::doOff; // go back to seeking lines and return that
  1079. return GetByte(); // byte instead.
  1080. } // If we have a normal byte then we
  1081. return c; // return it.
  1082. }