您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SNFMilter.cpp 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. // SNFMilter.cpp
  2. // Copyright (C) 2008 ARM Research Labs, LLC.
  3. // See www.armresearch.com for the copyright terms.
  4. //
  5. // This file contains the "guts" of the SNFMilter interface. Specifically,
  6. // the SNFMilter() function.
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <errno.h>
  10. #include <unistd.h>
  11. #include <grp.h>
  12. #include "SNFMulti.hpp"
  13. #include "configuration.hpp"
  14. #include "SNFMilter.hpp"
  15. #include "config.h"
  16. #include <syslog.h>
  17. #include <sstream>
  18. #if SMFI_VERSION > 3
  19. #define NEW_LIBMILTER
  20. #endif
  21. SNFMilterContextPool* MilterContexts = 0; // The global contexts handle.
  22. bool MilterDebugMode; // True if debug mode is on.
  23. sfsistat SkipReturn = SMFIS_CONTINUE; // libmilter return value when further
  24. // callbacks of the same type are to be skipped.
  25. /// Get the connection context object.
  26. //
  27. // \param[in] Ctx is the libmilter context object.
  28. //
  29. // \returns the pointer to the connection context object.
  30. //
  31. // \throws runtime_error if the obtained pointer is 0.
  32. //
  33. SNFMilterContext*
  34. getContextFromCtx(SMFICTX* Ctx) {
  35. SNFMilterContext* Context = (SNFMilterContext*) smfi_getpriv(Ctx); // Get the context object.
  36. if(0 == Context) throw runtime_error("Got NULL from smfi_getpriv()");
  37. return Context;
  38. }
  39. /// Get a new connection object and assign it to the context.
  40. //
  41. // \param[in] Ctx is the libmilter context object.
  42. //
  43. // \returns the pointer to the connection context object.
  44. //
  45. // \throws runtime_error if the obtained pointer is 0.
  46. //
  47. SNFMilterContext*
  48. assignContextToCtx(SMFICTX* Ctx) {
  49. SNFMilterContext* Context = MilterContexts->grab(); // Get any existing context object.
  50. if(0 == Context) // Check address.
  51. throw runtime_error("Got NULL from MilterContexts->grab()");
  52. smfi_setpriv(Ctx, Context); // Save the context object.
  53. Context->ConnectionData.clear(); // Clear the connection context object.
  54. return Context;
  55. }
  56. // Function to output an info message.
  57. void logInfo(const string ContextName, int Code, std::string Message) {
  58. cout << ContextName << " (code " << Code << "): " << Message << endl;
  59. #if 0
  60. syslog(LOG_MAIL | LOG_DEBUG, "%s", Message.c_str()); // Output to system mail log.
  61. #endif
  62. MilterContexts->logThisInfo(ContextName, Code, Message); // Log message.
  63. }
  64. // Function to output an error message.
  65. void logError(const string &ContextName, const int &Code, const std::string &Message) {
  66. cout << ContextName << " (code " << Code << "): " << Message << endl;
  67. #if 0
  68. syslog(LOG_MAIL | LOG_DEBUG, "%s", Message.c_str()); // Output to system mail log.
  69. #endif
  70. MilterContexts->logThisError(ContextName, Code, Message); // Log message.
  71. }
  72. class ResultActionHandler : public Configurator {
  73. private:
  74. SNFMilterEngine* Target;
  75. public:
  76. ResultActionHandler(SNFMilterEngine* T) : Target(T) {}
  77. void operator()(ConfigurationElement& E, ConfigurationData& D) {
  78. Target->setResultAction(
  79. Code,
  80. (Action >= Allow && Action <= Quarantine) ?
  81. static_cast<SNFMilterAction>(Action)
  82. : Allow
  83. );
  84. }
  85. int Code;
  86. int Action;
  87. };
  88. const int NoSuchCode = -1; // Magic number for no such code
  89. const int NoSuchAction = -1; // Magic number for no such action
  90. void SNFMilterEngine::readConfiguration() { // Parse the configuration.
  91. string NewConfiguration = myRulebase->PlatformConfiguration(); // Get the latest configuration.
  92. if(0 != RunningConfiguration.compare(NewConfiguration)) { // If it does not match, read it!
  93. RunningConfiguration = NewConfiguration; // Capture the latest.
  94. for(int i = 1; i < ResultCodesCount; i++) ResultActions[i] = NoAction; // Init Result/Action config.
  95. ResultActions[0] = Allow;
  96. NonZeroAction = NoAction; // NoAction if no configuration for
  97. // non-zero result.
  98. ResultActionHandler ResultActionConfigurator(this); // Create a Result/Action handler.
  99. ConfigurationElement Reader("milter"); // Create a configuration reader.
  100. Reader
  101. .Element("connect")
  102. .Element("white")
  103. .Attribute("action", reinterpret_cast<int&>(WhiteAction), static_cast<int>(Allow))
  104. .Mnemonic("Allow", AllowActionMnemonic)
  105. .Mnemonic("Accept", AcceptActionMnemonic)
  106. .Mnemonic("Retry", RetryActionMnemonic)
  107. .Mnemonic("Reject", RejectActionMnemonic)
  108. .Mnemonic("Discard", DiscardActionMnemonic)
  109. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  110. .End("white")
  111. .Element("caution")
  112. .Attribute("action", reinterpret_cast<int&>(CautionAction), static_cast<int>(Allow))
  113. .Mnemonic("Allow", AllowActionMnemonic)
  114. .Mnemonic("Accept", AcceptActionMnemonic)
  115. .Mnemonic("Retry", RetryActionMnemonic)
  116. .Mnemonic("Reject", RejectActionMnemonic)
  117. .Mnemonic("Discard", DiscardActionMnemonic)
  118. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  119. .End("caution")
  120. .Element("black")
  121. .Attribute("action", reinterpret_cast<int&>(BlackAction), static_cast<int>(Allow))
  122. .Mnemonic("Allow", AllowActionMnemonic)
  123. .Mnemonic("Accept", AcceptActionMnemonic)
  124. .Mnemonic("Retry", RetryActionMnemonic)
  125. .Mnemonic("Reject", RejectActionMnemonic)
  126. .Mnemonic("Discard", DiscardActionMnemonic)
  127. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  128. .End("black")
  129. .Element("truncate")
  130. .Attribute("action", reinterpret_cast<int&>(TruncateAction), static_cast<int>(Allow))
  131. .Mnemonic("Allow", AllowActionMnemonic)
  132. .Mnemonic("Accept", AcceptActionMnemonic)
  133. .Mnemonic("Retry", RetryActionMnemonic)
  134. .Mnemonic("Reject", RejectActionMnemonic)
  135. .Mnemonic("Discard", DiscardActionMnemonic)
  136. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  137. .End("truncate")
  138. .End("connect")
  139. .Element("scan")
  140. .Element("result")
  141. .atEndCall(ResultActionConfigurator)
  142. .Attribute("code", ResultActionConfigurator.Code, NoSuchCode)
  143. .Attribute("action", ResultActionConfigurator.Action, NoSuchAction)
  144. .Mnemonic("Allow", AllowActionMnemonic)
  145. .Mnemonic("Accept", AcceptActionMnemonic)
  146. .Mnemonic("Retry", RetryActionMnemonic)
  147. .Mnemonic("Reject", RejectActionMnemonic)
  148. .Mnemonic("Discard", DiscardActionMnemonic)
  149. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  150. .End("result")
  151. .Element("nonzero")
  152. .Attribute("action", reinterpret_cast<int&>(NonZeroAction), static_cast<int>(NoAction))
  153. .Mnemonic("Allow", AllowActionMnemonic)
  154. .Mnemonic("Accept", AcceptActionMnemonic)
  155. .Mnemonic("Retry", RetryActionMnemonic)
  156. .Mnemonic("Reject", RejectActionMnemonic)
  157. .Mnemonic("Discard", DiscardActionMnemonic)
  158. .Mnemonic("Quarantine", QuarantineActionMnemonic)
  159. .End("nonzero")
  160. .End("scan")
  161. .End("milter");
  162. ConfigurationData ConfigurationData( // Convert our configuration string
  163. NewConfiguration.c_str(), // to a configuration data buffer.
  164. NewConfiguration.length());
  165. Reader.initialize(); // Initialize the defaults.
  166. Reader.interpret(ConfigurationData); // Read the new configuration.
  167. }
  168. }
  169. void SNFMilterEngine::setResultAction(int Result, SNFMilterAction Action) { // Set a result / action pair.
  170. if(
  171. 0 <= Result &&
  172. ResultCodesCount > Result // If the Result code is in
  173. ) { ResultActions[Result] = Action; } // range then set the action.
  174. }
  175. void SNFMilterEngine::checkConfiguration() { // Reload the config if it is old.
  176. if(ConfigurationCheckTime.isExpired()) readConfiguration();
  177. }
  178. SNFMilterEngine::SNFMilterEngine(snf_RulebaseHandler* R) : // Construct the engine.
  179. myRulebase(R), // Remember our rulebase.
  180. myEngine(0), // We need to set this later.
  181. WhiteAction(Allow), // Initialize our default actions.
  182. CautionAction(Allow),
  183. BlackAction(Allow),
  184. TruncateAction(Allow),
  185. ConfigurationCheckTime(ConfigurationLifetime)
  186. {
  187. myEngine = new snf_EngineHandler(); // Create an engine handler.
  188. myEngine->open(myRulebase); // Connect it to the rulebase.
  189. readConfiguration(); // Read our configuration.
  190. }
  191. SNFMilterEngine::~SNFMilterEngine() { // Destroy the engine.
  192. try {
  193. ScopeMutex EngineLock(ConfigMutex); // Don't die while scanning.
  194. if(myEngine) { // If we're not dead then die.
  195. myEngine->close(); // Close the engine.
  196. delete myEngine; // Delete it.
  197. myEngine = 0; // Forget it.
  198. myRulebase = 0; // Forget (don't delete) this too.
  199. }
  200. }
  201. catch(...) {} // Silently capture exceptions.
  202. }
  203. SNFMilterAction SNFMilterEngine::scanIP(unsigned long int IP) { // Scans an IP.
  204. IPTestRecord Tester(IP); // Make up a test record for this IP.
  205. ScopeMutex ConfigurationLock(ConfigMutex); // Lock our configuration.
  206. if(0 == myEngine) throw runtime_error("Null engine when scanning IP"); // Skip safely if we're down.
  207. checkConfiguration(); // Re-read our config if it is old.
  208. myRulebase->performIPTest(Tester); // Tun it past the engine.
  209. SNFMilterAction TestResult = Allow; // Allow by default.
  210. switch(Tester.R) { // Convert the result to an action.
  211. case White: { TestResult = WhiteAction; break; } // If the IP scan range is recognized
  212. case Caution: { TestResult = CautionAction; break; } // in our configuration then we will
  213. case Black: { TestResult = BlackAction; break; } // return the action code that is
  214. case Truncate: { TestResult = TruncateAction; break; } // configured. Otherwise we will return
  215. default: break;
  216. } // the default "Allow" action.
  217. return TestResult; // Tell them what we've got.
  218. }
  219. SNFMilterAction SNFMilterEngine::scanMessage( // Scans a message.
  220. const unsigned char* bfr, // Requires a pointer to the buffer.
  221. int length) { // Requires the buffer length.
  222. ScopeMutex ConfigurationLock(ConfigMutex); // Lock the configuration.
  223. if(0 == myEngine) throw runtime_error("Null engine when scanning message"); // Skip safely if we're down.
  224. checkConfiguration(); // Re-read our config if it is old.
  225. int R = myEngine->scanMessage(bfr, length, "", 0); // Scan the message & get the result.
  226. if(0 > R || ResultCodesCount <= R) return Error; // If R is out of range, return Error.
  227. if (0 == R || NoAction != ResultActions[R]) return ResultActions[R]; // Return the translated action.
  228. return NonZeroAction;
  229. }
  230. string SNFMilterEngine::XHeaders() { // Return X headers from last scan.
  231. ScopeMutex EngineLock(ConfigMutex); // Use myEngine safely.
  232. if(0 == myEngine) return ""; // Return no headers if dead.
  233. return myEngine->getXHDRs(); // Simply return them.
  234. }
  235. //// SNFMilterContext
  236. SNFMilterContext::SNFMilterContext(snf_RulebaseHandler *myRulebase) :
  237. milterEngine(myRulebase),
  238. MessageData(MailBufferReserveSize) {}
  239. SNFMilterContext::~SNFMilterContext() {}
  240. /// Return the local received header.
  241. //
  242. // \returns the local received header.
  243. //
  244. string
  245. SNFMilterContext::getLocalReceivedHeader() {
  246. string locHeader;
  247. locHeader = "Received: from <" + ConnectionData.HostName;
  248. locHeader += "> [" + (string) ConnectionData.HostIP;
  249. locHeader += "] by " PACKAGE_NAME;
  250. return locHeader;
  251. }
  252. /// Map return value from SNFMilterEngine scan to libmilter return value.
  253. //
  254. // \param[in] MilterAction is the return from an SNFMilterEngine scan.
  255. //
  256. // \returns the return value for the libmilter callback.
  257. //
  258. // \throws std::out_of_range if MilterAction of out of range.
  259. //
  260. sfsistat
  261. SNFMilterContext::smfisReturn(SNFMilterAction MilterAction) {
  262. static const sfsistat ReturnValue[] = {
  263. SMFIS_CONTINUE,
  264. SMFIS_ACCEPT,
  265. SMFIS_TEMPFAIL,
  266. SMFIS_REJECT,
  267. SMFIS_DISCARD,
  268. SMFIS_CONTINUE
  269. };
  270. if ( (MilterAction < 0) || (MilterAction >= NMilterActions) ) {
  271. ostringstream Temp;
  272. Temp << "Illegal value of SNFMilterAction in SNFMilterContext::smfisReturn ("
  273. << MilterAction << ") while processing message from "
  274. << MessageData.SenderAddress
  275. << " (connection from " << ConnectionData.HostName << " ("
  276. << (string) ConnectionData.HostIP << ").";
  277. throw std::out_of_range(Temp.str());
  278. }
  279. return ReturnValue[MilterAction];
  280. }
  281. //// SNFMilterContextPool
  282. SNFMilterContextPool::SNFMilterContextPool(snf_RulebaseHandler* Rulebase) : // Ctor needs a live rulebase handler.
  283. myRulebase(Rulebase), // Capture the rulebase handler.
  284. MilterSocketPort(0) {
  285. string NewConfiguration = myRulebase->PlatformConfiguration(); // Get the latest configuration.
  286. ConfigurationElement Reader("milter"); // Create a configuration reader.
  287. Reader
  288. .Element("socket")
  289. .Attribute("type", reinterpret_cast<int&>(MilterSocketType), static_cast<int>(NOMilterSocket))
  290. .Mnemonic("unix", UNIXMilterSocketMnemonic)
  291. .Mnemonic("tcp", TCPMilterSocketMnemonic)
  292. .Attribute("path", MilterSocketPath, "")
  293. .Attribute("group", MilterSocketGroup, "")
  294. .Attribute("ip", MilterSocketIP, "")
  295. .Attribute("port", MilterSocketPort, 0)
  296. .End("socket")
  297. .End("milter");
  298. ConfigurationData ConfigurationData( // Convert our configuration string
  299. NewConfiguration.c_str(), // to a configuration data buffer.
  300. NewConfiguration.length());
  301. Reader.initialize(); // Initialize the defaults.
  302. Reader.interpret(ConfigurationData); // Read the new configuration.
  303. switch (MilterSocketType) { // Named pipe.
  304. case UNIXMilterSocket:
  305. if (0 == MilterSocketPath.size()) { // Path specified?
  306. ostringstream Temp; // No.
  307. Temp << "Path needs to be specified for socket type \"unix\"";
  308. throw runtime_error(Temp.str());
  309. }
  310. if ( (0 != MilterSocketIP.size()) || // These should not be specified.
  311. (0 != MilterSocketPort) ) {
  312. ostringstream Temp;
  313. Temp << "IP (" << MilterSocketIP << ") and/or port (" << MilterSocketPort
  314. << ") were specified for socket type \"unix\". They should not be specified.";
  315. throw runtime_error(Temp.str());
  316. }
  317. break;
  318. case TCPMilterSocket:
  319. if (0 == MilterSocketIP.size()) { // IP/host specified?
  320. ostringstream Temp; // No.
  321. Temp << "Host or IP address needs to be specified for socket type \"inet\"";
  322. throw runtime_error(Temp.str());
  323. }
  324. if (0 == MilterSocketPort) { // Port specified?
  325. ostringstream Temp; // No.
  326. Temp << "Port needs to be specified for socket type \"inet\"";
  327. throw runtime_error(Temp.str());
  328. }
  329. if ( (0 != MilterSocketPath.size()) || // These should not be specified.
  330. (0 != MilterSocketGroup.size()) ) {
  331. ostringstream Temp;
  332. Temp << "Path (" << MilterSocketPath << ") and/or group (" << MilterSocketGroup
  333. << ") were specified for socket type \"inet\". They should not be specified.";
  334. throw runtime_error(Temp.str());
  335. }
  336. break;
  337. case NOMilterSocket:
  338. {
  339. ostringstream Temp;
  340. Temp << "The required <socket> element was not present in the configuration file.";
  341. throw runtime_error(Temp.str());
  342. }
  343. break;
  344. default:
  345. {
  346. ostringstream Temp;
  347. Temp << "The type of the <socket> element configuration file is invalid. "
  348. "The type must by \"unix\" or \"inet\"";
  349. throw runtime_error(Temp.str());
  350. }
  351. }
  352. }
  353. SNFMilterSocketType SNFMilterContextPool::getSocketType() {
  354. return MilterSocketType;
  355. }
  356. string SNFMilterContextPool::getSocketPath() { return MilterSocketPath; }
  357. string SNFMilterContextPool::getSocketGroup() { return MilterSocketGroup; }
  358. string SNFMilterContextPool::getSocketIP() { return MilterSocketIP; }
  359. int SNFMilterContextPool::getSocketPort() { return MilterSocketPort; }
  360. SNFMilterContextPool::~SNFMilterContextPool() { // Dtor gracefully discards contexts.
  361. ScopeMutex ContextPoolLock(ContextAllocationControl); // Lock the context allocation system.
  362. myRulebase = 0; // Forget our rulebase. We're dead.
  363. for( // Loop through the context pool
  364. vector<SNFMilterContext*>::iterator iC = ContextPool.begin(); // and delete any contexts we have
  365. iC != ContextPool.end(); // allocated.
  366. iC++) { delete (*iC); }
  367. }
  368. SNFMilterContext* SNFMilterContextPool::grab() { // Get a context to use.
  369. ScopeMutex ContextPoolLock(ContextAllocationControl); // Lock the context allocation system.
  370. if(0 == myRulebase) return 0; // No contexts left if we're dead.
  371. if(1 > AvailableContexts.size()) { // If we need more contexts then
  372. SNFMilterContext* N = new SNFMilterContext(myRulebase); // Create a new context,
  373. ContextPool.push_back(N); // add it to the pool,
  374. AvailableContexts.give(N); // and make it available.
  375. }
  376. return AvailableContexts.take(); // Return the next avialable context.
  377. }
  378. void SNFMilterContextPool::drop(SNFMilterContext* E) { // Drop a context after use.
  379. // Update context state.
  380. E->State = SNFMilterContext::Pooled;
  381. AvailableContexts.give(E); // Make this context available.
  382. }
  383. bool SNFMilterContextPool::allUnused() {
  384. return (AvailableContexts.size() == ContextPool.size());
  385. }
  386. void SNFMilterContextPool::logThisError(string ContextName, int Code, string Text) {
  387. myRulebase->logThisError(ContextName, Code, Text);
  388. }
  389. void SNFMilterContextPool::logThisInfo(string ContextName, int Code, string Text) {
  390. myRulebase->logThisInfo(ContextName, Code, Text);
  391. }
  392. // End of configuration setup and engine and context interface components
  393. ////////////////////////////////////////////////////////////////////////////////
  394. ////////////////////////////////////////////////////////////////////////////////
  395. // SNFMilter callback definitions, constants, and global data.
  396. extern "C" {
  397. // Connection callback.
  398. //
  399. // This callback is invoked when a new connection is made to the
  400. // MTA. It obtains an available connection context object if one
  401. // hasn't already been assigned, and saves the IP address and name
  402. // of the connecting MTA. Next, it performs an IP scan, and
  403. // returns the appropriate response.
  404. //
  405. // Returns: SMFIS_CONTINUE, SMFIS_ACCEPT, SMFIS_TEMPFAIL, or
  406. // SMFIS_REJECT according to the following mapping:
  407. //
  408. // IPScanResult return mlfi_connect return
  409. //
  410. // Quarantine, Discard, Error FailSafeMilterResponse
  411. //
  412. // Anything else SNFMilterContext::smfisReturn(IPScanResult)
  413. //
  414. sfsistat
  415. mlfi_connect(SMFICTX *Ctx, char *HostName, _SOCK_ADDR *HostAddr)
  416. {
  417. const string ContextName = PACKAGE_NAME "::mlfi_connect";
  418. int ErrorCode = 1;
  419. int InfoCode = 1;
  420. sfsistat CallbackResult = FailSafeMilterResponse;
  421. try {
  422. SNFMilterContext *Context = assignContextToCtx(Ctx); // Get the existing context object,
  423. // or assign a new context object.
  424. Context->State = SNFMilterContext::Connect; // Update context state.
  425. sockaddr_in *SaIn = (sockaddr_in *) HostAddr; // Fetch the IP address.
  426. Context->ConnectionData.HostName = HostName; // Load the info.
  427. Context->ConnectionData.HostIP = ntohl(SaIn->sin_addr.s_addr);
  428. if (MilterDebugMode) {
  429. ostringstream Temp;
  430. Temp << "Connect from " << Context->ConnectionData.HostName << " ("
  431. << (string) Context->ConnectionData.HostIP << ").";
  432. logInfo(ContextName, InfoCode, Temp.str());
  433. }
  434. SNFMilterAction IpScanResult; // Perform IP scan.
  435. IpScanResult = Context->milterEngine.scanIP(Context->ConnectionData.HostIP);
  436. if (MilterDebugMode) {
  437. ostringstream Temp;
  438. Temp << "IP scan result for connection from "
  439. << Context->ConnectionData.HostName << " ("
  440. << (string) Context->ConnectionData.HostIP << "): " << IpScanResult << ".";
  441. logInfo(ContextName, InfoCode, Temp.str());
  442. }
  443. if ( (Error == IpScanResult) || // Check for error
  444. (Quarantine == IpScanResult) ||
  445. (Discard == IpScanResult) ) {
  446. std::ostringstream Temp; // Illegal result.
  447. Temp << "Illegal result from IP scan for "
  448. << (string) Context->ConnectionData.HostIP
  449. << ": " << IpScanResult;
  450. throw std::runtime_error(Temp.str());
  451. }
  452. CallbackResult = Context->smfisReturn(IpScanResult); // Load return value.
  453. } catch (exception &E) {
  454. logError(ContextName, ErrorCode, E.what());
  455. } catch (...) {
  456. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  457. }
  458. return CallbackResult;
  459. }
  460. //
  461. // HELO callback.
  462. //
  463. // This callback is invoked when the connecting MTA sends a HELO
  464. // message. It saves the argument of the HELO command in the
  465. // connection context object.
  466. //
  467. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  468. // otherwise.
  469. //
  470. sfsistat
  471. mlfi_helo(SMFICTX *Ctx, char *heloHost)
  472. {
  473. const string ContextName = PACKAGE_NAME "::mlfi_helo";
  474. int ErrorCode = 1;
  475. int InfoCode = 1;
  476. sfsistat CallbackResult = FailSafeMilterResponse;
  477. try {
  478. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  479. Context->State = SNFMilterContext::Helo; // Update context state.
  480. Context->ConnectionData.HostHelo = heloHost; // Save the helo host name.
  481. if (MilterDebugMode) {
  482. ostringstream Temp;
  483. Temp << "HELO " << Context->ConnectionData.HostHelo << " from "
  484. << Context->ConnectionData.HostName << " ("
  485. << (string) Context->ConnectionData.HostIP << ").";
  486. logInfo(ContextName, InfoCode, Temp.str());
  487. }
  488. CallbackResult = SMFIS_CONTINUE; // Load return value.
  489. } catch (exception &E) {
  490. logError(ContextName, ErrorCode, E.what());
  491. } catch (...) {
  492. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  493. }
  494. return CallbackResult;
  495. }
  496. //
  497. // envfrom callback.
  498. //
  499. // This callback is invoked to process the envelope from line of the
  500. // mail message. It clears the message buffer, and adds the local
  501. // received header to the message buffer to scan. The local received
  502. // header is added to the email message in mlfi_eom.
  503. //
  504. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  505. // otherwise.
  506. //
  507. sfsistat
  508. mlfi_envfrom(SMFICTX *Ctx, char **argv)
  509. {
  510. const string ContextName = PACKAGE_NAME "::mlfi_envfrom";
  511. int ErrorCode = 1;
  512. int InfoCode = 1;
  513. sfsistat CallbackResult = FailSafeMilterResponse;
  514. try {
  515. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  516. Context->State = SNFMilterContext::EnvFrom; // Update context state.
  517. Context->MessageData.clear(); // This is the beginning of a new message.
  518. // Clear data from any previous message.
  519. if (MilterDebugMode) {
  520. Context->MessageData.SenderAddress = argv[0];
  521. ostringstream Temp;
  522. Temp << "Processing sender address " << Context->MessageData.SenderAddress
  523. << " (connection from " << Context->ConnectionData.HostName << " ("
  524. << (string) Context->ConnectionData.HostIP << ")).\n";
  525. logInfo(ContextName, InfoCode, Temp.str());
  526. }
  527. CallbackResult = SMFIS_CONTINUE; // Load return value.
  528. } catch (exception &E) {
  529. logError(ContextName, ErrorCode, E.what());
  530. } catch (...) {
  531. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  532. }
  533. return CallbackResult;
  534. }
  535. //
  536. // envrcpt callback.
  537. //
  538. // This callback is invoked to process the envelope receipt line of
  539. // the mail message.
  540. //
  541. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  542. // otherwise.
  543. //
  544. sfsistat
  545. mlfi_envrcpt(SMFICTX *Ctx, char **argv)
  546. {
  547. const string ContextName = PACKAGE_NAME "::mlfi_envrcpt";
  548. int ErrorCode = 1;
  549. int InfoCode = 1;
  550. sfsistat CallbackResult = FailSafeMilterResponse;
  551. try {
  552. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  553. // Update context state.
  554. Context->State = SNFMilterContext::EnvRcpt;
  555. if (MilterDebugMode) {
  556. ostringstream Temp;
  557. Temp << "Processing recipient " << argv[0] << " for message from "
  558. << Context->MessageData.SenderAddress
  559. << " (connection from " << Context->ConnectionData.HostName << " ("
  560. << (string) Context->ConnectionData.HostIP << ")).";
  561. logInfo(ContextName, InfoCode, Temp.str());
  562. }
  563. CallbackResult = SMFIS_CONTINUE; // Load return value.
  564. } catch (exception &E) {
  565. logError(ContextName, ErrorCode, E.what());
  566. } catch (...) {
  567. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  568. }
  569. return CallbackResult;
  570. }
  571. //
  572. // header callback.
  573. //
  574. // This callback is invoked to process the a header line of the mail
  575. // message. It writes the header line + SMTPENDL to the message buffer
  576. // that is scanned.
  577. //
  578. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  579. // otherwise.
  580. //
  581. sfsistat
  582. mlfi_header(SMFICTX *Ctx, char *headerf, char *headerv)
  583. {
  584. const string ContextName = PACKAGE_NAME "::mlfi_header";
  585. int ErrorCode = 1;
  586. int InfoCode = 1;
  587. sfsistat CallbackResult = FailSafeMilterResponse;
  588. try {
  589. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  590. Context->State = SNFMilterContext::Header; // Update context state.
  591. if (MilterDebugMode) {
  592. ostringstream Temp;
  593. Temp << "Processing header '" << headerf << ": " << headerv
  594. << "' for message from "
  595. << Context->MessageData.SenderAddress
  596. << " (connection from " << Context->ConnectionData.HostName << " ("
  597. << (string) Context->ConnectionData.HostIP << ")).";
  598. logInfo(ContextName, InfoCode, Temp.str());
  599. }
  600. Context->MessageData.MessageBuffer += headerf; // Add the header.
  601. Context->MessageData.MessageBuffer += ": ";
  602. Context->MessageData.MessageBuffer += headerv;
  603. Context->MessageData.MessageBuffer += SMTPENDL;
  604. CallbackResult = SMFIS_CONTINUE; // Load return value.
  605. } catch (exception &E) {
  606. logError(ContextName, ErrorCode, E.what());
  607. } catch (...) {
  608. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  609. }
  610. return CallbackResult;
  611. }
  612. //
  613. // End of header callback.
  614. //
  615. // This callback is invoked after the last header of the mail
  616. // message is sent. It writes SMTPENDL SMTPENDL to the message
  617. // buffer that is scanned.
  618. //
  619. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  620. // otherwise.
  621. //
  622. sfsistat
  623. mlfi_eoh(SMFICTX *Ctx)
  624. {
  625. const string ContextName = PACKAGE_NAME "::mlfi_eoh";
  626. int ErrorCode = 1;
  627. int InfoCode = 1;
  628. sfsistat CallbackResult = FailSafeMilterResponse;
  629. try {
  630. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  631. Context->State = SNFMilterContext::EOH; // Update context state.
  632. Context->MessageData.MessageBuffer += SMTPENDL + SMTPENDL; // Add the blank lines..
  633. if (MilterDebugMode) {
  634. ostringstream Temp;
  635. Temp << "All headers received for message from "
  636. << Context->MessageData.SenderAddress
  637. << " (connection from " << Context->ConnectionData.HostName << " ("
  638. << (string) Context->ConnectionData.HostIP << ")). Message buffer--\n'"
  639. << Context->MessageData.MessageBuffer << "'.";
  640. logInfo(ContextName, InfoCode, Temp.str());
  641. }
  642. CallbackResult = SMFIS_CONTINUE; // Load return value.
  643. } catch (exception &E) {
  644. logError(ContextName, ErrorCode, E.what());
  645. } catch (...) {
  646. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  647. }
  648. return CallbackResult;
  649. }
  650. //
  651. // message body callback.
  652. //
  653. // This callback is invoked zero or more times to send the body of the
  654. // mail message is sent. It writes the body to the message buffer that
  655. // is scanned.
  656. //
  657. // Returns: SMFIS_CONTINUE if more of the message body is needed,
  658. // SkipReturn if more of the message body is not needed, or
  659. // FailSafeMilterResponse if an error occurs. Context is the
  660. // connection context object.
  661. //
  662. sfsistat
  663. mlfi_body(SMFICTX *Ctx, unsigned char *Bodyp, size_t Bodylen)
  664. {
  665. const string ContextName = PACKAGE_NAME "::mlfi_body";
  666. int ErrorCode = 1;
  667. int InfoCode = 1;
  668. sfsistat CallbackResult = FailSafeMilterResponse;
  669. try {
  670. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  671. Context->State = SNFMilterContext::Body; // Update context state.
  672. if (Context->MessageData.MessageBuffer.size() >= // Return if there is enough in the
  673. MailBufferReserveSize) { // message buffer.
  674. return SkipReturn;
  675. }
  676. if (Context->MessageData.MessageBuffer.size() < // Do we need to copy this?
  677. MailBufferReserveSize) {
  678. string::size_type NCharToTransfer = MailBufferReserveSize - // Yes. How much more?
  679. Context->MessageData.MessageBuffer.size();
  680. if (NCharToTransfer > Bodylen) { // Don't transfer more characters
  681. // than are available.
  682. NCharToTransfer = Bodylen;
  683. }
  684. Context->MessageData.MessageBuffer.append((const char *) Bodyp, // Append the message.
  685. NCharToTransfer);
  686. if (MilterDebugMode) {
  687. ostringstream Temp;
  688. Temp << "Appended " << NCharToTransfer << " bytes to "
  689. << "message from " << Context->MessageData.SenderAddress
  690. << " (connection from " << Context->ConnectionData.HostName << " ("
  691. << (string) Context->ConnectionData.HostIP << ")). Message length: "
  692. << Context->MessageData.MessageBuffer.size() << ".";
  693. logInfo(ContextName, InfoCode, Temp.str());
  694. }
  695. } else {
  696. if (MilterDebugMode) {
  697. ostringstream Temp;
  698. Temp << "Discarded " << Bodylen << " bytes "
  699. << "message from " << Context->MessageData.SenderAddress
  700. << " (connection from " << Context->ConnectionData.HostName << " ("
  701. << (string) Context->ConnectionData.HostIP << ")) because "
  702. << MailBufferReserveSize << " bytes have already been "
  703. << "transferred. Message length: "
  704. << Context->MessageData.MessageBuffer.size() << ".";
  705. logInfo(ContextName, InfoCode, Temp.str());
  706. }
  707. }
  708. CallbackResult = SMFIS_CONTINUE; // Load return value.
  709. } catch (exception &E) {
  710. logError(ContextName, ErrorCode, E.what());
  711. } catch (...) {
  712. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  713. }
  714. return CallbackResult;
  715. }
  716. //
  717. // End-Of-Message callback.
  718. //
  719. // This callback is invoked to when the entire message has been sent
  720. // to SNFMilter. It adds the local received header to the email
  721. // message, and then scans the message body. If the scan result
  722. // indicates that the message is to be quarantined, then the message
  723. // is set to be quarantined (using smfi_quarantine).
  724. //
  725. // Returns: SMFIS_CONTINUE, SMFIS_ACCEPT, SMFIS_TEMPFAIL, or
  726. // SMFIS_DISCARD, SMFIS_REJECT, or FailSafeMilterResponse
  727. // according to the following mapping:
  728. //
  729. // MessageScan return mlfi_connect return
  730. //
  731. // Error FailSafeMilterResponse
  732. //
  733. // Anything else SNFMilterContext::smfisReturn(IPScanResult)
  734. //
  735. // Side effect: If the MessageScan result is Quarantine, the
  736. // message is quarantined using smfi_quarantine().
  737. //
  738. sfsistat
  739. mlfi_eom(SMFICTX *Ctx)
  740. {
  741. const string ContextName = PACKAGE_NAME "::mlfi_eom";
  742. int ErrorCode = 1;
  743. int InfoCode = 1;
  744. sfsistat CallbackResult = FailSafeMilterResponse;
  745. try {
  746. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  747. Context->State = SNFMilterContext::EOM; // Update context state.
  748. if (MilterDebugMode) {
  749. ostringstream Temp;
  750. Temp << "End of message from " << Context->MessageData.SenderAddress
  751. << " (connection from " << Context->ConnectionData.HostName << " ("
  752. << (string) Context->ConnectionData.HostIP << ")).";
  753. logInfo(ContextName, InfoCode, Temp.str());
  754. }
  755. if (PrependLocalReceivedHeader) {
  756. Context->MessageData.MessageBuffer.
  757. insert(0, Context->getLocalReceivedHeader() + SMTPENDL); // Prepend local received header line
  758. // to the message buffer.
  759. }
  760. SNFMilterAction MsgScanResult; // Perform scan.
  761. MsgScanResult =
  762. Context->milterEngine.scanMessage((unsigned char *) Context->MessageData.MessageBuffer.c_str(),
  763. Context->MessageData.MessageBuffer.size());
  764. if (MilterDebugMode) {
  765. ostringstream Temp;
  766. Temp << "Message scan result for message from " << Context->MessageData.SenderAddress
  767. << " (connection from " << Context->ConnectionData.HostName << " ("
  768. << (string) Context->ConnectionData.HostIP << ")): " << MsgScanResult << ".";
  769. logInfo(ContextName, InfoCode, Temp.str());
  770. }
  771. if (Error == MsgScanResult) { // Check for scan error
  772. // Illegal result.
  773. std::ostringstream Temp;
  774. Temp << "Illegal message scan result for message from "
  775. << Context->MessageData.SenderAddress
  776. << " (connection from " << Context->ConnectionData.HostName << " ("
  777. << (string) Context->ConnectionData.HostIP << ")): " << MsgScanResult;
  778. throw std::runtime_error(Temp.str());
  779. }
  780. string XHeaders = Context->milterEngine.XHeaders(); // Fetch X-headers to submit.
  781. MailHeaders MailHeadersParse; // Object to parse X-headers.
  782. MailHeadersParse.loadHeaders(XHeaders); // Load the headers to be parsed.
  783. string HeaderName; // Name of X-header.
  784. string HeaderBody; // Body of X-header, formatted for libmilter.
  785. while (MailHeadersParse.getNameBody(&HeaderName, &HeaderBody)) { // While there is an X-Header...
  786. if (MilterDebugMode) {
  787. ostringstream Temp;
  788. Temp << "Processed X-Header for message from " << Context->MessageData.SenderAddress
  789. << " (connection from " << Context->ConnectionData.HostName << " ("
  790. << (string) Context->ConnectionData.HostIP << ")). X-Header name: '"
  791. << HeaderName << "'. X-Header body: '" << HeaderBody << "'.";
  792. logInfo(ContextName, InfoCode, Temp.str());
  793. }
  794. if (MI_SUCCESS != smfi_addheader(Ctx, // Add header to the email message.
  795. (char *) HeaderName.c_str(),
  796. (char *) HeaderBody.c_str())) {
  797. ostringstream Temp;
  798. Temp << "Error adding X-header to message from " << Context->MessageData.SenderAddress
  799. << " (connection from " << Context->ConnectionData.HostName << " ("
  800. << (string) Context->ConnectionData.HostIP
  801. << ")).\nX-Header name: '" << HeaderName << "'. X-Header body--\n'"
  802. << HeaderBody << "'.";
  803. logError(ContextName, 1, Temp.str());
  804. }
  805. }
  806. if (Quarantine == MsgScanResult) { // Quarantine the message?
  807. if (MilterDebugMode) {
  808. ostringstream Temp;
  809. Temp << "Quarantining message from " << Context->MessageData.SenderAddress
  810. << " (connection from " << Context->ConnectionData.HostName << " ("
  811. << (string) Context->ConnectionData.HostIP << ")).";
  812. logInfo(ContextName, InfoCode, Temp.str());
  813. }
  814. if (MI_SUCCESS != smfi_quarantine(Ctx,
  815. (char *) "Quarantined by " PACKAGE_NAME)) {
  816. ostringstream Temp;
  817. Temp << "Error quarantining message from "
  818. << Context->MessageData.SenderAddress
  819. << " (connection from " << Context->ConnectionData.HostName << " ("
  820. << (string) Context->ConnectionData.HostIP << ")).";
  821. logError(ContextName, 1, Temp.str());
  822. }
  823. return SMFIS_CONTINUE;
  824. }
  825. CallbackResult = Context->smfisReturn(MsgScanResult); // Load return value.
  826. } catch (exception &E) {
  827. logError(ContextName, ErrorCode, E.what());
  828. } catch (...) {
  829. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  830. }
  831. return CallbackResult;
  832. }
  833. //
  834. // Callback for aborting the message.
  835. //
  836. // This callback is invoked to when the processing of the current
  837. // message is to be aborted. It logs the abort as an info event,
  838. // clears the email message buffer, and sets the state to
  839. // connected.
  840. //
  841. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  842. // otherwise.
  843. //
  844. sfsistat
  845. mlfi_abort(SMFICTX *Ctx)
  846. {
  847. const string ContextName = PACKAGE_NAME "::mlfi_abort";
  848. int ErrorCode = 1;
  849. int InfoCode = 1;
  850. sfsistat CallbackResult = FailSafeMilterResponse;
  851. try {
  852. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  853. Context->State = SNFMilterContext::Connect; // Update context state.
  854. ostringstream Temp; // Log message.
  855. Temp << "Aborted processing of message from " << Context->MessageData.SenderAddress
  856. << " (connection from " << Context->ConnectionData.HostName << " ("
  857. << (string) Context->ConnectionData.HostIP << ")).";
  858. logInfo(ContextName, InfoCode, Temp.str());
  859. Context->MessageData.clear(); // Clear data for this message.
  860. CallbackResult = SMFIS_CONTINUE; // Load return value.
  861. } catch (exception &E) {
  862. logError(ContextName, ErrorCode, E.what());
  863. } catch (...) {
  864. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  865. }
  866. return CallbackResult;
  867. }
  868. //
  869. // Callback for closing the connection.
  870. //
  871. // This callback is invoked to when the connection with the remote MTA is closed.
  872. // It returns the connection context object to the pool.
  873. //
  874. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  875. // otherwise.
  876. //
  877. sfsistat
  878. mlfi_close(SMFICTX *Ctx)
  879. {
  880. const string ContextName = PACKAGE_NAME "::mlfi_close";
  881. int ErrorCode = 1;
  882. int InfoCode = 1;
  883. sfsistat CallbackResult = FailSafeMilterResponse;
  884. try {
  885. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  886. Context->State = SNFMilterContext::Close; // Update context state.
  887. if (MilterDebugMode) {
  888. ostringstream Temp;
  889. Temp << "Closing connection from "
  890. << Context->ConnectionData.HostName << " ("
  891. << (string) Context->ConnectionData.HostIP << ").";
  892. logInfo(ContextName, InfoCode, Temp.str());
  893. }
  894. MilterContexts->drop(Context); // Return the context object.
  895. smfi_setpriv(Ctx, 0);
  896. CallbackResult = SMFIS_CONTINUE; // Load return value.
  897. } catch (exception &E) {
  898. logError(ContextName, ErrorCode, E.what());
  899. } catch (...) {
  900. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  901. }
  902. return CallbackResult;
  903. }
  904. #ifdef NEW_LIBMILTER
  905. //
  906. // Callback for unknown SMTP command.
  907. //
  908. // This callback is invoked to when an unknown SMTP command is
  909. // received by the local MTA. The unknown command is logged.
  910. //
  911. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  912. // otherwise.
  913. //
  914. sfsistat
  915. mlfi_unknown(SMFICTX *Ctx, const char *Cmd)
  916. {
  917. const string ContextName = PACKAGE_NAME "::mlfi_unknown";
  918. int ErrorCode = 1;
  919. int InfoCode = 1;
  920. sfsistat CallbackResult = FailSafeMilterResponse;
  921. try {
  922. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  923. ostringstream Temp; // Log.
  924. Temp << "Unknown SMTP command from "
  925. << Context->ConnectionData.HostName << " ("
  926. << (string) Context->ConnectionData.HostIP << "): '"
  927. << *Cmd << "'";
  928. logInfo(ContextName, InfoCode, Temp.str());
  929. CallbackResult = SMFIS_CONTINUE; // Load return value.
  930. } catch (exception &E) {
  931. logError(ContextName, ErrorCode, E.what());
  932. } catch (...) {
  933. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  934. }
  935. return CallbackResult;
  936. }
  937. //
  938. // data callback.
  939. //
  940. // This callback is invoked when the connecting MTA sends a DATA
  941. // message.
  942. //
  943. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  944. // otherwise.
  945. //
  946. sfsistat
  947. mlfi_data(SMFICTX *Ctx)
  948. {
  949. const string ContextName = PACKAGE_NAME "::mlfi_data";
  950. int ErrorCode = 1;
  951. int InfoCode = 1;
  952. sfsistat CallbackResult = FailSafeMilterResponse;
  953. try {
  954. SNFMilterContext *Context = getContextFromCtx(Ctx); // Get the context object.
  955. Context->State = SNFMilterContext::Data; // Update context state.
  956. if (MilterDebugMode) {
  957. ostringstream Temp;
  958. Temp << "DATA for message from "
  959. << Context->MessageData.SenderAddress
  960. << " (connection from " << Context->ConnectionData.HostName << " ("
  961. << (string) Context->ConnectionData.HostIP << ")).";
  962. logInfo(ContextName, InfoCode, Temp.str());
  963. }
  964. CallbackResult = SMFIS_CONTINUE; // Load return value.
  965. } catch (exception &E) {
  966. logError(ContextName, ErrorCode, E.what());
  967. } catch (...) {
  968. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  969. }
  970. return CallbackResult;
  971. }
  972. //
  973. // Callback for negotiating the capabilities of the MTA.
  974. //
  975. // This callback is invoked at the start of each SMTP connection.
  976. // It obtains an available connection context object if one hasn't
  977. // already been assigned, checks whether the MTA can accept an
  978. // SMFIS_SKIP return, and configures the connection context object
  979. // to return an acceptable value.
  980. //
  981. // Returns: SMFIS_CONTINUE if no error, FailSafeMilterResponse
  982. // otherwise.
  983. //
  984. sfsistat
  985. mlfi_negotiate(SMFICTX *Ctx,
  986. unsigned long F0,
  987. unsigned long F1,
  988. unsigned long F2,
  989. unsigned long F3,
  990. unsigned long *PF0,
  991. unsigned long *PF1,
  992. unsigned long *PF2,
  993. unsigned long *PF3)
  994. {
  995. const string ContextName = PACKAGE_NAME "::mlfi_negotiate";
  996. int ErrorCode = 1;
  997. int InfoCode = 1;
  998. sfsistat CallbackResult = SMFIS_ALL_OPTS;
  999. try {
  1000. bool AcceptsSkip = F1 & SMFIP_SKIP;
  1001. if (AcceptsSkip) { // MTA accepts SMFIS_SKIP return?
  1002. SkipReturn = SMFIS_SKIP; // Yes. Use SMFIS_SKIP.
  1003. } else {
  1004. SkipReturn = SMFIS_CONTINUE; // No. Use SMFIS_CONTINUE.
  1005. }
  1006. if (MilterDebugMode) {
  1007. ostringstream Temp; // Log message.
  1008. Temp << "MTA does " << (AcceptsSkip ? "" : "not ") << "accept SMFIS_SKIP.";
  1009. logInfo(ContextName, InfoCode, Temp.str());
  1010. }
  1011. CallbackResult = SMFIS_ALL_OPTS; // Load return value.
  1012. } catch (exception &E) {
  1013. logError(ContextName, ErrorCode, E.what());
  1014. } catch (...) {
  1015. logError(ContextName, ErrorCode, UnknownExceptionMessage);
  1016. }
  1017. return CallbackResult;
  1018. }
  1019. #endif
  1020. }
  1021. // End of SNFMilter callback definitions, constants, and global data.
  1022. ////////////////////////////////////////////////////////////////////////////////
  1023. ////////////////////////////////////////////////////////////////////////////////
  1024. // SNFMilter setup & run function.
  1025. // The runLibMilter function establishes the appropriate libmilter call backs and
  1026. // accepts calls from the MTA via libmilter until it is told to quit. When it
  1027. // is told to quit it gracefully closes down, reclaims any memory it allocated,
  1028. // and returns.
  1029. void runLibMilter(SNFMilterContextPool* Contexts, bool DebugMode) { // Run the milter 'til it's done.
  1030. MilterContexts = Contexts; // Save the pool of context objects.
  1031. MilterDebugMode = DebugMode; // Save the debug mode flag.
  1032. #if 0
  1033. if (MilterDebugMode) {
  1034. openlog(PACKAGE_NAME, LOG_PID | LOG_PERROR, LOG_MAIL); // Initialize system logging to log
  1035. // messages to mail file.
  1036. }
  1037. #endif
  1038. struct smfiDesc smfilter = { // Load structure containing callbacks.
  1039. (char *) PACKAGE_NAME, // Filter name.
  1040. SMFI_VERSION, // Version code -- do not change.
  1041. SMFIF_ADDHDRS | SMFIF_QUARANTINE, // Flags.
  1042. mlfi_connect, // Connection info callback.
  1043. mlfi_helo, // SMTP HELO command callback.
  1044. mlfi_envfrom, // Envelope sender callback.
  1045. mlfi_envrcpt, // Envelope recipient callback.
  1046. mlfi_header, // Header callback.
  1047. mlfi_eoh, // End of headers callback.
  1048. mlfi_body, // Body block callback.
  1049. mlfi_eom, // End of message callback.
  1050. mlfi_abort, // Message abort callback.
  1051. mlfi_close // Connection closed callback.
  1052. #ifdef NEW_LIBMILTER
  1053. ,
  1054. mlfi_unknown, // Unknown SMTP command callback.
  1055. mlfi_data, // DATA ccallback.
  1056. mlfi_negotiate // Negotiation at the start of each SMTP
  1057. #endif
  1058. // connection callback.
  1059. };
  1060. string MilterConnSpec;
  1061. switch (Contexts->getSocketType()) { // Configure the connection.
  1062. case UNIXMilterSocket:
  1063. MilterConnSpec = "unix:" + Contexts->getSocketPath(); // Generate the connection spec.
  1064. break;
  1065. case TCPMilterSocket:
  1066. {
  1067. ostringstream Temp;
  1068. Temp << "inet:" << Contexts->getSocketPort() << "@" // Generate the connection spec.
  1069. << Contexts->getSocketIP();
  1070. MilterConnSpec = Temp.str();
  1071. }
  1072. break;
  1073. default:
  1074. {
  1075. ostringstream Temp;
  1076. Temp << PACKAGE " internal error: Invalid socket type from SNFMilterContextPool.";
  1077. throw logic_error(Temp.str());
  1078. }
  1079. }
  1080. if (MI_FAILURE == smfi_setconn(const_cast<char *>(MilterConnSpec.c_str()))) {
  1081. ostringstream Temp;
  1082. Temp << "smfi_setconn failed with input \"" << MilterConnSpec << "\"";
  1083. throw std::runtime_error(Temp.str());
  1084. }
  1085. if (MI_FAILURE == smfi_register(smfilter)) { // Register the callbacks.
  1086. string msg = "smfi_register failed";
  1087. throw std::runtime_error(msg);
  1088. }
  1089. if (UNIXMilterSocket == Contexts->getSocketType()) {
  1090. if (MI_FAILURE == smfi_opensocket(true)) { // Create the named pipe.
  1091. ostringstream Temp;
  1092. Temp << "smfi_opensocket failed for \"" << MilterConnSpec << "\"";
  1093. throw std::runtime_error(Temp.str());
  1094. }
  1095. string MilterConnPath = Contexts->getSocketPath();
  1096. if (chmod(MilterConnPath.c_str(), // Set permissions.
  1097. S_IRUSR | S_IWUSR |
  1098. S_IRGRP | S_IWGRP) != 0) {
  1099. ostringstream Temp;
  1100. Temp << "Error setting permissions of " << MilterConnPath << ": "
  1101. << strerror(errno);
  1102. throw runtime_error(Temp.str());
  1103. }
  1104. string GroupName = Contexts->getSocketGroup();
  1105. if (0 != GroupName.size()) { // Was a group specified?
  1106. struct group *Group = getgrnam(GroupName.c_str()); // Get the ID of the group.
  1107. errno = 0;
  1108. if (NULL == Group) {
  1109. ostringstream Temp;
  1110. if (0 != errno) { // Error?
  1111. Temp << "Error obtaining the group ID of " << GroupName << ": "
  1112. << strerror(errno);
  1113. } else { // Group not found.
  1114. Temp << "Error obtaining the group ID of " << GroupName << ": "
  1115. << "No such group";
  1116. }
  1117. throw runtime_error(Temp.str());
  1118. }
  1119. if (chown(MilterConnPath.c_str(), // Set group.
  1120. -1,
  1121. Group->gr_gid) != 0) {
  1122. ostringstream Temp;
  1123. Temp << "Error setting group of " << MilterConnPath << " to "
  1124. << Group->gr_name << ": " << strerror(errno);
  1125. throw runtime_error(Temp.str());
  1126. }
  1127. }
  1128. }
  1129. if (MI_FAILURE == smfi_main()) { // Hand control to libmilter
  1130. string msg = "smfi_main failed";
  1131. throw std::runtime_error(msg);
  1132. }
  1133. const string ContextName = "--EXITING--";
  1134. int ErrorCode = 1;
  1135. int InfoCode = 1;
  1136. logInfo(ContextName, InfoCode, "Shutdown command received. Waiting for message processing to complete...");
  1137. Sleeper WaitATic;
  1138. try {
  1139. WaitATic.setMillisecondsToSleep(ShutdownWaitPeriod_ms); // Learn to wait.
  1140. }
  1141. catch(...) {
  1142. ostringstream Temp;
  1143. Temp << "Invalid value for ShutdownWaitPeriod_ms: " << ShutdownWaitPeriod_ms << ".";
  1144. throw out_of_range(Temp.str());
  1145. }
  1146. int iPeriod = 0; // Number of periods waited.
  1147. while (!MilterContexts->allUnused() && iPeriod < ShutdownPeriods) {
  1148. iPeriod++;
  1149. WaitATic(); // Wait a period.
  1150. }
  1151. if (!MilterContexts->allUnused()) {
  1152. logError(ContextName, ErrorCode, "Not all messages finished processing.");
  1153. }
  1154. logInfo(ContextName, InfoCode, "Exiting");
  1155. WaitATic(); // Wait for messages to be logged.
  1156. MilterContexts = 0; // Turn off.
  1157. }